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);
})
Related
In my web form I am generating multiple checkboxes dynamically. hence they are not in the control. I am trying to get the value using Request.Form[name] but it is not correct
<input type="checkbox" name="Suppresision" value="Suppresision" />Suppresision
Now I have a add button which dynamically (using Javascript) add more similar checkbox. So within my table element now I have
<input type="checkbox" name="Suppresision" value="Suppresision" />Suppresision
<input type="checkbox" name="Suppresision" value="Suppresision" />Suppresision
<input type="checkbox" name="Suppresision" value="Suppresision" />Suppresision
How do I try to get the values of all three ? I am doing the same for textbox but when I use Request.Form[textbox name] I get a comma separated values of all of them. But for the checkbox I do Request.Form["Suppresision"] I only get one value that too Suppresision instead of checked or not checked.How do I get all three value even if it not checked
If you absolutely need to get a list of all the checkbox controls you have dynamically added you could assemble them into a hidden input when you submit the form.
You need to include a hidden input for each set of checkboxes you add with a name like name="[checkbox name]_allValues"
<input type="checkbox" name="Suppresision" value="Suppresision1" />Suppresision 1
<input type="checkbox" name="Suppresision" value="Suppresision2" />Suppresision 2
<input type="checkbox" name="Suppresision" value="Suppresision3"/>Suppresision 3
<input type='hidden' value='' name="Suppresision_allVals">
Then add in this jQuery to loop the checkbox groups and you will have access to the full list of values for each checkbox on the server.
$(document.forms[0]).submit(function(event){
$('input[type=checkbox]').each(function( index ) { //loop all checkboxes
$itm = $( this );
$allVals = $('input[name=' + $itm.attr('name') + '_allVals]').first();
if ($allVals.length) { //see if we have a hidden input
$allVals.val($allVals.val()
+ ($allVals.val().length > 0 ? ',' : ' ') //add delemiter
+ ($itm.is(':checked') ? $itm.val() : '')); //add value
}
});
});
This way you will have access to the full list in Request.Form["Suppresision_allVals"] with blank values for unchecked boxes similar to what you have for empty textbox controls now.
You have same name attribute value for the three checkboxes. You should have different to make sure they can be read separately from the request form's collection on the server side. Also, in case of checkboxes, it should be checked attribute. Hopefully this will put you the right direction.
<input type="checkbox" name="Suppresision1" checked="checked" />
<input type="checkbox" name="Suppresision2" checked="" />
<input type="checkbox" name="Suppresision3" checked="" />
<input type="checkbox" class="chkItems" name="Suppresision1" checked="checked" />
<input type="checkbox" class="chkItems" name="Suppresision2" checked="" />
<input type="checkbox" class="chkItems" name="Suppresision3" checked="" />
var chkValue = [];
$('.chkItems:checked').each(function(i, e) {
chkValue.push({
chkItem : $(this).val()
});
});
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();
}
});
How can I check checkboxes checked property? If any of them is not checked, display this sentence in span: "you shoud select one of them". My validation don't work.
<label>
<input type="checkbox" name="chk[]" id="chk[]" />male
</label>
<label>
<input type="checkbox" name="chk[]" id="chk[]" />female
</label>
<script>
if ($('input[name="chk[]"]:checked').length < 0) {
$("#textspan").html('you shoud select one of them');
}
</script>
As far as your specific question goes, when no checkbox is checked $('input[name="chk[]"]:checked').length is 0, not negative - so you should change the condition from if ($('input[name="chk[]"]:checked').length < 0) to if ($('input[name="chk[]"]:checked').length == 0)
Full example
Other than that, some side notes:
1. I'd use radio buttons (as it is more suitable for your current male / female selection).
2. You have the same ID (chk[]) twice, which renders your HTML invalid.
3. The [] characters in the ID are not permitted in HTML 4.1 standards, and do not suit the convention.
I took the liberty of changing the code a bit, as your HTML is a bit strange.
Working example: http://jsfiddle.net/a4jzvoou/
HTML:
<div>
<input type="checkbox" class='gender' id="male">male</input>
<input type="checkbox" class='gender' id="female">female</input>
</div>
<button class="validate">Validate</button>
JS:
$(function() {
$('.validate').click(function(event) {
var checkedCount = ($('input[class="gender"]:checked').length))
})
});
I'm trying to compare the selected radio button value to a predetermined value, then display text corresponding to either a match or not a match. This seems like it should be simple enough but it is displaying the "match" text regardless of whether the two values match or not.
Here's my code:
submit: function() {
$("#submit").click(function(){
if($("input:radio[name=answers]:checked").val() == triviaGame.correctSelection) {
$("#result").text("Correct!");
} else {$("#result").text("I'm sorry, you did not select the correct answer :(");}
});
I've also tried:
submit: function() {
$("#submit").click(function() {
if ($("input:radio[name=answers]:checked").val() == triviaGame.questions[questionSelectNum].choices[triviaGame.questions[questionSelectNum].choices[0]]) {
$("#result").text("Correct!");
} else {$("#result").text("I'm sorry, you did not select the correct answer :(");}
});
And I've tried === and == as well as other syntax tweaks.
I checked to make sure I was setting the values of the radio buttons correctly in my nextQuestion method and my test worked so I don't think that's the problem. What puzzles me the most is that the if (true) code executes when it shouldn't instead of the else (false) code executing when it shouldn't, which I think would be a more likely bug.
Here's my HTML:
<div>
<button id = "nextQuestion">Next Question</button>
<br></br>
<div id = "questionDisplay"></div>
<br></br>
<input type="radio" id= "1" name="answers" value="defaultVal">
<label id= "labelOne">Answer 1</label>
<br></br>
<input type="radio" id= "2" name="answers" value="defaultVal">
<label id= "labelTwo">Answer 2</label>
<br></br>
<input type="radio" id= "3" name="answers" value="defaultVal">
<label id= "labelThree">Answer 3</label>
<br></br>
<input type="radio" id= "4" name="answers" value="defaultVal">
<label id= "labelFour">Answer 4</label>
<br></br>
<button id = "submit">Submit</button>
<br></br>
<div id= "result">Please select an answer above</div>
</div>
Here's a link to the full code at jsbin.
Apologies, I got the wrong end of the stick at first, I think you just need to update this section:
//sets the values of each radio button to the same value as each radio's corresponding answer
$("#1") .val(triviaGame.firstAnswer);
$("#2") .val(triviaGame.firstAnswer);
$("#3") .val(triviaGame.firstAnswer);
$("#4") .val(triviaGame.firstAnswer);
With this:
//sets the values of each radio button to the same value as each radio's corresponding answer
$("#1") .val(triviaGame.firstAnswer);
$("#2") .val(triviaGame.secondAnswer);
$("#3") .val(triviaGame.thirdAnswer);
$("#4") .val(triviaGame.fourthAnswer);
http://jsbin.com/OKecora/1/edit
What method would be best to use to selectively set a single or multiple radio button(s) to a desired setting with JavaScript?
Very simple
radiobtn = document.getElementById("theid");
radiobtn.checked = true;
the form
<form name="teenageMutant">
<input value="aa" type="radio" name="ninjaTurtles"/>
<input value="bb" type="radio" name="ninjaTurtles"/>
<input value="cc" type="radio" name="ninjaTurtles" checked/>
</form>
value="cc" will be checked by default, if you remove the "checked" non of the boxes will be checked when the form is first loaded.
document.teenageMutant.ninjaTurtles[0].checked=true;
now value="aa" is checked. The other radio check boxes are unchecked.
see it in action: http://jsfiddle.net/yaArr/
You may do the same using the form id and the radio button id. Here is a form with id's.
<form id="lizardPeople" name="teenageMutant">
<input id="dinosaurs" value="aa" type="radio" name="ninjaTurtles"/>
<input id="elephant" value="bb" type="radio" name="ninjaTurtles"/>
<input id="dodoBird" value="cc" type="radio" name="ninjaTurtles" checked/>
</form>
value="cc" is checked by default.
document.forms["lizardPeople"]["dinosaurs"].checked=true;
now value="aa" with id="dinosaurs" is checked, just like before.
See it in action: http://jsfiddle.net/jPfXS/
Vanilla Javascript:
yourRadioButton.checked = true;
jQuery:
$('input[name=foo]').prop('checked', true);
or
$("input:checkbox").val() == "true"
You can also explicitly set value of radio button:
<form name="gendersForm">
<input type="radio" name="gender" value="M" /> Man
<input type="radio" name="gender" value="F" /> Woman
</form>
with the following script:
document.gendersForm.gender.value="F";
and corresponding radio button will be checked automatically.
Look at the example on JSFiddle.
/**
* setCheckedValueOfRadioButtonGroup
* #param {html input type=radio} vRadioObj
* #param {the radiobutton with this value will be checked} vValue
*/
function setCheckedValueOfRadioButtonGroup(vRadioObj, vValue) {
var radios = document.getElementsByName(vRadioObj.name);
for (var j = 0; j < radios.length; j++) {
if (radios[j].value == vValue) {
radios[j].checked = true;
break;
}
}
}
Try
myRadio.checked=true
<input type="radio" id="myRadio">My radio<br>
$("#id_of_radiobutton").prop("checked", true);
I am configuring a radio button within a document fragment and tried using radiobtn.checked = true;.
That didn't work so I instead went with this solution:
radiobtn.setAttribute("checked", "checked");
This sets checked using name to cycle through the elements and a value check to set the desired element to true. I kept it as simple as possible, its pretty easy to put it into a function or a loop, etc.
variable 'nameValue' is the radio elements name value
variable 'value' when matched sets the radio button
Array.from( document.querySelectorAll('[name="' + nameValue + '"]') ).forEach((element,index) =>
{
if (value === element.value) {
element.checked = true;
} else {
element.checked = false;
}
});