could any body explain me how can i save state of two list boxes on post back i am using jQuery of this kind i dont know on what event what should i do or where can i save view state or how can i use hiddenField to persist the state of both list box
<script language="javascript" type="text/javascript">
$(document).ready(function() {
//If you want to move selected item from fromListBox to toListBox
$("#add").click(function() {
$("#"+'<%= fromListBox.ClientID %>'+" option:selected").appendTo("#"+'<%=toListBox.ClientID %>');
});
//If you want to move all item from fromListBox to toListBox
$("#addAll").click(function() {
$("#"+'<%= fromListBox.ClientID %>'+" option").appendTo("#"+'<%=toListBox.ClientID %>');
});
//If you want to remove selected item from toListBox to fromListBox
$("#remove").click(function() {
$("#"+'<%=toListBox.ClientID %>'+" option:selected").appendTo("#"+'<%= fromListBox.ClientID %>');
});
//If you want to remove all items from toListBox to fromListBox
$("#removeAll").click(function() {
$("#"+'<%=toListBox.ClientID %>'+" option").appendTo("#"+'<%= fromListBox.ClientID %>');
});
});
</script>
<asp:ListBox ID="fromListBox" runat="server" SelectionMode="Multiple" Height="150px" Width="150px" >
<asp:ListItem Text="Student Enrollment ID" Value="enrollment_no"></asp:ListItem> <asp:ListItem Text="Student Name" Value="first_name"></asp:ListItem> <asp:ListItem Text="Last Name" Value="last_name"></asp:ListItem> <asp:ListItem Text="Father Name" Value="father_name"></asp:ListItem>
</asp:Listbox>
<asp:ListBox runat="server" ID="toListBox" ></asp:ListBox>
I think you just should use normal html listboxes, not asp.net server controls.
Here are some tips about it. And here you can find decent code for jquery that will move items beetween listboxes.
I think you have three options:
Use normal HTML listboxes, write some javascript code, and manipulate with them on server using standard POST request.
Use UpdatePanel with your listboxes (you'll eliminate page flickering and you probably wont have to use jQuery or rewrite your existing code)
Find or write your own control that uses javascript to move items and manage viewstate itself
I would use HTML listboxes (select elements) to avoid viewstate issues. It'll save you a lot of time.
Related
I've been trying to find a solution for hours now.
asp:textbox 1:
<asp:TextBox runat="server" ID="code" placeholder="<%$ Resources:ErrorMessages, EnterCode %>" CssClass="enterCode"></asp:TextBox><br />
asp:textbox 2:
<asp:TextBox runat="server" ID="code2" placeholder="<%$ Resources:ErrorMessages, EnterCode %>" CssClass="enterCode"></asp:TextBox><br />
button:
<asp:Button CssClass="btn btn-primary" runat="server" ID="buttonEnable2" OnClick="buttonEnable_Click" Text="<%$ Resources:UserMessages, Enable %>" />
I'm trying to copy text from textbox 2 into textbox 1.
textbox 2 is embedded in a jquery accordion in a bootstrap popover.
I've tried:
the simple one within aspx.cs:
code.text = code2.text;
some jquery within a javascript file linked to the aspx file:
$("#buttonEnable2").click(function () {
$('#code').val($('#code2').val());
alert('test');
});
the code above doesn't seem to work at all, it doesn't even give me an alert.
The problem is that you're using an accordion inside of a popover which clones everything inside the popover, coping the ID of everything. So when you type a value into the textbox it attaches it to the clone of the textbox, not the actual textbox.
here's the solution:
function clickEnable2() {
var txtBox1 = this.parentElement.getElementsByClassName("enterCode")[0].value;
$("#MainContent_code").val(txtBox1);
$("#MainContent_buttonEnable").click();
}
$("#MainContent_buttonEnable2").click(clickEnable2);
This Code is in javascript
<script>
function Copy() {
var n1 = document.getElementById('code');
var n2 = document.getElementById('code2');
n2.value = n1.value;
}
</script>
and your button should be like
<asp:Button CssClass="btn btn-primary" runat="server" ID="buttonEnable2" OnClientClick="Copy()" OnClick="buttonEnable_Click" Text="<%$ Resources:UserMessages, Enable %>" />
Hope it will help.
Your textboxes are of asp.net which changes the ID of textboxes with respect to its ContentPlaceHolder. So jquery is unable to find the textboxes.
You can use ClientIDMode="Static" so that ID of textboxes will not change. Put this property for the other textbox as well.
<asp:TextBox runat="server" ID="code" ClientIDMode="Static" placeholder="<%$ Resources:ErrorMessages, EnterCode %>" CssClass="enterCode"></asp:TextBox>
Then use jquery to copy text from one textbox to other.
$('#code').val($('#code2').val());
If you are using master pages, update panels etc in asp.net, the ID of the text box will be automatically replaced with a dynamic ID, hence you may need to do the following, this will help if you do not want to change the ClientIDMode to Static
First declare a javascript variable and assign your textbox's dynamic id's to it, for which the JQuery will be
$(document).ready(function(){
var txtBox1 = <%=code.ClientId%>;
var txtBox2 = <%=code2.ClientId%>;
});
Now you can use these two variables to copy your text into one another
$("#buttonEnable2").click(function () {
$('#' + txtBox1).val($('#' + txtBox2).val());
});
You can also use the document.getElementById in the following way.
var n1 = document.getElementById(<%=code.ClientId%>);
var n2 = document.getElementById(<%=code2.ClientId%>);
I hope this will help you.
Arg. Inheriting projects is SO much fun. Especially when they don't work well, and even more especially when they contain UpdatePanels...
I have a shipping address user control inside an UpdatePanel. We need to be able to process international addresses, so one thing I've done is show/hide the State dropdown depending on if the country selected is US or not. In addition, I have a RequiredFieldValidator on that dropdown.
When the user control is used on a normal page elsewhere in the application, everything is great. However, in the UpdatePanel, .NET is not seeing the RFV even though JavaScript does.
Address.ascx: (snipped)
<li class="form-list-question question-state">
<span class="form-label">
<asp:Label ID="lblState" runat="server" SkinID="FieldLabel" AssociatedControlID="ddlState" Text="State" /></span>
<asp:DropDownList ID="ddlState" runat="server" SkinID="State" DataSourceID="dsStates" AppendDataBoundItems="true" ViewStateMode="Enabled"
DataTextField="Name" DataValueField="Abbr" CssClass="required">
<asp:ListItem Text="" Value=""></asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="rfvState" runat="server" EnableClientScript="true" Display="None" ControlToValidate="ddlState"
ErrorMessage="State is required." ValidationGroup="Address" />
</li>
address.js: (snipped)
function SetFormByCountry() {
if (isUsTerritory()) {
$('.question-state').show();
if ($('#rfvState').length > 0) {
$('#rfvState').enabled = true;
}
} else {
$('.question-state').hide();
if ($('#rfvState').length > 0) {
$('#rfvState').enabled = false;
}
}
}
Current behavior: When a country other than the US is selected, the State dropdown disappears as appropriate, but when the form is submitted, validation still occurs on the now hidden dropdown. There are no JS errors created.
Expected behavior: Given the above scenario, the RequiredFieldValidator should be disabled and the form should post.
Have you tried using the ValidatorEnable function?
It's an ASP.Net javascript function that can be used to turn off client side validators; in your example, you should be able to do the following in your client side javascript (where you set the enabled property):
ValidatorEnable(document.getElementById('<%=rfvState.ClientID%>'), false);
My only other suggestion is to fire a async postback when the country is changed and remove the state validator server side.
I have the following markup. The errorPanel was first only used to show server side exception messages, and works fine like that. Now I'd like to incorporate my validation summary into that same errorPanel.
<asp:Panel ID="errorPanel" runat="server" CssClass="error" Visible="false">
<div style="float: right;">
Close</div>
<asp:Label ID="errorLabel" runat="server"></asp:Label>
<asp:ValidationSummary ID="validationSummary" runat="server" EnableClientScript="true" />
</asp:Panel>
<fieldset>
<legend>Create New Role</legend><asp:Label ID="newRoleNameLabel" runat="server" AssociatedControlID="newRoleNameText">Role Name:</asp:Label>
<asp:TextBox ID="newRoleNameText" runat="server" Width="100px"></asp:TextBox>
<asp:RequiredFieldValidator ID="newRoleNameRequired" runat="server" EnableClientScript="true" ControlToValidate="newRoleNameText" Display="Dynamic" ErrorMessage="Please enter a role name.">*</asp:RequiredFieldValidator>
<asp:Button ID="createButton" runat="server" Text="Create" OnClick="createButton_Click" />
</fieldset>
My problem now is that the required validation happens client side, and I want to keep that, so I have no server side opportunity to make errorPanel visible, in order to make the validation summary visible.
I see I have two options: Do validation server side, and use my code there to make the panel visible, or hook into the client side code somehow and catch an event there when the summary should be made visible, and then also make the errorPanel visible. How could I go about the latter?
Here is an approach which is really not recommended, but I had fun writing it, and it might lead you to some zany ideas!
(p.s. I am using jQuery to make life easier)
Take the Visible="false" off your asp:Panel, we'll do it all client side.
<asp:Panel ID="errorPanel" runat="server" CssClass="error">
Now, at document ready time we will hide the panel, and mess with ASP.NET's validation code.
$(document).ready(function () {
// This is more like it!
$("#<% =errorPanel.ClientID %>").hide();
eval('ValidatorCommonOnSubmit = ' + ValidatorCommonOnSubmit.toString().replace('return result;', 'myValidatorHook(result); return result;'));
});
That eval takes the ValidatorCommonOnSubmit() function which is generated by the ASP.NET validators, and modifies it in place so just before it returns its result, it calls myValidatorHook() with that result.
(see this StackOverflow question for where I got the idea)
Now, our hook:
function myValidatorHook(validated) {
if (validated) {
$("#<% =errorPanel.ClientID %>").hide();
}
else {
$("#<% =errorPanel.ClientID %>").show();
}
}
Simple enough - if the validator returned true (page validates), hide the panel; if it returned false (page did not validate), show it.
Use at your own risk! If the JavaScript generated by the ASP.NET validators changes, this will break horribly - but I did test it in ASP.NET 2.0, 3.5 and 4.0, and it worked the same in all three.
I had a similar problem where I had a containing div around a set of ASP validation fields, I wanted to only show the container if there was an error to show.
I used jQuery to hide the container as per Carson63000's answer, but then used jQuery to look at the visibility of the errors and show the container again if something was visible.
jQuery(function () {
jQuery(".checkout-validation").hide();
var show = false;
jQuery(".checkout-validation span").each(function () {
if (jQuery(this).css('display') != 'none' && jQuery(this).css('visibility') != 'hidden') {
show = true;
}
});
if (show == true) {
jQuery(".checkout-validation").show();
}
});
The only clarification other clarification I would add is that standard validation fields are set to visibility: hidden by default and Display="Dynamic" validations are display: none
Old question, but anyway.
I found one simple and clean solution to this. No server-side, no javascript needed.
You can simply put your content of errorPanel in HeaderText of ValidationSummary Control.
Like said on MSDN site:
The HeaderText property is not HTML encoded. Therefore, HTML tags can
be included in HeaderText.
Your example:
<asp:ValidationSummary ID="validationSummary" runat="server" EnableClientScript="true" CssClass="error"
HeaderText='<div style="float: right;">Close</div><span ID="errorLabel" runat="server"></span>'/>
<fieldset>
...
And PLBlum also nailed it on Microsoft asp.net forum:
I would like to set the focus on a textbox and/or control after clicking an asp label? Can some explain to me how to do this? Similar to doing a
<label for="txtBoxID">Blah</label>
You can also do this
<label for="<%=txtName.ClientID%>">Name:</label>
<asp:TextBox runat="server" ID="txtName"></asp:TextBox>
or on dot 4.
<label for="txtName">Name: </label>
<asp:TextBox runat="server" ID="txtName" ClientIDMode="Static"></asp:TextBox>
and avoid JavaScript.
This is the Best way to write and avoid javascript
<p>
<asp:Label ID="lblName" runat="server" AssociatedControlID="txtFirstName" Text="First Name: " />
<asp:TextBox ID="txtFirstName" runat="server" />
</p>
You can do it using Javascript or jQuery.
<label for="txtBoxID" onClientClick="SetMyFocus()">Blah</label>
<javascript>
function SetMyFocus()
{
document.getElementById("MyTextBox").focus();
}
</javascript>
If you have a specific need of doing something in the server side on the click of the label, you shall have to handle the same in code behind and then set the client side script to fire up after reloading the page. Use RegisterStartupScript for the same.
I'm assuming you want to do it completely on the client side to avoid a postback?
You can use jQuery to set focus. After adding a script reference to the jQuery library, you can use the following JavaScript in your page:
$(document).ready(function() {
$("#labelId").click(function() {
$("*[id$='txtBoxID']").focus()
});
});
The "*[id$='txtBoxID']" selector allows you to select the ASP.NET server side ID of your textbox without any additional code. Basically, it's saying "select any DOM element whose ID ends with txtBoxId."
You can add jQuery to your page with the following CDN script reference:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
A more generalized solution using jQuery:
$(document).ready(function() {
$("label[for]").click(function() {
var inputid = '#' + $(this).attr('for');
$(inputid).focus();
});
});
Should handle all labels, as long as you correctly define the for attribute.
I have a server side button as
<asp:Button ID="btnSummary" runat="server" OnClick="btnSummary_Click" Text="Next" />
I want to attach the jQuery Click event using its ID and NOT using the alternative class attribute way.
I tried to attach the click event as:
$("#btnSummary").click(function()
{
alert("1");
});
But, its click event is not fired. Also, I have also tried $("id[$btnSummary]").
Is there any way to attach the click event on asp:button using jQuery without the class attribute on the button?
Some of the options you have can be found here
How to stop ASP.NET from changing ids in order to use jQuery
EDIT:
After reading your comments on other answers, it sounds like you need to bind the onclick event handler inside of ASP.NET AJAX's pageLoad, so that it is bound on every postback, including asynchronous postbacks. On the other hand, $(document).ready() binds only once on initial page load
function pageLoad(sender, args)
{
$("#<%=btnSummary.ClientID %>").click(function()
{
alert("1");
});
}
Dave Ward wrote a nice article on the difference between pageLoad and $(document).ready().
Add ClientIDMode="Static" to your asp:button, something like this:
<asp:Button ID="Button1" runat="server" ClientIDMode="Static" Text="Button" />
This will make the ID remain the same. It disables the autogenerated names for this control.
Here is the reference for this: http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientid.aspx
Check if the id attribute is in the html source when you run the site.
Do you have the click function inside a document ready function ?
-
$(document).ready(function() {
// put all your jQuery goodness in here.
});
EDIT:
Since its a server side control and the ID changes, you will need to dynamically update the javascript on every page load with the variable.
ASP.NET generates a UniqueID for client-side stuff, you can use that to bind the event. That ID is generated based on the position of that Control inside a ControlCollection and different INamingContainers, it's ugly and you can't guess it...
Add this kind of code somewhere on your page to hook up that button.
<script type="text/javascript">
$(function() { $("#<%=btnSummary.ClientID%>") }).click(function(){/*...*/});
</script>
I'm little confused here now.
Let me explain:
1. I added a button on the page:
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" />
<div>
2. Then I added a JavaScript and jQuery:
<script type="text/javascript">
$(document).ready(function() {
$("#Button1").click(function() {
alert("Hello world!");
});
});
</script>
3. The generated html is this:
<div>
<input type="submit" name="Button1" value="Button" id="Button1" />
<div>
Now, I don't see ASP.NET (asp.net 3.5) changing the ids. Why do I see
different behavior?
Btw. This does work when I hit the button!
Thanks.
Assigning the selector to the class worked for me.
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="My Button" CssClass="myButton"/>
<script>
jQuery(".myButton").click(function () {
alert("clicked");
});
</script>
Please use the following syntax : $("[id*=Button1]") to reference any asp control
use pageLoad when using updatepanels because document.ready only runs once on initialization of the page and loses its binding on partial postbacks.
PageLoad gets run everytime so will rebind every partial postback.
I had the same problem, this works for me
<asp:Button ID="Button1" runat="server" Text="ASP Button" OnClientClick="return false;" />
Its the addition of return false that seems to make the difference. Hope this helps.
regards
Peter
ASP.NET adds to you id (example: id "selectButton" becomes
"ctl00_middleContent_gvPeople_ctl04_selectButton");
Use the jquery syntax to search for the part of the id that doesn't change.
$("[id='_selectButton']")
Please try below:
document.getElementById("<%=button1.ClientID %>").click();
Wrap this <asp:Button/> inside a html <div> container.
<div id="testG">
<asp:Button ID="btn1" runat="server" Text="TestButton" />
</div>
$(document).ready(function () {
$("#testG").click(function () {
alert("1");
//your code
});
});
You have reached there. There are two ways i guess,
Either inspect the control from Browser and See the Control ID, looks like ct1000_ btnSummary. use this ID on Click event of jQuery.
replace code
$("#ctl00_contentplcedholder_btnSummary").click(function()
{
alert("1");
});
Next one is quite easy just add an attribute ClientIdMode="static" to your control and use your actual Jquery click event it will fire.