getting class attribute of radio button in IE - javascript

I need to get the class attribute of checked radio button, with name="radio".
Used the code that's working fine in Firefox, but fails in IE.
val = $('input:radio[name=radio]:checked').attr('class');
How can i accomplish this?

There is no psuedo-class :radio. I think you meant [type=radio].

As comments says, I think you should use type instead of name. But i think you have named your input as radio because you can find this specific input. If you just use type selector you will catch every single selected radio input on page.
<input type="radio" name="radio" class="ey" /> Male<br />
So, if your page have more forms, you should specify a parent or form to avoid conflicts. Set a id for your form and try to find it by form id and radio type like this:
<form id="myForm">
<input type="radio" name="radio" class="ey" /> Male<br />
</form>
val = $("#myform input[type='radio']:checked").attr('class');
I hope it can help you :)

Related

Radio button intercepting unchecked event in Angular/Javascript

I am writing an Angular component which uses radio button (Need to use default radio buttons due to project constraints).
I need to print the value of the radio button (whether it is checked or unchecked). Like following:
<input type="radio" (change)="onUpdate($event)">
<p>{{isActive}}</p>
In the component something like this:
onUpdate(event) {
this.isActive = event.target.checked;
}
But this doesn't work as the change event is not triggered when the radio button is unchecked. Is there any way to intercept the event when the radio button is unchecked?
Please help. I am stuck. Dummy app link here
Edit: What I am trying to do
I am trying to write a custom radio button so that I can styles it on my own. I cannot write a radio-group component. Hence I need a wrapper component around the default one. Something like Stackblitz-link. I need the unchecked event because I have some custom element which has to be notified about this. Any way to achieve this ?
Use a checkbox, style it like a radio button. Seems to be the easiest solution and of course use ng-model instead of onChange.
You could replace (change) with (click), because every click on the radio button is a change anyway.
<input type="radio" (click)="onUpdate($event)">
<p>{{isActive}}</p>
The above is a solution, but I'd use this:
<input type="radio" [(ngModel)]="isActive">
<p>{{isActive}}</p>
It binds your radio button to your isActive property, so it changes dynamically with clicking.
So using two radio buttons got this working for me, let me know if you can model this for your application.
<input type="radio" name="button" [value]="checked" (change)="checked=!checked">
<input type="radio" name="button" [value]="!checked" (change)="checked=!checked">
<p>{{checked}}</p>
I am setting checked to false by default in my component.
Can you please try to adjust this logic with your code? Checking some new radio will uncheck other and we can keep track of this behavior.
<p>
<input type="radio" name="r1" value="one" [(ngModel)]="isActive">
<input type="radio" name="r2" value="two" [(ngModel)]="isActive">
<input type="radio" name="r3" value="three" [(ngModel)]="isActive">
</p>
<p>{{isActive}}</p>
Stackblitz link

Copy input field's value to multiple hidden fields... but with same ID's?

1) I have 3 input radio buttons with unique values.
For e.g.
<input type="radio" id="id1" value="This is first value" />
<input type="radio" id="id2" value="This is second value" />
<input type="radio" id="id3" value="This is third value" />
2) Next, I have 2 hidden form like this:
<form action="//mysite.com/process1.php"><input type="hidden" id="uniqueid" value=""></form>
<form action="//mysite.php/process2.php"><input type="hidden" id="uniqueid" value=""></form>
3) Based upon whichever radio button the user clicks, I need to copy its value to the value of both the above forms hidden field.
For e.g. If user clicks on radio with id1, then it's value "This is first value" should be copied to both the forms hidden field.
CONSTRAINTS:
1) Have to use javascript or jquery, no server side processing available.
2) Note: both the final forms have one input field, but with same id. This is a constraint.
3) Why? Because based on some other actions on the page, the user gets to see one of the 2 forms. The only difference between them is their action is unique. All fields are same.
WHAT I HAVE SO FAR:
Using this, I am able to copy the value from the radio button to a hidden field's value, but it only copies to a field with a UNIQUE ID.
var $unique = $("#unique");
$("#radio1").keyup(function() {
$unique.val(this.value);
});
$("#email").blur(function() {
$unique.val(this.value);
});
Can someone guide as to how can the value be copied to multiple input fields, but with same id's?(Yes, the id's of the initial radio buttons can be unique.)
Having two HTML elements with same ID is an error.
You cannot treat this as a constraint, this is NOT a valid HTML code and it will cause inconsistent behavior in different browsers.
Use classes instead:
<form action="//mysite.com/process1.php"><input type="hidden" class="uniqueid" value=""></form>
<form action="//mysite.php/process2.php"><input type="hidden" class="uniqueid" value=""></form>
And javascript:
var $unique = $(".uniqueid");
However, I couldn't find any #radio1 or #email in your code, are you sure you have the right selectors?
My recommendation for the JS will be: (Working jsFiddle)
var $unique = $(".uniqueid");
$('input[type="radio"]').click(function(){
$unique.val(this.value);
});
Notes for jsFiddle:
I've used click event instead of keyup (don't really understand why you used keyup here..).
I've given all radio buttons the same name so they will cancel each other out when selected.
I've turned the hidden fields to text so you could see the result.
<form action="//mysite.com/process1.php"><input type="hidden" class="uniqueid" id="uniqueid" value=""></form>
<form action="//mysite.php/process2.php"><input type="hidden" class="uniqueid" id="uniqueid" value=""></form>
var $unique = $("input[type=hidden].uniqueid");
$("#radio1").keyup(function() {
$unique.val(this.value);
});
$("#email").blur(function() {
$unique.val(this.value);
});
As said by others, id must be unique. Try using a data-attribute:
<form action="//mysite.com/process1.php">
<input type="hidden" data-shouldupdate="true" value="">
</form>
<form action="//mysite.php/process2.php">
<input type="hidden" data-shouldupdate="true" value="">
</form>
Now you can use that attribute as selector to do something like:
$('[data-shouldupdate]').val(this.value);
I agree with all other who posted that id have to be unique to have correct HTML document. So if it's possible I strictly recommend you to fix the HTML document to remove all duplicates.
I write my answer only for the case that you can't remove id duplicates because of some reason and you still have the same requirements. In the case you should change the line
var $unique = $("#uniqueid");
to
var $unique = $("*[id=uniqueid]");
The selector *[id=uniqueid] (or just [id=uniqueid]) works slowly as #uniqueid, but it allows you to get all elements with the specified id attribute value. So it works even in case of id duplicates on the HTML page.
The most simple solution is to give a same name to both inputs. Check this link jsfiddle to see a working example. The code used is the one given is below:
HTML:
<input type="radio" name="copiedValue" id="id1" value="This is first value" />
<input type="radio" name="copiedValue" id="id2" value="This is second value" />
<input type="radio" name="copiedValue" id="id3" value="This is third value" />
<form action="//mysite.com/process1.php"><input name="uniqueid" id="uniqueid" value=""></form>
<form action="//mysite.php/process2.php"><input name="uniqueid" id="uniqueid" value=""></form>
jQuery/javascript:
$("input:radio[name=copiedValue]").click(function() {
$("input[name=uniqueid]").val($(this).val());
});
The radio-buttons should have the same name. I removed the type="hidden" so u can see it working correctly.
Hope it useful!

validate field in javascript and jquery

I have four radio buttons. If I select the last radio button then one textbox is appearing. I handled this scenario by jquery. Now I want to validate in such a way that if user gets this textbox means if user checked the last radio button, then he should provide some text.But in my case, if I check any one of the radio button, its telling to provide some text. The code is like:
<input type="radio" name="bus_plan" id="smallBtn" value="1" />1
<input type="radio" name="bus_plan" id="smallBtn" value="2" />2
<input type="radio" name="bus_plan" id="smallBtn" value="3" />3
<input type="radio" name="bus_plan" id="smallBtn" value="Promotional" />
<span class="plantxt"><a style="cursor:pointer;" onclick="popup('popUpDiv')">Promotional Plan</a> (Please enter a promotional code)</span>
<div class="reg-line" id="pr_code_id" style="display:none">
<div class="reg-linea" align="left">Promotional Code: <sup>*</sup></div>
<input type="text" name="bus_prcode" id="bus_prcode" class="reg-line-input" value="Promotional Code" onblur="if(this.value=='') this.value='Promotional Code'" onClick="if(this.value==this.defaultValue) this.value='';" />
<br />
<div>
<div id="promotionalbox" style="display:none;font-size:13px;clear:both"></div>
</div>
</div>
<script type="text/javascript" src="js/jquery-1.7.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("input:radio[name=bus_plan]").click(function(){
var values = $(this).val();
if(values == 'Promotional'){
$('#pr_code_id').show();
}else{
$('#pr_code_id').hide();
}
});
});
</script>
and in js if I alert the value of document.getElementById('bus_prcode').value then always it is showing Promotional code, which is only for last radio button value.
Your code is a bit of a mess which is the root of this problem. Remember, one element per ID.
You may also find it helpful to look at jQuery .is(), for example:
$('input[value="Promotional"]').is(':checked')
n.b. I do not suggest the above, you should use identifiers in the appropriate way first.
Also worth noting that your code works fine for me using Chrome. See an example (which I have expanded for you) here: http://jsbin.com/ofujal/3/
You should not have an element with the same ID (your radio buttons). Also, you're getting the textbox by running document.getElementById('bus_prcode') and not the radio button. You should give a unique ID to your last radio button, e.g. btnPromotional, then bind click to it:
$("#btnPromotional").click(...)

Observing change in radio button selection using Prototype JS

I'm relatively new to Prototype JS (v1.7), and I'm stuck on something. I'm trying to detect when a change in the radio button selection occurs. Here's the code:
Radio buttons:
<input class="amounts" type="radio" name="amount" id="amount-1" value="1" />
<input class="amounts" type="radio" name="amount" id="amount-2" value="2" />
<input class="amounts" type="radio" name="amount" id="amount-3" value="3" />
Javascript:
Here's a stab I took at it, which doesn't work:
Event.observe($$('amounts'), 'change', function(event) {
alert('change detected');
});
When the form loads, no radio buttons are checked. I'd like the Javascript to detect these events:
A radio button is selected when none was previously selected
The radio button selection changes
Any help would be greatly appreciated.
It doesn't work because $$ returns an array of elements and Event needs a single element. Also $$('amounts') doesn't match any elements, there are no <amounts> tags.
A better way is to use a single ancestor element which is easy to identify.
<form id="amounts-form">
<input class="amounts" type="radio" name="amount" id="amount-1" value="1" />
<input class="amounts" type="radio" name="amount" id="amount-2" value="2" />
<input class="amounts" type="radio" name="amount" id="amount-3" value="3" />
</form>
Now there is a unique ID to work with we can use Event.on
$('amounts-form').on('change', '.amounts', function(event) {
alert('change detected');
});
Notice the events are being filtered by '.amounts', the period says to use the class name.
If you're using FireBug for FireFox or Chrome's developer tools then you can test parts of your script directly in the console. It really helps to find if a selector is matching the elements you think it is by typing $$('.amounts')
Alternegro's answer attempts to use an iterator to attach the event handler directly to the "amount" radio elements but doesn't work for a few reasons:
The "$" function doesn't take css selectors as parameters, only ids. Use "$$" instead.
The css "id" attribute selector should include square braces "[]". It's also spelled wrong. "amounts-" should be "amount-" to match the ids in the example. Or just use a class selector instead: ".amounts".
There is no "change" method that can be called on enumerables. Use invoke or some other enumerable method instead.
This one should work:
$$("[id^=amount-]").invoke(
'on',
'change',
function(){alert("hello " + this.id)}
)
(YMMV using "this" in the event handler. I only checked the code in Firefox)
Its more efficient to just give those checkboxes the same class but u can also try
$("id^=amounts-").change(function(){alert("blah blah")})

In jQuery, how do I select an element by its name attribute?

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

Categories

Resources