Trigger Button Click when Radio button is selected - javascript

I have two radio buttons, when I select one of radio button (ex: id = one), and click button will be show alert ("one").
here is my code
<input type="radio" name="test" value="one" id="one">one
<input type="radio" name="test" value="two" id="two">two
<button id="click">Click</button>
and my JS
$("#click").click(function(){
if($('input[type="radio"]').attr('id') == 'one'){
alert ("one")
} else{
alert("two")
}
})
My question is why alert two is not show? any body help? thank you
http://jsfiddle.net/dedi_wibisono17/gydrw291/10/

See the docs on .attr:
The .attr() method gets the attribute value for only the first element in the matched set. To get the value for each element individually, use a looping construct...
Because your selector
input[type="radio"]
will always return a collection that contains the #one element in front, your if statement will always evaluate to true.
To fix it, have your selector string select only the radio button that's selected - so, use the :checked psuedo-selector as well:
$("#click").click(function() {
if ($('input[type="radio"]:checked').attr('id') == 'one') {
alert("one")
} else {
alert("two")
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="test" value="one" id="one">one
<input type="radio" name="test" value="two" id="two">two
<button id="click">Click</button>

Related

How can I get the value of the radio button after click

How will I get the value of the radio button after clicked on the button?
document.getElementById('btnKnop1').addEventListener('click', function(){
var kleuren = document.querySelectorAll('input[type=radio');
for (var i in kleuren) {
kleuren[i].onclick = function(){
document.getElementById('divResult'). innerHTML =
'Gekozen kleur: ' + this.value;
}
}
});
<input type="radio" name="radioGroup" value="rood" checked />Rood</br />
<input type="radio" name="radioGroup" value="blauw" />Blauw</br />
<input type="radio" name="radioGroup" value="geel" />Geel</br />
<input type="radio" name="radioGroup" value="groen" />Groen</br />
<button id="btnKnop1">Check de waarde!</button>
<div id="divResult"></div>
Now it depends on click on the radio button, but I'd to depend on click on the button
The issue seems to be be the inner click event on the radio button. If you change the loop to an if statement checking if it's checked then you can output the value on the button click:
document.getElementById('btnKnop1').addEventListener('click', function(){
var kleuren = document.querySelectorAll('input[type=radio');
for (var i in kleuren) {
if (kleuren[i].checked === true) {
document.getElementById('divResult'). innerHTML =
'Gekozen kleur: ' + kleuren[i].value;
}
}
});
<input type="radio" name="radioGroup" value="rood" checked />Rood</br>
<input type="radio" name="radioGroup" value="blauw" />Blauw</br>
<input type="radio" name="radioGroup" value="geel" />Geel</br>
<input type="radio" name="radioGroup" value="groen" />Groen</br>
<button id="btnKnop1">Check de waarde!</button>
<div id="divResult"></div>
First of all, please consider using english-named variables, it will improve readability by a lot.
Second of all, line
var kleuren = document.querySelectorAll('input[type=radio');
has a typo, it's missing a closing square bracket - ].
To check a checkbox/radio button value you can use checkbox.checked, where checkbox is your DOM object selected by querySelector.
You're basically already doing it. When you click the button, in the click handler for the button, just grab the radio button element using a selector (either class or id), with a "querySelector" call (just like you're doing). Inspect that element for whatever property makes sense (probably "checked").
Something like:
<button onclick="onClick ()">Click Me</button>
...
onClick () {
const kleuren = document.querySelector ( [mySelectorByIDorClass, etc.] );
console.log ( kleuren.checked );
}
See here:
https://www.w3schools.com/jsref/prop_radio_checked.asp
The checked property will tell you whether the element is selected:
if (document.getElementById('id').checked) {
var variable = document.getElementById('id').value;
}

Jquery .val() function to check the value of radio buttons

Below is my logic to check the value of each of the radio buttons. I am using a part of their id's to get hold of the radio buttons. However, my code is always returning a value based on the value of my first radio button. I want it to return the value of each radio button. For example if radio button clicked is yes, then value returned should be 1. Else, 0. Any body who can update my code please.
$('.YesNoRadio').each(function() {
if ($('[id*="YesNo_RadioButtonList_"] input[type="radio"]:checked').val() == 1) {
//$('[id*="AddAttachment"]').trigger('click');
$('[id="upload"]').click();
}
});
Html:
//For yes radio button
<input id="_YesNo_RadioButtonList_0" type="radio" name="YesNo_RadioButtonList" value="1">
//For no
<input id="_YesNo_RadioButtonList_0" type="radio" name="YesNo_RadioButtonList" value="0">
Your selector is incorrect, Remove space from selector. When you use " " it indicates you are targeting child elements i.e. Descendant Selector (“ancestor descendant”)
if($('[id*="YesNo_RadioButtonList_"]:radio:checked').val() == 1)
$('[id="upload"]').click();
And, You don't need .each()
//For yes radio button
<input class="YesNoRadio" id="_YesNo_RadioButtonList_0" type="radio" name="YesNo_RadioButtonList" value="1">
//For no
<input class="YesNoRadio" id="_YesNo_RadioButtonList_0" type="radio" name="YesNo_RadioButtonList" value="0">
<script type="text/javascript">
$('.YesNoRadio').each(function() {
if ($(this).is(':checked')) {
alert($(this).val());
//code for yes radio button
$('[id="upload"]').click();
}else{
alert($(this).val());
//code for no radio button
}
});
</script>
A method that worked for me was setting the name in the html input tag the same for each radio button is your list, which you did:
<input id="_YesNo_RadioButtonList_0" type="radio" name="YesNo_RadioButtonList" value="1">
<input id="_YesNo_RadioButtonList_0" type="radio" name="YesNo_RadioButtonList" value="0">
then I would do this is my JS with JQuery.
var radioButtonValue = $("input[name='YesNo_RadioButtonList']:checked").val();
This should give you the value of your radio button. The value, in your case, is preset in you input tag.
Try this code
$('.YesNoRadio').each(function() {
if ($('[id*="YesNo_RadioButtonList_"] input[type="radio"]:checked').val() == 1) {
//$('[id*="AddAttachment"]').trigger('click');
console.log($(this).val());
$('[id="upload"]').click();
}
});

Set hidden input value depending on radio button selection

I have a checklist form that tallies a score based on the radio button selection that is working fine. When I post the form I want to get a value of "yes" or "no" from a hidden input with the same class based on radio button selection.
Because the "value" field is taken up by an integer for the scoring I want to pass a value to a hidden form input with the same class name. The value of the hidden input will be "no" if the value of the radio button selected is 0, or else it will be "yes".
I would like to be able to iterate it through all radio input groups (there are many). This is what I am trying to acheive in jquery written in English:
FOR each radio input group, IF the value of radio button selected is 0 then value of hidden input with the same class is "No", ELSE it is "yes".
I am having trouble with the javascript and would appreciate some assistance.
HTML
<!--Radio button example -->
<li>
<label>Does 1 + 1 equal 10 ?</label>
<input type="radio" class="radio1" name="question" value="1">Yes</input>
<input type="radio" class="radio1" name="question" value="0">No</input>
<input type="hidden" value="" id="answer" class="radio1"></input>
</li>
Thank you in advance, please let me know if you need more information.
Attach a JQuery event to radiobutton change
$(document).ready(function() {
$('input.radio1[type=radio]').change(function() { //change event by class
if (this.value == '0') {
$(this.ClassName[type=hidden]).val("No");
}
else if (this.value == '1') {
$(this.ClassName[type=hidden]).val("Yes");
}
});
});
This code may contain syntax errors, consider this as a pseudo code and Do It Yourself
Give the answers unique IDs if you need to use them
If you add [] to the name of the questions PHP will treat them as array and you can use a ternary to set the value $answer = $question=="1"?"YES":"NO";
If you still need to use a hidden field, here is code that does not look at the ID but at the name and type of field in each LI
$(function() {
//$("#questionnaire").on("submit", // better but not allowed in the SO snippet
$("#send").on("click",
function(e) {
e.preventDefault(); // remove when tested
$("#questionnaire ul li").each(function() {
var $checkedRad = $(this).find('input[name^=question]:checked');
var $answerField = $(this).find("input[name^=answer]");
$answerField.val($checkedRad.val()=="0"?"NO":"YES");
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form id="questionnaire">
<ul id="questions">
<li>
<label>Does 1 + 1 equal 10 ?</label>
<input type="radio" class="radio" name="question1" value="1">Yes</input>
<input type="radio" class="radio" name="question1" value="0">No</input>
<input type="hidden" value="" name="answer1" class="radio"></input>
</li>
<li>
<label>Does 1 + 1 equal 20 ?</label>
<input type="radio" class="radio" name="question2" value="1">Yes</input>
<input type="radio" class="radio" name="question2" value="0">No</input>
<input type="hidden" value="" name="answer2" class="radio"></input>
</li>
</ul>
<button id="send" type="button">Click</button>
</form>
$("input[type='radio']:checked").each(function(i, element) {
var hiddenVal = $(element).value() === "0" ? "No" : "yes"
$("." + $(element).attr("class") + "[type='hidden']").val(hiddenVal);
})

Hide div for Radio button selected value using jquery- Not working

I want to hide a div (AppliedCourse), when radi button value is Agent. I wrote below code but it is not working.
Any idea?
$('#HearAboutUs').click(function() {
$("#AppliedCourse").toggle($('input[name=HearAboutUs]:checked').val()='Agent');
});
<tr><td class="text"><input type="radio" name="HearAboutUs" value="Press">Press & Print media
<input type="radio" name="HearAboutUs" value="Internet">Internet
<input type="radio" name="HearAboutUs" value="Agent">Agent
<input type="radio" name="HearAboutUs" value="Friend">Friend
<input type="radio" name="HearAboutUs" value="Other" checked="checked">Other</td></tr>
Either your HTML is incomplete or your first selector is wrong. It is possible that your click handler is not being called because you have no element with id 'HeadAboutUs'. You might want to listen to clicks on the inputs themselves in that case.
Also, your logic is not quite right. Toggle hides the element if the parameter is false, so you want to negate it using !=. Try:
$('input[name=HearAboutUs]').click(function() {
var inputValue = $('input[name=HearAboutUs]:checked').val()
$("#AppliedCourse").toggle( inputValue!='Agent');
});
I have made a JSFiddle with a working solution: http://jsfiddle.net/c045fn2m/2/
Your code is looking for an element with id HearAboutUs, but you don't have this on your page.
You do have a bunch of inputs with name="HearAboutUs". If you look for those, you'll be able to execute your code.
$("input[name='HearAboutUs']").click(function() {
var clicked = $(this).val(); //save value of the input that was clicked on
if(clicked == 'Agent'){ //check if that val is "Agent"
$('#AppliedCourse').hide();
}else{
$('#AppliedCourse').show();
}
});
JS Fiddle Demo
Another option as suggested by #Regent is to replace the if/else statement with $('#AppliedCourse').toggle(clicked !== 'Agent');. This works too.
Here is the Fiddle: http://jsfiddle.net/L9bfddos/
<tr>
<td class="text">
<input type="radio" name="HearAboutUs" value="Press">Press & Print media
<input type="radio" name="HearAboutUs" value="Internet">Internet
<input type="radio" name="HearAboutUs" value="Agent">Agent
<input type="radio" name="HearAboutUs" value="Friend">Friend
<input type="radio" name="HearAboutUs" value="Other" checked="checked">Other
</td>
Test
$("input[name='HearAboutUs']").click(function() {
var value = $('input[name=HearAboutUs]:checked').val();
if(value === 'Agent'){
$('#AppliedCourse').hide();
}
else{
$('#AppliedCourse').show();
}
});

Check value of radio buttons

<input type="radio" name="group2" value="Water"> Water<br>
<input type="radio" name="group2" value="Beer"> Beer<br>
<input type="radio" name="group2" value="Wine" checked> Tee
<span id="check" >check</span>
And jQuery:
function check()
{
alert($('input[name=group2]').val());
}
$('#check').click(function(){
check();
});
$('input[name=group2]').change(function(){
check()
})
Live: http://jsfiddle.net/j9cj5/
Why this always show me Water? How can i check value of these radio buttons? I would like check this if i change this value and if i click on check.
The selector $('input[name=group2]') will select all the elements with that name, and val() returns only the value for the first element in the collection, so that's always Water. You have to target just the checked radio :
function check() {
alert( $('input[name=group2]:checked').val());
}
FIDDLE
Replace $('input[name=group2]') with $('input[name=group2]:checked') :)
Demo: http://jsfiddle.net/hungerpain/j9cj5/2/
The reason this happens is because $('input[name=group2]') will generate an array of all your radio buttons and thus will give only the first element (which happens by default). So get the selected element, you must use the :checked pseudo selector.
Try like this
function check(val) {
alert(val);
}
$('input[name=group2]').change(function(){
check($(this).val());
});
This is working FIDDLE

Categories