JavaScript Not Working properly in ASP.NET - javascript

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..:)

Related

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

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.";
}

How to find control from InsertItemTemplate in Java Script

I am new to Java Script. I have a aspx ListView with InsertItemTemplate and some buttons in it.Now i need to access the buttons from insertitemtemplate in JavaScript to disable it. This is not working?
document.getElementById('<%= Button1.ClientID %>').disable = true;
Please help me.
Solution 1
You can set the Javascript code in code-behind, where you have access to the ClientID property of the controls for each item of the ListView. For example, if you have two buttons in the item template and you want to disable btn2 when clicking on btn1, you can set the client code in the ItemDataBound event:
void lstView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.InsertItem)
{
Button btn1 = e.Item.FindControl("btn1") as Button;
Button btn2 = e.Item.FindControl("btn2") as Button;
btn1.OnClientClick = string.Format("var btn2 = document.getElementById('{0}'); btn2.disabled = true; return false;", btn2.ClientID);
}
}
Solution 2
If you cannot use the first method, but can modify the markup, then you can give the button a name that is unique in your page and set the ClientIDMode of the button to Static:
<asp:Button ID="btnUniqueName1" runat="server" ClientIDMode="Static" ... />
Since there is at most one insert item in the ListView, that ID should be unique in the form. You can retrieve the button like this:
document.getElementById('btnUniqueName1');
Solution 3
If you must find the button without modifying the server code, you can retrieve all the buttons in the form and look for some attribute that is found only in the button you are looking for:
var buttons = document.getElementsByTagName('button');
for (var i = 0; i < buttons.length; i++) {
var button = buttons[i];
// Check if that button is the one you want
// Look for some unique attribute, class name, etc.
if (button.className == 'btnUniqueClassName') {
// The button was found
button.disabled = true;
}
}

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;
}

Run Javascript to change value on RadioButtonList click

Alright, so I'm writing a code that calculates a cost based on the values of three text boxes and the selection from a radiobuttonlist. The page uses ASP.net controls. The following script is run in the onBlur from each text box so that it updates the total and displays it in another texbox:
function calcTotal(form) {
var total = 0;
var sellingthings = $(form).find('.payable');
var adultLunch = $(form).find('.adultLunch');
var lunch1 = $(adultLunch).val();
var childLunch = $(form).find('.childLunch');
var lunch2 = $(childLunch).val();
var semTix = $(form).find('.seminarTix');
var tix = $(semTix).val();
var reg= $(form).find('.registration input:checked');
var regCost = $(reg).val();
//alert(regCost);
total = (10*lunch1 + 5*lunch2 + 40*tix + regCost*1);
var output = $(form).find('.total');
$(output).val(total);
}
This code works on the textboxes to update the value in the .total field. However, the same code does not work right on the radiobuttonlist. The code for it is here:
<asp:RadioButtonList ID = "RegType" runat = "server" name="regType" onclick="calcTotal(this.form)">
<asp:ListItem Value="50">Family ($50)</asp:ListItem>
<asp:ListItem Value="35">Individual ($35)</asp:ListItem>
<asp:ListItem Value="10">Student ($10)</asp:ListItem>
</asp:RadioButtonList>
Does anyone know why this might be or how I could fix it?
Thanks!
I'm not sure there is an onClick property for a RadioButtonList control.
Have a look at this tutorial to see if it helps.
By default RadioButtonList renders as a table and as such, it will add the onclick handler to the table rather than the radio input element. Change the RepeatLayout property to RepeatLayout.Flow and see if that works.
I found a solution. In the Javascript, I used the following code:
$(document).ready(function () {
$(".registration input").change(function () { calcTotal(document.forms[0]); });
});
When the radiobutton input is changed at any point, it will run the calculation code. You can't add code to a radiobuttonlist, so you have to do it another way.

Enabling disabled CheckBoxList in javascript - checked items not recognized after postback

I have a CheckBoxList which can load as disabled, but might need to become enabled after some client side actions.
I am able to enable the checkboxes using jQuery, but the problem is that after submitting the page, the selected items in the ChceckBoxList are not recognized (probably because the control is not in the ViewState).
A simple example for the scenario:
<asp:CheckBoxList ID="chkList1" runat="server" Enabled="false" ClientIDMode="Static">
<asp:ListItem Value="123" />
<asp:ListItem Value="456" />
<asp:ListItem Value="789" />
</asp:CheckBoxList>
$(document).ready(function()
{
$("#divEnable").click(function()
{
var inputs = $("#chkList1").find("input");
for (var i = 0; i < inputs.length; i++)
{
inputs[i].disabled = false;
}
});
}
And then after enabling the checkboxes, selecting them and sending a postback - no selected items are recognized.
I tried disabling the items "manually", as in
chkList1.Items[0].Attributes.Add("disabled", "disabled");
But that did not work (the disabled attribute was attached to the containing span instead of the input control).
I also considered using hidden fields to keep track of the checkbox selections, but since I have multiple CheckBoxLists in a grid, that would be very inelegant.
Is there any way around this?
try this:
$(document).ready(function()
{
$("#divEnable").click(function()
{
var inputs = $("#chkList1").find("input")
.each(function(){
//if($(this).is(":disabled"))
//{
$(this).prop("disabled",true);
//}
});
});
Ref:
jQuery asp control .prop(“disabled”, “”) not enabling check box in IE 9
Unable to handle disable check box
You can use this
for (i = 0; i < document.forms[0].length; i++)
{
e = document.forms[0].elements[i];
if (e.id.indexOf("chklist") != -1)
{
e.disabled = false;
}
}
I had the same issue. The way I fixed this was to enable the checkboxlist to start, then on load of the page, disable using script. That way the controls got into the viewstate, but were still disabled to start.
var checkBoxListToChange = document.getElementById('');
var checkboxes = checkBoxListToChange.getElementsByTagName("input");
for (var x = 0; x < checkboxes.length; x++) {
checkboxes[x].disabled = true;
}

Categories