why does textbox.disabled= true clears the text of the textbox? - javascript

I have a few asp:Textbox elements in my code, which I was disabling with javascript after the user clicks validate.
eg:
<asp:TextBox CssClass="dateClass" ID="fromDateE" width="100px" runat="server" Text=""></asp:TextBox>
My javascript function was :
function disableDateFields()
{
var dates = document.getElementsByClassName("dateClass");
for (var i = 0; i < dates.length; i++)
{
//console.log(dates[i]);
dates[i].disabled = true;
}
}
The problem I had was after submit the value I had inside the textbox was getting cleared.
To get around this problem I changed the JS function so instead of disabling I set the readOnly property of the text box to true :
function disableDateFields()
{
var dates = document.getElementsByClassName("dateClass");
for (var i = 0; i < dates.length; i++)
{
//console.log(dates[i]);
dates[i].readOnly= true;
}
}
I am just wondering why disabling the textbox clears out the value inside of it? Is this simply the default behavior or am I missing something?

In this case ViewState has nothing to do with this. The problem lies in the fact that disabled input controls are not part of the Form Post back to the server. But because the TextBox does still exists on the page asp.net will fill it with the values it receives from PostBack, but that one is null so the TextBox is made empty.
You can check this with the following snippet. You will see that fromDateE.UniqueID does not exists and thus fromDateE will be emptied.
if (Request.Form[fromDateE.UniqueID] == null)
{
fromDateE.Text = "Form Post was empty.";
}

Related

Trying to display variable value in confirm message: Javascript

I am trying to create a validation for a list of radio buttons, which, if successful, prompts a confirm box. The confirm box must state which button the user has selected, and then allow them to confirm.
The validation works, but when the popup box appears, I can't get the user's selection to display in the message, either by using checked or checked.value. Here's the code:
var checked = null;
var inputs = document.getElementsByName('levels');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
checked = inputs[i];
break;
}
}
if(checked==null)
{
alert('Please choose an exam level.');
return false;
}
else {
return confirm('You have chosen '+ checked + ', is this correct?');
}
Using this code, the message displayed is "You have chosen [object HTMLInputElement], is this correct?", regardless of which button is selected.
How do I correctly refer to the variable to avoid this?
You probably want checked = inputs[i].value. inputs[i] is the DOM Element, when cast to a string it becomes "[object HTMLInputElement]" (in case of an input element).

JavaScript Not Working properly in ASP.NET

I am pretty new to JavaScript and got stuck at one point:
I am using asp control fileupload to upload some files and store them to database, i am using asp repeater control to show all the docs in database in front end and have associated a html checkbox to every doc:
The problem is when i check or uncheck the checkbox, the delete button enables/disables accordingly, but when i click the "Select All" button where i am calling both functions - to check all checkboxes and to enable button, somehow the delete button is not getting enabled..Please help.
Here is JavaScript Code to enable delete button:-
function EnableButton() {
var rpt = document.getElementById('<%= rptWordDoc.ClientID %>');
var chkbx = document.getElementsByTagName('input');
var x = document.getElementById("btnDelWordDoc");
for (i = 0; i <= chkbx.length; i++) {
var id = "rptWordDoc_chkWordDoc_" + i
var y = document.getElementById(id);
if (y == null) {
break;
}
if (y.checked == true) {
x.disabled = false;
break;
}
else {
x.disabled = true;
}
}
}
This is how i am calling the function:-
<asp:Button ID="btnSelectAll" runat="server" Text="Select All" OnClientClick="fnSelectAll(); JavaScript:EnableButton();" />
Through Checkbox:-
<input type="checkbox" id="chkWordDoc" runat="server" onclick="JavaScript:EnableButton();" />
You called two functions fnSelectAll(); and JavaScript:EnableButton(); may be second is not executed after executing the first one.
Finally found the cause:
Actually i was using asp: button control for Select All & Clear All features and thus it was posting back to the server and setting back the value of delete button enabled attribute to false.
I added a html control instead of asp button for Select All & clear all buttons and didn't added runat=server attribute since no server side event was required.
Thanks for your suggestions..
Cheers..:)

DOM Elements created in JavaScript function disappear after function returned

I have a dropdown list with multiple selections allowed. A user selects from the list and then clicks the submit button with an onclick=test() which calls a JS function. I am using Jsp pages, and this is a Spring MVC framework project with DWR for remote service.
The data that's returned from the remote service - dwrService is handled by the callback function - handleAddSuccess. Based on the item(s) selected, I need to populate one or more textareas. From looking at Firebug, I see the textarea display and then being populated, but once the function, test() completes, the textarea disappears. I have been looking for answers everywhere, but no results.
function test() {
var careIDs = dwr.util.getValue("careIDs");
dwrService.getNewCares(careIDs, {
callback : handleAddSuccess,
errorHandler : handleAddError
});
}
function handleAddSuccess(data) {
var aFragment = document.createDocumentFragment();
var divta1 = document.getElementById("divta1");
for (i = 0; i < data.length; i++) {
var ta = document.createElement("textarea");
ta.setAttribute("id", "definition"+i);
ta.setAttribute("cols", "75");
ta.setAttribute("rows", "75");
divta1.appendChild(ta);
aFragment.appendChild(divta1);
}
document.body.appendChild(aFragment);
for (i = 0; i < data.length; i++) {
dwr.util.setValue("definition"+i, data[i].definition);
}
alert(" end of handleAddSuccess " ) ;
}
I have also returned from the callback function, and the case is the same - I could see the textarea elements being setup in Firebug and populated with values, but once the function returned, the textarea element disappears.
You don't return false from within test(), so the form gets submitted when the submit button is clicked and the page is reset to its initial state (depending on what the server does with the submitted form).

how to get selected radio button from radiobuttonlist in javascript [duplicate]

I have an ASP.NET web page with a databound RadioButtonList. I do not know how many radio buttons will be rendered at design time. I need to determine the SelectedValue on the client via JavaScript. I've tried the following without much luck:
var reasonCode = document.getElementById("RadioButtonList1");
var answer = reasonCode.SelectedValue;
("answer" is being returned as "undefined")
Please forgive my JavaScript ignorance, but what am I doing wrong?
Thanks in advance.
ASP.NET renders a table and a bunch of other mark-up around the actual radio inputs. The following should work:-
var list = document.getElementById("radios"); //Client ID of the radiolist
var inputs = list.getElementsByTagName("input");
var selected;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
selected = inputs[i];
break;
}
}
if (selected) {
alert(selected.value);
}
Try this to get the selected value from the RadioButtonList.
var selectedvalue = $('#<%= yourRadioButtonList.ClientID %> input:checked').val()
I always View Source. You will find each radio button item to have a unique id you can work with and iterate through them to figure out which one is Checked.
Edit: found an example. I have a radio button list rbSearch. This is in an ascx called ReportFilter. In View Source I see
ReportFilter1_rbSearch_0
ReportFilter1_rbSearch_1
ReportFilter1_rbSearch_2
So you can either loop through document.getElementById("ReportFilter1_rbSearch_" + idx ) or have a switch statement, and see which one has .checked = true.
RadioButtonList is an ASP.NET server control. This renders HTML to the browser that includes the radio button you are trying to manipulate using JavaScript.
I'd recommend using something like the IE Developer Toolbar (if you prefer Internet Explorer) or Firebug (if you prefer FireFox) to inspect the HTML output and find the ID of the radio button you want to manipulate in JavaScript.
Then you can use document.getElementByID("radioButtonID").checked from JavaScript to find out whether the radio button is selected or not.
The HTML equivalent to ASP.NET RadioButtonList, is a set of <input type="radio"> with the same name attribute(based on ID property of the RadioButtonList).
You can access this group of radio buttons using getElementsByName.
This is a collection of radio buttons, accessed through their index.
alert( document.getElementsByName('RadioButtonList1') [0].checked );
function CheckRadioListSelectedItem(name) {
var radioButtons = document.getElementsByName(name);
var Cells = radioButtons[0].cells.length;
for (var x = 0; x < Cells; x++) {
if (document.getElementsByName(name + '_' + x)[0].checked) {
return x;
}
}
return -1;
}
For a 'RadioButtonList with only 2 values 'yes' and 'no', I have done this:
var chkval=document.getElemenById("rdnPosition_0")
Here rdnposition_0 refers to the id of the yes ListItem. I got it by viewing the source code of the form.
Then I did chkval.checked to know if the value 'Yes' is checked.
I would like to add the most straightforward solution to this problem:
var reasons= document.getElementsByName("<%=RadioButtonList1.UniqueID%>");
var answer;
for (var j = 0; j < reasons.length; j++) {
if (reason[j].checked) {
answer = reason[j].value;
}
}
UniqueID is the property that gave you the name of the inputs inside the control, so you can just check them really easily.
I've tried various ways of determining a RadioButtonList's SelectedValue in Javascript with no joy. Then I looked at the web page's HTML and realised that ASP.NET renders a RadioButtonList control to a web page as a single-column HTML table!
<table id="rdolst" border="0">
<tr>
<td><input id="rdolst_0" type="radio" name="rdolst" value="Option 1" /><label for="rdolst_0">Option 1</label></td>
</tr>
<tr>
<td><input id="rdolst_1" type="radio" name="rdolst" value="Option 2" /><label for="rdolst_1">Option 2</label></td>
</tr>
</table>
To access an individual ListItem on the RadioButtonList through Javascript, you need to reference it within the cell's child controls (known as nodes in Javascript) on the relevant row. Each ListItem is rendered as the first (zero) element in the first (zero) cell on its row.
This example loops through the RadioButtonList to display the SelectedValue:
var pos, rdolst;
for (pos = 0; pos < rdolst.rows.length; pos++) {
if (rdolst.rows[pos].cells[0].childNodes[0].checked) {
alert(rdolst.rows[pos].cells[0].childNodes[0].value);
//^ Returns value of selected RadioButton
}
}
To select the last item in the RadioButtonList, you would do this:
rdolst.rows[rdolst.rows.length - 1].cells[0].childNodes[0].checked = true;
So interacting with a RadioButtonList in Javascript is very much like working with a regular table. Like I say I've tried most of the other solutions out there but this is the only one which works for me.
I wanted to execute the ShowShouldWait script only if the Page_ClientValidate was true. At the end of the script, the value of b is returned to prevent the postback event in the case it is not valid.
In case anyone is curious, the ShouldShowWait call is used to only show the "please wait" div if the output type selected is "HTML" and not "CSV".
onclientclick="var isGood = Page_ClientValidate('vgTrxByCustomerNumber');if(isGood){ShouldShowWait('optTrxByCustomer');} return isGood"
To check the selected index of drop down in JavaScript:
function SaveQuestion() {
var ddlQues = document.getElementById("<%= ddlQuestion.ClientID %>");
var ddlSubQues = document.getElementById("<%=ddlSecondaryQuestion.ClientID%>");
if (ddlQues.value != "" && ddlSubQues.value != "") {
if (ddlQues.options[ddlQues.selectedIndex].index != 0 ||
ddlSubQues.options[ddlSubQues.selectedIndex].index != 0) {
return true;
} else {
return false;
}
} else {
alert("Please select the Question or Sub Question.");
return false;
}
}
reasonCode.options[reasonCode.selectedIndex].value
From here:
if (RadioButtonList1.SelectedIndex > -1)
{
Label1.Text = "You selected: " + RadioButtonList1.SelectedItem.Text;
}

How do I pass form elements to a javascript validation function?

I have a form that lists users, and for each user there is a drop down menu (2 choices: waiting, finished) and a comments textbox. The drop down menus are each labeled "status-userid" and the comments textbox is labeled "comments-userid" ... so for user 92, the fields in his row are labeled status-92 and comments-92.
I need to validate the form in the following way:
If the value of the status is "finished", I have to make sure that the user entered comments to correspond with that specific drop down menu.
So far, I have:
function validate_form () {
valid = true;
/*here's where i need to loop through all form elements */
if ( document.demerits.status-92.value == "finished" &&
document.demerits.comments-92.value == "")
{
alert ( "Comments are required!" );
valid = false;
}
return valid;
}
How do I loop through all of the status-userid elements in the form array?! Or is there another way to do this?
This should do it in raw Javascript (no framework).
var form = document.demerits;
for (var i = 1; i <= 100; i++)
{
if (form["status-" + i.toString()].value == "finished" &&
form["comments-" + i.toString()].value == "")
{
// enable visibility of element next to comments indicating validation problem
valid = false;
}
}
Using alerts would be bad though.
You'll need a collection of the dropdowns in your form. This can be acquired by using getElementsByTagName.
var dropdowns = document.demerits.getElementsByTagName("select");
for (var i = 0; i < dropdowns.length; i++)
{
// You can now reference the individual dropdown with dropdowns[i]
}

Categories