Cannot find an answer:
I have searched Stack Overflow, however, despite finding lots of similar posts — and more complicated situations — I still couldn't find an answer to the issue I am trying to solve.
Here's my issue:
I have four radio buttons, and one hidden field:
<!-- My HTML Document -->
<form action="/my-doc.html" method="post">
<!-- The 4 Radio Buttons-->
<input type="radio" name="game" value="1" checked> First
<input type="radio" name="game" value="2"> Second
<input type="radio" name="game" value="3"> Third
<input type="radio" name="game" value="4"> Fourth
<!-- The Hidden Field -->
<input type="hidden" name="criteria" value="1">
<!-- My Submit Button -->
<input type="submit" name="action" value="Go">
</form>
What I need to do is set the value of <input type="hidden" name="criteria" value="1"> so that it is 0
Like this: <input type="hidden" name="criteria" value="0">
...but only after the user selects either the first, or second, radio button. The value of the hidden field should remain as being equal to 1 if any other radio button is selected.
How does a person do this using JavaScript?
Requirements: "Looking for a VanillaJS answer."
you can try below option
In javascript
function setValue() {
var selectedRadio = '';
var games = document.getElementsByName('game')
for (var i = 0; i < games.length; i++) {
if (games[i].checked) {
selectedRadio = games[i].value;
}
}
document.getElementById("hdnSelectedRadValue").value = (selectedRadio == "1" || selectedRadio == "2") ? "0" : "1";
return false;
}
Changes to do in HTML side
<body style="background-color: #f2f2f2;">
<form action="some.htm" method="post">
<input type="radio" name="game" value="1" checked> First
<input type="radio" name="game" value="2"> Second
<input type="radio" name="game" value="3"> Third
<input type="radio" name="game" value="4"> Fourth
<input type="text" name="criteria" id="hdnSelectedRadValue">
<input type="submit" name="action" value="Go" onclick="setValue();">
</form>
</body>
var radios =
document.querySelectorAll('input[type=radio][name="game"]');
radios.forEach(radio => radio.addEventListener(
'change', () => {
document.getElementsByName("criteria")[0].value =
parseInt(radio.value, 10) > 2 ? '1' : '0';
}
));
<input type="radio" name="game" value="1" checked> First
<input type="radio" name="game" value="2"> Second
<input type="radio" name="game" value="3"> Third
<input type="radio" name="game" value="4"> Fourth
<input type="hidden" name="criteria" value="1">
<input type="submit" name="action" value="Go">
You can simply listen to "change" events on all of the radio buttons, then just set the value accordingly.
Here's the snippet code I have written and tested
(function(){
let hdfValue = document.getElementById("myhiddenfield")
let radioButtons = document.querySelectorAll('input[name="game"]');
let submitButton = document.querySelector('input[name="action"]')
radioButtons.forEach((input) => {
input.addEventListener('change', function(e){
let radioButtonValue = e.target.value
if(radioButtonValue == 1 || radioButtonValue == 2){
hdfValue.value = 0;
} else {
hdfValue.value = 1;
}
});
});
submitButton.addEventListener("click", function() {
console.log(hdfValue.value)
});
})()
<form>
<input type="radio" name="game" value="1" checked> First
<input type="radio" name="game" value="2"> Second
<input type="radio" name="game" value="3"> Third
<input type="radio" name="game" value="4"> Fourth
<input type="hidden" name="criteria" id="myhiddenfield" value="1">
<input type="button" name="action" value="Go">
</form>
Related
I have three different group of radio buttons in my form. If I click on the radio button I don't see attribute checked set to true. I'm wondering what is the best way to handle this in JQuery/JavaScript? Here is example:
$("input[type=radio]").on('click', function() {
var secondClick = true;
$(this).change(function() {
secondClick = false;
});
$(this).click(function() {
if (secondClick) {
$(this).prop("checked", false);
}
secondClick = true;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="myForm" id="myForm" method="POST" action="#">
<div class="formItem">
<label for="evaluation">Evaluation</label>
<input type="radio" name="frm_eval" id="frm_eval1" value="0" />Yes
<input type="radio" name="frm_eval" id="frm_eval2" value="1" />No
</div>
<div class="formItem">
<label for="conditions">Conditions</label>
<input type="radio" name="frm_cond" id="frm_cond1" value="0" />Good
<input type="radio" name="frmhs_cond" id="frm_cond2" value="1" />Fair
<input type="radio" name="frm_cond" id="frm_cond3" value="2" />Poor
</div>
<div class="formItem">
<label for="responses">Responses</label>
<input type="radio" name="frm_res" id="frm_res1" value="0" />Good
<input type="radio" name="frm_res" id="frm_res2" value="1" />Fair
<input type="radio" name="frm_res" id="frm_res3" value="2" />Poor
</div>
</form>
Function above did not change/set the attribute checked=true on the element that I clicked. I would like to see selected element with an attribute checked true and all other check boxes to be set to false.
var radioInputs = $("#myForm input[type=radio]")
radioInputs.on('change',function() {
var $this = $(this)
if ($this.is(':checked')) {
radioInputs.not($this).removeAttr('checked')
}
})
Your second input in conditions was named frmhs_cond instead of frm_cond
<form name="myForm" id="myForm" method="POST" action="#">
<div class="formItem">
<label for="evaluation">Evaluation</label>
<input type="radio" name="frm_eval" id="frm_eval1" value="0" />Yes
<input type="radio" name="frm_eval" id="frm_eval2" value="1" />No
</div>
<div class="formItem">
<label for="conditions">Conditions</label>
<input type="radio" name="frm_cond" id="frm_cond1" value="0" />Good
<input type="radio" name="frm_cond" id="frm_cond2" value="1" />Fair
<input type="radio" name="frm_cond" id="frm_cond3" value="2" />Poor
</div>
<div class="formItem">
<label for="responses">Responses</label>
<input type="radio" name="frm_res" id="frm_res1" value="0" />Good
<input type="radio" name="frm_res" id="frm_res2" value="1" />Fair
<input type="radio" name="frm_res" id="frm_res3" value="2" />Poor
</div>
</form>
I have some generated HTML along the lines of this.
<form id="form_56">
<input type="radio" name="option" value="0">
<input type="radio" name="option" value="1">
<input type="radio" name="option" value="2">
<input type="radio" name="option" value="3">
<input type="radio" name="option" value="4">
<input type="radio" name="option" value="5">
<input type="radio" name="option" value="6">
</form>
The form id can be anything, but I want to take a form ID and return the selected value from 0 to 6.
I tried following the questions here, but they didn't seem to translate easily to a specific form.
$('#form_56:radio[name=option]:checked').val();
I'm able to use the selector to grab the proper form, but everything I've attempted to get the selected value has returned undefined.
Thanks for your time.
First, you need to change the colon to a space or " > ".
Second you need to change radio to input.
$('#form_56 input[name=option]:checked').val();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form_56">
<input type="radio" name="option" value="0">
<input type="radio" name="option" value="1">
<input type="radio" name="option" value="2">
<input type="radio" name="option" value="3">
<input type="radio" name="option" value="4">
<input type="radio" name="option" value="5">
<input type="radio" name="option" value="6">
</form>
<a href="javascript:console.log($('#form_56 input[name=option]:checked').val());">
<button>Test</button>
</a>
$("#form_56 input:radio[name='option']").val()
You need an event for listening when it changes
see example
$(function() {
$("#form_56 input:radio[name='option']").click(function() {
var val = $(this).val();
alert(val);
});
});
https://jsfiddle.net/rodrigo/cp8rd7h0/
problem in your code: on change event not assign to radio button so undefined alert popup
here is solution:
$(document).ready(function () {
$('input[type=radio]').on('change', function () {
alert($('input[name=option]:checked', '#form_56').val());
});
});
For any form:
$('form>input[type="radio"]:checked').val()
With id:
$('#form_56>input[type="radio"]:checked').val()
It will return selected value or undefined, if no value selected.
Good luck!
function getSelectedValue()
{
return $('form>input[type="radio"]:checked').val();
}
$(function() {
$('button').on(
'click',
function() {
console.log(getSelectedValue() + ' selected');
}
);
});
form {display: inline}
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<form id="randomId-839054763">
<input type="radio" name="option" value="0">
<input type="radio" name="option" value="1">
<input type="radio" name="option" value="2">
<input type="radio" name="option" value="3">
<input type="radio" name="option" value="4">
<input type="radio" name="option" value="5">
<input type="radio" name="option" value="6">
</form>
<button>Log value</button>
How to count the total value of radio button within the same page and pass to another php file? The total will be count at this page and i can get the total from answer.php file.
<form action="answer.php" method="POST">
<input type="radio" name="q1" value="1" />Yes <br />
<input type="radio" name="q1" value="0" />No <br />
<input type="radio" name="q2" value="2" />Yes <br />
<input type="radio" name="q2" value="0" />No <br />
<input type="radio" name="q3" value="3" />Yes <br />
<input type="radio" name="q3" value="0" />No <br />
<input type="submit" value="submit" name="submit"/>
</form>
I suggest using an array to count your values.
<input type="radio" name="q[]" value="2" />
<input type="radio" name="q[]" value="3" />
<input type="radio" name="q[]" value="4" />
<input type="radio" name="q[]" value="5" />
This will result in $_POST['q'] being an array. You can now do:
echo "The total amount is ".array_sum($_POST['q']);
Using jQuery- it is easy, just iterate through the inputs and tally up the values. Note that I gave the form an Id so it can be targetted directly if you have other form. The total can be passed to your other page - either via AJAX or using a standard HTML form as a hidden field. Alternatively - since this is a form and you are already passing it to a PHP page - you could simply submit the form and tally up the $_POST variables on the other side.
$('#testForm input').on('change', function() {
var total=0;
$('input[type=radio]:checked', '#testForm').each(function(){
total += parseInt($(this).val());
})
alert(total)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="testForm" action="answer.php" method="POST">
<input type="radio" name="q1" value="1" />Yes <br />
<input type="radio" name="q1" value="0" />No <br />
<input type="radio" name="q2" value="2" />Yes <br />
<input type="radio" name="q2" value="0" />No <br />
<input type="radio" name="q3" value="3" />Yes <br />
<input type="radio" name="q3" value="0" />No <br />
<input type="submit" value="submit" name="submit"/>
</form>
Commented version for the OP:
$('#testForm input').on('change', function() {//triggers the function on any change in the form
var total=0;//initialises the total at 0 so that each round ottallying up resets before the tally
$('input[type=radio]:checked', '#testForm').each(function(){//selects each input in the #testForm that is checked
total += parseInt($(this).val());//adds the value of each checked radio button to the tally
})
alert(total); //alerts the final tally after all iterations
});
You don't need jquery for this. Add a class to your radio buttons so we can query them without risking getting other elements in the page, something like "my-radio"
This javascript will get you the sum:
function getRadioButtonsSum(radioClass) {
var radioBtns = document.querySelectorAll(radioClass);
var count = 0;
var i;
for (i = 0; i < radioBtns.length; i += 1) {
if (radioBtns[i].checked) {
count += +radioBtns[i].value;
}
}
return count;
}
getRadioButtonsSum('.my-radio');
I want to check all checkboxes using javascript. When I click on submit button all the checkboxes should be checked. However all the checkboxes are checked just for a few seconds.
What am I doing wrong?
html:
<form method="post" name="myform">
<input type="checkbox" name="h" value="1" id="g">Reading<br/>
<input type="checkbox" name="h" value="2" id="g">php<br/>
<input type="checkbox" name="h" value="3" id="g">playing<br/>
<input type="checkbox" name="h" value="4" id="g">Gaming<br/>
<input type="checkbox" name="h" value="5" id="g">Coding<br/>
<input type="submit" name="sub" value="submit" onclick="checkall(document.myform.h)" >
</form>
javascript code:
<script type="text/javascript">
function checkall(chk){
for(var i = 0; i < chk.length; i++) {
chk[i].checked = true;
}
}
</script>
the problem is you are using a submit button within a form, which on click will submit the form.
So one solution is to change the button form a submit button to a normal button which will not trigger the submit of the form.
function checkall(chk) {
var i;
for (i = 0; i < chk.length; i++) {
chk[i].checked = true;
//return true;
}
}
<form method="post" name="myform">
<input type="checkbox" name="h" value="1" id="g">Reading
<br/>
<input type="checkbox" name="h" value="2" id="g">php
<br/>
<input type="checkbox" name="h" value="3" id="g">playing
<br/>
<input type="checkbox" name="h" value="4" id="g">Gaming
<br/>
<input type="checkbox" name="h" value="5" id="g">Coding
<br/>
<!--<input type="radio" name="gen" value="male">Male<br/>-->
<!--<input type="radio" name="gen" value="female">Female<br/>-->
<input type="button" name="sub" value="submit" onclick="checkall(document.myform.h)">
</form>
You created a form.And form will be submit after click on submit button.You can use following approach to select all checkbox only.
step 1- Write following statement in html.
<input type="checkbox" name="h" value="1" class="g">Reading<br/>
<input type="checkbox" name="h" value="2" class="g">php<br/>
<input type="checkbox" name="h" value="3" class="g">playing<br/>
<input type="checkbox" name="h" value="4" class="g">Gaming<br/>
<input type="checkbox" name="h" value="5" class="g">Coding<br/>
<input type="button" name="sub" value="check all" id='custom_button'>
step 2- Write following statement in js file-
jQuery('#custom_button').click(function(){
jQuery('.g').each(function() { //loop through each checkbox
this.checked = true; //deselect all checkboxes with class "checkbox1"
});
});
Above statement will select all checkbox after click on button.
If you want to check example please use this link - http://jsfiddle.net/oxg3p1ny/1/
your code is working just stop from form submit will solve your problem use <form method="post" name="myform" onsubmit="return false"> and use ajax to get data.
Working Fiddle
I have a few radio buttons, and when I select one of them, I also have to check another one.
For example, if I select yes on a radio button, another radio button must be automatically checked with no.
I tried a few scripts but don't seem to work.
Does anyone know a solution? I'm new in JS.
Thanks in advance!
> Live Demo <
<!--HTML-->
<input type="radio" name="group_1" value="yes" id="r1">Yes<br>
<input type="radio" name="group_1" value="no" id="r2">No<br>
<br>
<input type="radio" name="group_2" value="yes" id="r3">Yes<br>
<input type="radio" name="group_2" value="no" id="r4">No<br>
//Script
$("input[name='group_1']").click(function(){
if(this.value=="yes"){
$("input#r4").attr("checked",true);
}else{
$("input#r3").attr("checked",true);
}
});
$("input[name='group_2']").click(function(){
if(this.value=="yes"){
$("input#r2").attr("checked",true);
}else{
$("input#r1").attr("checked",true);
}
});
I'm not very certain on what you are trying to achieve but by using the "name" attribute this automatically happens...when you check one radio...the others with the same name get set to unchecked.
<input type="radio" name="someoption" value="0" />0
<input type="radio" name="someoption" value="1" />1
<input type="radio" name="someoption" value="2" />2
checking any one of the above will cause the other 2 to be unchecked
unless do you may be mean checkboxes or multiple option sets ?
javascript:
$('#myradio1').bind('change', function () {
$('#myradio3').attr('checked', 'checked');
});
html
<input type="radio" name="cols1" value="1" id="myradio1" />
<input type="radio" name="cols1" value="2" id="myradio2" />
<input type="radio" name="cols2" value="1" id="myradio3" />
<input type="radio" name="cols2" value="2" id="myradio4" />
see working example at http://jsfiddle.net/9jXbv/
For HTML markup like below:
<div>
<input type="radio" name="one" value="yes"> yes
<input type="radio" name="one" value="no"> no
</div>
<div>
<input type="radio" name="two" value="yes"> yes
<input type="radio" name="two" value="no"> no
</div>
you can use this JavaScript code:
$(":radio").on("change", function() {
var that = this;
$(":radio").filter(function() {
return this.value == "no" && this.name != that.name;
}).prop("checked", true);
});
DEMO: http://jsfiddle.net/nKLMX/
With jquery:
$("#radio1").change(function() {
$("#radio2").removeAttr("checked");
});
http://jsfiddle.net/
I've mocked up a pure JS solution to this ( No libraries )
<input type="radio" name="g1" value="1" />Yes
<br />
<input type="radio" name="g1" value="0" />No
<br /><br />
<input type="radio" name="g2" value="1" />Yes
<br />
<input type="radio" name="g2" value="0" />No
<script type="text/javascript">
var g1 = document.getElementsByName('g1'); // store g1 elements
var g2 = document.getElementsByName('g2'); // store g2 elements
// handle click functionality
function radio_checked_event(obj, f) {
if(obj.addEventListener) {
obj.addEventListener('click', f, false);
} else if(obj.attachEvent) {
obj.attachEvent('onclick', f);
}
}
// when you click on g1 yes
radio_checked_event(g1[0], function() {
//set g1 no to checked
g2[1].setAttribute('checked', 'checked');
});
</script>