Select a radio control from Javascript - javascript

I have a group of 2 asp radio controls and I want to choose one of them on ajax postback. I can put breakpoints and can tell the code is being hit, but nothing is happening. I have tried good 5-10 different variations, but nothing seems to work. The .css bit was to test that I can find the right control and that is working. The CSS gets applied.
I have tried .trigger("click") , also attr(checked="checked" and true). Have tried anything that I could find on Google. But the second option is not getting checked.
$("[main=true]").Checked = true;
$("[main=true]").css("background-color", "yellow");
Html
<asp:RadioButton GroupName="Complete" runat="server" Text="Yes" Checked="true" />
<asp:RadioButton GroupName="Complete" runat="server" Text="No" main="true" /><br />
Another minor issue I seem to be having is that if I click on the words "Yes" or "No" both option boxes get un-selected. Any reason for that?
$(window).load(function () {
$("[main=false]").prop('checked', false);
$("[main=true]").prop('checked', true);
$("[main=true]").prop('checked', true);
$("[main=true]").attr('checked', true);
$("[main=true]").Checked = true;
$("[main=true]").css("background-color", "yellow");
var id = localStorage.getItem("CustomerID");
$('img[alt = "' + id + '"]').trigger("click");
localStorage.clear();
});
The HTML out put
<span>Mark as complete:</span><span main="false">
<input id="gvCustomers_ctl07_0" type="radio" name="gvCustomers$ctl02 $Complete" value="ctl07" checked="checked" />
<label for="gvCustomers_ctl07_0">Yes</label>
</span><span main="true"><input id="gvCustomers_ctl08_0" type="radio" name="gvCustomers$ctl02$Complete" value="ctl08" />
<label for="gvCustomers_ctl08_0">No</label></span>
By the way there are more than one radio controls with main attribute set to true, but I want all of them to get selected. Not sure if that makes any difference. What doesn't make sense is that the CSS is getting applied.

I have a confusion, How can HTML be
<asp:RadioButton GroupName="Complete" runat="server" Text="Yes" Checked="true" />
According to my knowledge, No matter what programing language you use, it is first converted to HTML and then rendered in the browser.
So as much i can assume, you code will be getting converted to
<input name='Complete' type='radio' checked='true'></input>
<input name='Complete' type='radio' main='true'></input>
A very simple & naive solution to your problem will be
var elemArray=document.getElementsByName("Complete");
elemArray[0].checked=true;//For 1 radio
elemArray[1].checked=true; //For 2 radio
or you can simply iterate over the element array
for(i=0;i<elem.length;i++){
if(elem[i].hasAttribute('main')){
elem[i].checked=true;//if the second element do not have any main attribute
//or
if(elem[i].main='true'){
elem[i].checked=true;
}
}
}

Related

Server tag not evaluated in server control

On my ASPX page, I need a server control checkbox to pass a backend variable as a parameter in its onclick JS function. But it doesn't seem to work as expected.
Please refer the two checkboxes below:
<input type="checkbox" id="Checkbox1" onclick="ToggleMyOnly('<%=gsListID %>');" />
<input type="checkbox" id="Checkbox2" runat="server" onclick="ToggleMyOnly('<%=gsListID %>');" />
Here the Checkbox1 evaluates the value of gsListID as expected. However, Checkbox2 just passes it as is.
The only difference between these two controls is that Checkbox2 is a server control.
I have searched for a solution for this issue across many sites, but did not get an answer.
I also tried converting the Checkbox1 to an ASP checkbox as follows:
<asp:CheckBox ID="CheckboxASP" runat="server" Text="test" onclick="ToggleMyOnly('<%=gsListID %>');" />
But this also did not evaluate the server tag.
Can anyone help me know how to use the server tag in "onclick" for a server control input element? (Avoiding an ASP:checkbox preferred).
You should write like below:
<asp:CheckBox runat="server" ID="chk" Text="Test" onchange="return ToggleMyOnly('<%=gsListID %>');" />
if you dont want to postback then return false from ToggleMyOnly function.
It's working from myside.

jQuery else clause not working [duplicate]

I have 3 radio buttons in my web page, like below:
<label for="theme-grey">
<input type="radio" id="theme-grey" name="theme" value="grey" />Grey</label>
<label for="theme-pink">
<input type="radio" id="theme-pink" name="theme" value="pink" />Pink</label>
<label for="theme-green">
<input type="radio" id="theme-green" name="theme" value="green" />Green</label>
In jQuery, I want to get the value of the selected radio button when any of these three are clicked. In jQuery we have id (#) and class (.) selectors, but what if I want to find a radio button by its name, as below?
$("<radiobutton name attribute>").click(function(){});
Please tell me how to solve this problem.
This should do it, all of this is in the documentation, which has a very similar example to this:
$("input[type='radio'][name='theme']").click(function() {
var value = $(this).val();
});
I should also note you have multiple identical IDs in that snippet. This is invalid HTML. Use classes to group set of elements, not IDs, as they should be unique.
To determine which radio button is checked, try this:
$('input:radio[name=theme]').click(function() {
var val = $('input:radio[name=theme]:checked').val();
});
The event will be caught for all of the radio buttons in the group and the value of the selected button will be placed in val.
Update: After posting I decided that Paolo's answer above is better, since it uses one less DOM traversal. I am letting this answer stand since it shows how to get the selected element in a way that is cross-browser compatible.
$('input:radio[name=theme]:checked').val();
another way
$('input:radio[name=theme]').filter(":checked").val()
This works great for me. For example you have two radio buttons with the same "name", and you just wanted to get the value of the checked one. You may try this one.
$valueOfTheCheckedRadio = $('[name=radioName]:checked').val();
The following code is used to get the selected radio button value by name
jQuery("input:radio[name=theme]:checked").val();
Thanks
Adnan
For anyone who doesn't want to include a library to do something really simple:
document.querySelector('[name="theme"]:checked').value;
jsfiddle
For a performance overview of the current answers check here
I found this question as I was researching an error after I upgraded from 1.7.2 of jQuery to 1.8.2. I'm adding my answer because there has been a change in jQuery 1.8 and higher that changes how this question is answered now.
With jQuery 1.8 they have deprecated the pseudo-selectors like :radio, :checkbox, :text.
To do the above now just replace the :radio with [type=radio].
So your answer now becomes for all versions of jQuery 1.8 and above:
$("input[type=radio][name=theme]").click(function() {
var value = $(this).val();
});
You can read about the change on the 1.8 readme and the ticket specific for this change as well as a understand why on the :radio selector page under the Additional Information section.
If you'd like to know the value of the default selected radio button before a click event, try this:
alert($("input:radio:checked").val());
You can use filter function if you have more than one radio group on the page, as below
$('input[type=radio]').change(function(){
var value = $(this).filter(':checked' ).val();
alert(value);
});
Here is fiddle url
http://jsfiddle.net/h6ye7/67/
<input type="radio" name="ans3" value="help">
<input type="radio" name="ans3" value="help1">
<input type="radio" name="ans3" value="help2">
<input type="radio" name="ans2" value="test">
<input type="radio" name="ans2" value="test1">
<input type="radio" name="ans2" value="test2">
<script type="text/javascript">
var ans3 = jq("input[name='ans3']:checked").val()
var ans2 = jq("input[name='ans2']:checked").val()
</script>
If you want a true/false value, use this:
$("input:radio[name=theme]").is(":checked")
Something like this maybe?
$("input:radio[name=theme]").click(function() {
...
});
When you click on any radio button, I believe it will end up selected, so this is going to be called for the selected radio button.
I you have more than one group of radio buttons on the same page you can also try this to get the value of radio button:
$("input:radio[type=radio]").click(function() {
var value = $(this).val();
alert(value);
});
Cheers!
can also use a CSS class to define the range of radio buttons and then use the following to determine the value
$('.radio_check:checked').val()
This worked for me..
HTML:
<input type="radio" class="radioClass" name="radioName" value="1" />Test<br/>
<input type="radio" class="radioClass" name="radioName" value="2" />Practice<br/>
<input type="radio" class="radioClass" name="radioName" value="3" />Both<br/>
Jquery:
$(".radioClass").each(function() {
if($(this).is(':checked'))
alert($(this).val());
});
Hope it helps..
$('input:radio[name=theme]').bind(
'click',
function(){
$(this).val();
});
You might notice using class selector to get value of ASP.NET RadioButton controls is always empty and here is the reason.
You create RadioButton control in ASP.NET as below:
<asp:RadioButton runat="server" ID="rbSingle" GroupName="Type" CssClass="radios" Text="Single" />
<asp:RadioButton runat="server" ID="rbDouble" GroupName="Type" CssClass="radios" Text="Double" />
<asp:RadioButton runat="server" ID="rbTriple" GroupName="Type" CssClass="radios" Text="Triple" />
And ASP.NET renders following HTML for your RadioButton
<span class="radios"><input id="Content_rbSingle" type="radio" name="ctl00$Content$Type" value="rbSingle" /><label for="Content_rbSingle">Single</label></span>
<span class="radios"><input id="Content_rbDouble" type="radio" name="ctl00$Content$Type" value="rbDouble" /><label for="Content_rbDouble">Double</label></span>
<span class="radios"><input id="Content_rbTriple" type="radio" name="ctl00$Content$Type" value="rbTriple" /><label for="Content_rbTriple">Triple</label></span>
For ASP.NET we don't want to use RadioButton control name or id because they can change for any reason out of user's hand (change in container name, form name, usercontrol name, ...) as you can see in code above.
The only remaining feasible way to get the value of the RadioButton using jQuery is using css class as mentioned in this answer to a totally unrelated question as following
$('span.radios input:radio').click(function() {
var value = $(this).val();
});

Radio Button Name Changes

I created 2 radio buttons
<input type="radio" name="ApprovalGroup" runat="server" id="ApprovedOnly" value="true" />Approved
<input type="radio" name="ApprovalGroup" runat="server" id="UnapprovedOnly" value="false" />Unapproved
And was able to access them from js with $("input[name=ApprovalGroup]:checked").val() But then I needed to add runat="server" so I could access the radio button in the code behind.
The problem I have is the radio button name is being changed because of the content place holder. I'm using ClientIDMode="Static" but it only protects the id value, not the name. The radio button is rendered as
<input value="true" name="ctl00$cphContent$ApprovalGroup" type="radio" id="ApprovedOnly" />Approved
<input value="false" name="ctl00$cphContent$ApprovalGroup" type="radio" id="UnapprovedOnly" />Unapproved
Is it possible to prevent the name from changing?
You could use the $= selector, which selects attributes whose values end with the given substring:
$("input[name$=ApprovalGroup]:checked")
.NET wants the name for its own purposes, but that doesn't stop you for using a CSS class name for your own.
That way you can use $('.classname').val(). You can use individual class names for fields, or share them to make groups.
$("input[name*=ApprovalGroup]:checked")
is a good solution but if there is another input that contains these words, then it can be occured a conflict. So safer solution is to use your own attribute.
such as;
<input type="radio" name="ApprovalGroup" data-group="group1" runat="server" id="ApprovedOnly" value="true" />Approved
<input type="radio" name="ApprovalGroup" data-group="group1" runat="server" id="UnapprovedOnly" value="false" />Unapproved
then use filter below;
$("input[data-group='group1']:checked")

How to ASP Button onClick= "js variable"?

jQuery
$(document).ready(function () {
$('#ButtonRadioValue').click(function () {
var selValue = $('input[name=radio]:checked').val();
});
});
Radio
<div id="radio" align="center">
<input type="radio" id="radio1" value="BtnNextCaseClick" name="radio" checked="checked"/><label for="radio1" style="width: 109px; margin-right:-.9em">Next</label>
<input type="radio" id="radio2" value="CloseCase" name="radio" /><label for="radio2" style="margin-right:-.9em">Close Case</label>
<input type="radio" id="radio3" value="CloseWeb" name="radio" /><label for="radio3" style="width: 109px">Close Web</label>
</div>
So, below that radio I have a button, and I want it to execute different code behind according to radio selection. That value is stored in selValue. So how can I tell onclick event to run what's inside of selValue
Button
<asp:Button ID="ButtonRadioValue" CssClass="customButton" runat="server" onclick=" js variable here" Text="Aceptar" style="width: 111px; height: 30px"/>
Thanks.
EDIT
Since there was no real need for client-side procedure. I did it from Server side with this.radio1.Checked == true
Update: It appears I have misunderstood what is required, so I will leave my original below
If you want to know which radio button was selected on the post-back, then either make the radio's server-side controls (either by converting into <asp:RadioButton> or simply adding runat="server" to them. Then you can test for radio1.Checked, etc.
Otherwise you can check the form data using Request.Form("radio1"). If result is Nothing (VB.Net) or null (C#) then the radio was not selected. If there is a value there, you know the radio is selected.
Original / incorrect assumption
Unless I've misunderstood the issue, you don't need to have a special attribute in the <asp:Button> as you can do this just in the jQuery you've already written.
Add the following after your var selValue...
$("#" + selValue).trigger("click");
To produce...
$(document).ready(function () {
$('#ButtonRadioValue').click(function () {
var selValue = $('input[name=radio]:checked').val();
$("#" + selValue).trigger("click");
});
});
One thing to note is that if the control is within Master Page, Placeholder, etc, then the button will need the full ClientID, otherwise the jQuery will not find it
As a side note, the OnClick attribute of the <asp:Button> is used to wire-up the event handler for the click on a post-back to the server. If you want to run javascript then you want to use the OnClientClick attribute, which will produce an onclick attribute in the rendered HTML
It sounds like you are looking for eval().
var selValue = $('input[name=radio]:checked').val();
eval(selValue);
The Click is a server event. If you want JS code to execute use onclientclick.
You can try with OnClientClick event in order to call client function
Link : http://msdn.microsoft.com/fr-fr/library/system.web.ui.webcontrols.button.onclientclick(v=vs.80).aspx
Server Side : OnClick
Client Side : OnClientClick

Prevent users to click RadioButton

In my form I have some TextBoxes. Once the value of TextBox is changed then corresponding RadioButton will be selected. But I want to prevent users from changing the value of RadioButton.
I tried disabling like this.
optA.Attributes.Add("disabled", "disabled");
But this script greys out the radiobutton which is not looking good. Is there any script to prevent users from clicking/changing the selected value of radiobutton?
Small example is
totalval=document.getElementById('txt1').value+document.getElementById('txt2').value
if (totalval>101)
document.getElementById('optA1').checked=true;
else if(totalval<100)
document.getElementById('optA2').checked=true;
This is what I want. So the users should not change the value of radiobuttons (optA1,optA2)
if am using
optA1.Attributes.Add("disabled", "disabled");
I couldnt get the value of optA1 at server side.
My aspx code is
<asp:RadioButton ID="optA1" GroupName="optAchieve" runat="server" Text="30" value="30" onclick="indicateColor()" />
<asp:RadioButton ID="optA2" GroupName="optAchieve" runat="server" Text="20" value="20" onclick="indicateColor()" />
Try to prevent user action by onclick event like this :
optA.Attributes.Add("onclick", "return false;");
You have to right javascript on radio button click , no matter what the radio option is selected always select the default option from javascript.
Attach a readonly class and change attribute of radio button to unchecked on each click.
<input type="radio" id="radio1" name="radio" class="readonlyradio">
<input type="radio" id="radio2" name="radio" class="readonlyradio">​
Use this function in your JS:
$(".readonlyradio").click(function(){
$(this).attr('checked', false);
});​
Check this fiddle:http://jsfiddle.net/Xwtvp/
Hope it helps.

Categories