Run Javascript to change value on RadioButtonList click - javascript

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.

Related

Javascript word count price calculator

Everything works fine, except the problem with a pricing plan selection. What I want is that whenever user clicks on a specified price (even while the text is already present in textarea), it should immediately update the final Price. But it won't change at first click.
I should click twice on it instead. Any one got an idea what's wrong ?
So here how it looks like:
And here comes the javascript code:
function __textCalculatorCounter(){
var value = $('#calculateText').val();
var spanWords = $('#calculatedWordsTotal'),
spanChars = $('#calculatedCharsTotal'),
spanPrice = $('#calculatedPriceTotal');
if (value.length == 0) {
spanWords.html(0);
spanChars.html(0);
return;
}
var selectedPricing = $("input[name=calculatePrice]:checked").val();
var wordCount = value.trim().replace(/\s+/gi, ' ').split(' ').length;
var totalChars = value.length;
var totalPrice = (wordCount * parseFloat(Math.round(selectedPricing * 100) / 100));
spanWords.html(wordCount);
spanChars.html(totalChars);
spanPrice.html(totalPrice.toFixed(2));
}
function _initTextCalculator(){
var textblock = $('#calculateText');
textblock.change(__textCalculatorCounter);
textblock.keydown(__textCalculatorCounter);
textblock.keypress(__textCalculatorCounter);
textblock.keyup(__textCalculatorCounter);
textblock.blur(__textCalculatorCounter);
textblock.focus(__textCalculatorCounter);
$('label', '#pricesGroup').click(__textCalculatorCounter);
}
==== UPDATED ====
I don't know why, but it works fine in jsfiddle... it's exactly the same code extracted from html and javascript.
JSFIDDLE
So, since no one had an answer, I post mine, which solved the issue.
The problem is in Twitter's Bootstrap 3 radio button styles which is actually common issue when using along with javascript.
I've changed a click handler for radio buttons:
function _initTextCalculator(){
var textblock = $('#calculateText');
textblock.change(_textCalculatorTrigger);
textblock.keydown(_textCalculatorTrigger);
textblock.keypress(_textCalculatorTrigger);
textblock.keyup(_textCalculatorTrigger);
textblock.blur(_textCalculatorTrigger);
textblock.focus(_textCalculatorTrigger);
// Fixing bootstrap 3 radio buttons
$("#pricesGroup label").on('click', function(){
// Once clicked, mark current radio as checked
$('input:radio', this).prop("checked", true);
// Then call a function to calculate the price
_textCalculatorTrigger();
});
}
As it already commented, it assigns a property "checked" to radio button first once it's parent label tag is clicked, and then it calls a function to calculate the price.
Thanks to everyone

Adding numeric value from textbox into another textbox

I have been looking for this script everywhere however i was unable to find it. I am trying to create a simple donation count. When a value is added inside a textbox I want it to be permanently fixed into second textbox after button submission. Thanks in advance for all your help.
1) First get the value from textBox1 (assuming id=textbox1)
2) Assign the value to second textbox (assuming id=textbox2)
3) Add the below code in form submission or button click.
document.getElementById('textbox2').value =
document.getElementById('textbox1').value
Try this:
<script>
window.onload = function () {
var textfield6 = document.getElementById('textfield6');
textfield6.value = 0;
document.querySelector('input[type=button]').onclick = function () {
textfield6.value = parseInt(textfield6.value) + parseInt(document.getElementById('textfield5').value);
}
}
</script>
Demo here

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

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

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