ASP.NET checkbox losing value on postback due to JavaScript/jQuery array? - javascript

I have a simple asp:RadioButtonList within a form tag but for some reason it isn't keeping it's value on postback
Here's what I've got
<form runat="server">
<div class="Form">
<span class="FirstField">
<asp:RadioButtonList runat="server" ID="radiolist1" AutoPostBack="true" RepeatDirection="Horizontal">
<asp:ListItem Text="Yes" />
<asp:ListItem Text="No" />
</asp:RadioButtonList>
</span>
</div>
</form>
At the moment all I'm trying to do is get it to keep it's value on postback - it works in Safari but not in Firefox or Internet Explorer.
Any ideas?
Edit:
I've just found out that it is something to do with my javascript in the head of my page
$(document).ready(function() {
var originalValues = new Array();
$("input").focus(function() {
if (!originalValues[this.id]) {
originalValues[this.id] = $(this).val()
}
if ( $(this).val()==originalValues[this.id]) {
$(this).val('').css({'color': "#000", 'font-style': 'normal'});
}
$(this).css({'background-color':'#E8E8E8' });
});
$("input").blur(function() {
if ( $(this).attr("value")=="") {
$(this).val(originalValues[this.id]).css({'color': "#666", 'font-style': 'normal', 'font-weight': 'normal'});
}
$(this).css({'background-color':'#fff' });
});
});

I'm guessing you have some other input elements on your page which use this javascript.
Try specifying the type of input you want the javascript to run on:
$("input:text").focus(function() {
replace :text with the type you're using.

I have pasted your code in a newly created ASP.NET website and was able to retrieve the SelectedValue and SelectedIndex properties.
Are you using a custom adapter for rendering HTML? Please take a look at: ASP.Net RadioButton loses ViewState

Is ViewState enabled for page and control?
EnableViewState property for the page is set to true.
EnableViewState property for the control is set to true.
ViewStateMode property for the control is set to Enabled or inherits the Enabled setting.
http://msdn.microsoft.com/en-us/library/system.web.ui.page.enableviewstate.aspx
EDIT: you don't need to save the old "text" on a RadioButton (html=input type=radio), so you have to apply this function only on textboxes etc. I'm not so
familiar with jQuery, but you should be able to do this with a jQuery selector. Maybe with the :not-selector/function:
[untested]
$("input").not(input[type=radio]).focus(function() {

Related

Get/Set asp:textbox values from javascript

I'm not super familiar with javascript but I'm working on it, I'm trying to do a "same as billing address" type checkbox to fill some textboxes on the same form with data from other textboxes. I found a few solutions online but they weren't working for me. I'm probably overlooking something simple, but I've tried quite a few. Here's what I currently have:
function AutoFillBilling()
{
var text = document.getElementById("CustContact").Value;
alert(text);
}
The alert pops up, but just says undefined, I also tried $("#CustContact").Value to no avail. Below is the textbox I'm trying to access
<asp:Textbox runat="server" ID="CustContact" ClientIDMode="Static" type="text" placeholder="Contact" class="required"/>
What am I missing?
Properties begin with lowercase letters in JavaScript:
var text = document.getElementById("CustContact").value;
Additionally, while the ClientIDMode="Static" certainly should be explicitly setting the client-side id property, when debugging you may want to examine the HTML just to make sure. When using JavaScript, looking only at your server-side markup leaves you unnecessarily blind.
You can use it as such
<asp:CheckBox ID="Postal_Same_As_PermCheckBox" runat="server" onclick="copyPermAddress(this);" />
And JavaScript as
<script type="text/javascript">
function copyPermAddress(e) {
if (e.checked) {
document.getElementById('Postal_Adrs_Line_1TextBox').value = document.getElementById('Perm_Adrs_Line_1TextBox').value;
document.getElementById('Postal_City_VillageTextBox').value = document.getElementById('Perm_City_VillageTextBox').value;
} else {
document.getElementById("Postal_Adrs_Line_1TextBox").removeAttribute('readonly', 'readonly');
document.getElementById("Postal_City_VillageTextBox").removeAttribute('readonly', 'readonly');
}
}
In this example I am assuming that you are using client id mode as static on the controls mentioned in the JavaScript, if it is not then you may use <%# xxxx.ClientID%> blocks to access their IDs

Emptying dropdown list on event not working

I have two dropdown menus and a linkbutton:
<form name="OptionForm" method="post">
<p>
<label for="ddlLocJobPhOpt" class="ui-accessible">Location Job Phase</label>
<asp:DropDownList runat="server" ID="ddlLocJobPhOpt" data-mini="true"></asp:DropDownList>
</p>
<p>
<label for="ddlFrmnOpt" class="ui-accessible">Foreman</label>
<asp:DropDownList runat="server" ID="ddlFrmnOpt" data-mini="true"></asp:DropDownList>
</p>
<asp:LinkButton ID="lnkSelectOptions" data-icon="arrow-r" data-iconpos="right" runat="server" data-role="button" Class="custom-btn" data-inline="true" data-theme="c" data-transition="pop" UseSubmitBahavior="false" href="#" data-mini="true" OnClientClick="SelectOptions()">GO</asp:LinkButton>
</form>
When I click the linkbutton this function fires: SelectOptions()
I am trying to empty the second dropdown list when the button is clicked. But when I add:
var frmnDDL = $('#ddlFrmnOpt');
frmnDDL.html("");
or
var frmnDDL = $('#ddlFrmnOpt');
frmnDDL.empty();
and then renavigate to the OptionForm above the dropdown is still populated.
What am I doing wrong?
I can almost guarantee that frmnDDL.length is 0.
.Net renames controls to something like ctl00_MainContent_ddlFrmnOpt
You have two options
you can change your jquery selector to the actual generated name (inspect the rendered html)
you can change your selector to do a partial match with something like $("[id$=ddlFrmnOpt]") or $("select[id$=ddlFrmnOpt]")
After that there are many ways to empty the select
frmnDDL.empty();
frmnDDL.children().remove();
frmnDDL.find('option').remove();
//etc, etc
Secondly, I'm confused by what you mean when you say "and then renavigate to the OptionForm above the dropdown is still populated." If you are performing a postback, .net will reload the dropdown with it's data during it's page lifecycle. What you changed in the DOM was client side, and with the web being stateless, those changes aren't remembered between postbacks.
As #CaffGeek pointed out, your issue is the fact that ASP.NET uses the control's parent hierarchy to determine the rendered ID. You can continue using the Javascript and jQuery code you already have by using static IDs for your controls.
Try
<asp:DropDownList runat="server" ClientIDMode="Static" ID="ddlLocJobPhOpt" data-mini="true"></asp:DropDownList>
and
<asp:DropDownList runat="server" ClientIDMode="Static" ID="ddlFrmnOpt" data-mini="true"></asp:DropDownList>
As of .NET 4, adding
ClientIdMode="Static"
to any server side control tells ASP.NET to render the exact ID that you specified in your markup instead of rendering it based on its legacy rules.
See http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientidmode(v=vs.110).aspx
Check this Fiddle
$('button').click(function(){
$('#mySelect option').each(function(){
$(this).remove();
});
});

Checkbox "Error: Unable to get value of the property 'checked': object is null or undefined"

I'm trying to resolve whether or not a checkbox is checked. It seems rather straight forward.
<script type="text/Javascript">
function ValidateReqNum() {
var zCheckBox = document.getElementById('chkAllJobs');
if (zCheckBox.checked)
alert("true");
if (!zCheckBox.checked)
alert("false");
return true;
}
</script>
and the checkbox:
<asp:CheckBox ID="chkAllJobs" runat="server" Text="All Jobs" />
called from:
<asp:Button ID="btnPrintReport" runat="server" Text="Run Report"
OnClientClick="return ValidateReqNum();" OnClick="CreatePDFJobReport" />
I've tried it dozens of different ways and it keeps coming back with
Error: Unable to get value of the property 'checked': object is null or undefined
My other elements in the same aspx page are reporting in just fine. I can call chkAllJobs from my c# code and I can resolve whether or not it's checked from c# as well.
If you are using master pages, control ids of child page at client will be different to their server ids. So instead of using server control name, try using its client id as;
var zCheckBox = document.getElementById('<%= chkAllJobs.ClientID %>');
function ValidateReqNum() {
alert(zCheckBox.checked);
}
Here is a sample how check-box work. If you have the following check-box:
<input id="Checkbox" type="checkbox" name="mycheckbox" value="5"/>
Then you can get the value using forms collection
label_Result.text = Request.Form["mycheckbox"];
Consequently, you will get the value 5 only if that checkbox is checked.

How Do I Pass ASP.NET Control Name to Javascript Function?

I have Googled this to death and found lots of 'answers', but none of them will work for me, so maybe you clever people could give me a 'definitive' answer?
I have a Javascript function:
function enableSaveLink() {
document.getElementById('<%= btnSaveLink.ClientID %>').removeAttribute('disabled');
}
This works fine, but obviously it is hard-coded to enable a particular control on my page. What I'd like is to be able to call this function from any control on the page, passing the name of the control I'd like to enable as a variable. So, in an ideal world, my Javascript function would look like this:
function enableControl(ctl) {
document.getElementById(ctl).removeAttribute('disabled');
}
And I'd call it like this:
<asp:button id="btnTestButton" runat="server" Text="Click Me" onclientclick="enableControl('txtTestTextbox') />
<asp:button id="txtTestTextbox" runat="server" enabled="false />
I know the way I've passed the control name would never work, but I've tried passing it in all different ways and none work, so this is just for the purposes of illustration. Can anyone tell me how to actually make this work?
You need to use the ClientID property of the control.
This will help:
<asp:button id="btnTest" runat="server" Text="Click Me"
onclientclick="enableControl('<%= lblTest.ClientID %>') />
Use the this reference (more info here):
<asp:button id="btnTest" runat="server" Text="Click Me" onclientclick="enableControl(this);" />
Then in your script:
function enableSaveLink(elem) {
elem.removeAttribute('disabled');
}
Here you are passing a reference to the object calling the function to the function, you can then just set the attribute on the element rather than finding it in the DOM.
EDIT - Just realised what your intended usage is. If you're looking to fire an event from a disabled element when clicked, then you can't do this from the element. It would need to be handled from some other enabled element. The above method works fine if you intend to disable the element when clicked - but not enable the element when clicked.
EDIT - Just to accompany my comment, if you have a uniform structure like this (i.e. where all inputs have a corresponding label - or even button) then:
<div>
<label onclick="activateSibling(this);">Input One:</label>
<input type="text" />
</div>
You could try this:
function activateSibling(label) {
label.nextSibling.removeAttribute("disabled");
}
I've made a jsFiddle demonstrating my concept in jQuery which seems to work fine.
EDIT - OK, last idea. What about custom attributes. You could add a target attribute to your clickable element which contains the Id you're going to enable, like so:
<label target="active_me" onclick="activate(this);">Click to activate</label>
<input type="text" id="active_me" disabled="disabled" />
And your script:
function activate(label) {
var inputId = this.getAttribute("target");
var input = document.getElementById(inputId);
input.removeAttribute("disabled");
}
Although, it's starting to feel like we're fighting against the technology a little and we're not too far removed from ctrlInput.ClientID. But I suppose this makes your markup a little cleaner and gives you a function that's bindable en masse.
Ok, I've cracked it. There are probably more ways than one to do this, but this is fairly elegant.
My Javascript function:
function enableControl(ctl) {
document.getElementById(ctl).removeAttribute('disabled');
}
My ASP.NET markup:
<asp:Button ID="btnTestButton" runat="server" Text="Click to enable" OnClientClick="enableControl('txtTestTextbox');" />
<asp:TextBox ID="txtTestTextBox" runat="server" enabled="false" ClientIDMode="Static" />
The key is the ClientIDMode property, which, when set to static, means that the control's client-side ID when it is rendered will match the ID you give it in markup. If it's within a naming container you may need to include that in the variable passed in the function call. See here for more info about ClientIDMode.
Anyway, this works for me! Thanks for your input, everyone.
ClientID is used for getting server side control on javascript.
var element=document.getElementById('<%=lblTest.ClientID%>');

How to set the text of a button using JScript?

I'm trying to set the text on a button in a JScript function. I am using a JScript function like this...
function myfunction(sender, eventArgs)
{
wanted_text = window.source_text_field.get_displayText();
if (document.getElementById("my_span_element") != null)
{
document.getElementById("my_span_element").innerText = wanted_text;
}
if (document.getElementById("my_button") != null)
{
document.getElementById("my_button").text = wanted_text;
}
}
where the controls concerned are define like this...
<span id="my_span_element" class="some_class"></span>
<asp:Button id="my_button"
runat="server"
class="some_other_class"
text=""
Width="48"
Height="25"
onclick="do_foo"/>
The text in the span element is set correctly but the button is unaffected. I've also tried innerText, Value, Text, and also attempted to use the answer to this question but to no avail.
Can anyone see what I have overlooked?
Change the .value attribute of button:
document.getElementById("my_button").value = "new value";
ASP.Net generates its own IDs for server controls.
You need to write <%= my_button.ClientID %> to get this generated ID.
There are 2 problems here:
First: you use wrong attribute - should be "value", instead of "text"
Second: document.getElementById("my_button") will not work because ASP.NET assigns it's own ids to controls. If you take a look at generated markup you will notice that id of the element is completely different.
If your javascript is inside of the same .aspx page as <asp:button /> control, you can do like this:
document.getElementById("<%= my_button.ClientID %>").value = "some text";

Categories

Resources