jQuery if/else based on input value - javascript

I have a list of questions that a person can answer yes or no to. At the end, I want to display the question, whether they answered yes or no, and a paragraph about the results. I'm having trouble getting my if/else statement to work.
HTML:
<ol>
<li id='q1'>
<span>Are any of your valuables visible from the street?</span>
<input type="checkbox" class="calc" name="street" value="-1" /> yes
<input type="checkbox" class="calc" name="street" value="1" /> no
<input type="checkbox" name="street" value="0" /> n/a
</li>
</ol>
<div class='darkBtn' id='results'>Get Results ></div>
JS:
$('#results').click(function(){
var q1 = $('li#q1 input:checkbox:checked.calc').val();
if (q1 == 1) {
console.log("You answered No");
} else {
console.log("You answered Yes");
}
});
I've tried every variation I can think of, but the console always prints out "You answered Yes".

It looks like you mean to use radio buttons instead of checkboxes. I put together a quick fiddle of your example using radio buttons.
$(function(){
$("#results").click(function(){
var val = $('input[name=street]:checked').val();
if(val == 1) {
console.log('no');
} else {
console.log('yes');
}
});
});
fiddle

First your checkboxes should not have the same name attribute.
Then you should grab the selected questions using:
$('li#q1 input[type="checkbox"].calc:checked')
Also it appears that you want radio boxes instead of check boxes, in which case you'd be able to use the same name
UPDATE: fiddle

Related

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

Selected Checkbox disables the selection of another checkbox

I have a reason to use checkboxes instead of radio buttons so please don't suggest I use radio buttons but need to duplicate the functionality. However when I select the Yes checkbox, it disables the No checkbox for some reason. When no is selected I want to hide the div and deselect Yes, and the opposite when I select Yes I want to show the div and uncheck NO. The only way I can select NO when Yes is checked is to uncheck it.
Working demo Here
JS Fiddle not working Here
Javascript
function injure() {
if (document.getElementById("f2").checked == true) {
document.getElementById("LocFall").style.display="block";
document.getElementById("f1").checked = false;
} else {
if (document.getElementById("f1").checked == true) {
document.getElementById("LocFall").style.display="none";
document.getElementById("f2").checked = false;
}
}
}
CSS
#LocFall {
display:none;
}
HTML
<input type="checkbox" id="f1" name="" onclick="injure();">
<label for="f1"> No </label><BR>
<input type="checkbox" id="f2" name="" onclick="injure();">
<label for="f2"> Yes</label><BR>
<div id="LocFall">
Show some stuff
</div>
http://jsfiddle.net/6NN6s/14/
<input type="checkbox" id="f1" name="same" onclick="injure(this);" />
<label for="f1">No</label>
<BR>
<input type="checkbox" id="f2" name="same" onclick="injure(this);" />
<label for="f2">Yes</label>
<BR>
<div id="LocFall">Show some stuff</div>
function injure(cmb) {
if (cmb.checked) {
if(cmb.id==="f2")
{ document.getElementById("LocFall").style.display = "block";
document.getElementById("f1").checked = false;
}
else
{
document.getElementById("LocFall").style.display = "none";
document.getElementById("f2").checked = false;
}
}
}
try this out, may be what you need.
In Fiddle change on the left in second drop-down list 'onLoad' to 'no wrap - in <head>'.
Split injure into a different function for each; if you choose No, then you cannot choose Yes because of the way your function is set up - the first condition will always evaluate as true.
The problem stems from not knowing which checkbox was actually clicked inside the function. As it is there's only two different ways the function can respond: one if f1 is checked and one if f2 is checked. The problem is there's actually more possible states that you're trying to represent.
State 1: Nothing checked, user clicks f1 or f2
State 2: f1 checked, f2 clicked
State 3: f2 checked, f1 clicked
Your code handles the first state fine but it can't deal properly with the second ones. If you split your code into two seperate functions to handle each box then you'll have all the necessary information to write correct decision logic.
There's also the states of clicking the same box, but they are simple and your code handles them already.

CheckAll/UncheckAll checkbox with jQuery

I have made a check-box checkall/uncheckall.
HTML
<div> Using Check all function </div>
<div id="selectCheckBox">
<input type="checkbox" class="all" onchange="checkAll('selectCheckBox','all','check','true');" />Select All
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 1
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 2
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 3
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 4
</div>
main.js
function checkAll(parentId,allClass,checkboxClass,allChecked){
checkboxAll = $('#'+parentId+' .'+allClass);
otherCheckBox = $('#'+parentId+' .'+checkboxClass);
checkedCheckBox = otherCheckBox.filter($('input[type=checkbox]:checked'));
if(allChecked=='false'){
if(otherCheckBox.size()==checkedCheckBox.size()){
checkboxAll.attr('checked',true);
}else{
checkboxAll.attr('checked',false);
}
}else{
if(checkboxAll.attr('checked')){
otherCheckBox.attr('checked',true);
}else{
otherCheckBox.attr('checked',false);
}
}
}
It works fine. But get bulky when I have whole lot of checkboxes. I want to do same work by using jQuery rather than putting onchange on each checkbox. I tried different sort of things but couldnot work. I tried following one:
$('.check input[type="checkbox"]').change(function(e){
checkAll('selectCheckBox','all','check','true');
});
to do same work as onchange event but didnot work. Where do I went wrong.
I think you just need this: You do not need to pass all the arguments and have the inline onchange event attached to it. You can simplify your code.
$(function () {
$('input[type="checkbox"]').change(function (e) {
if(this.className == 'all')
{
$('.check').prop('checked', this.checked); //Toggle all checkboxes based on `.all` check box check status
}
else
{
$('.all').prop('checked', $('.check:checked').length == $('.check').length); // toggle all check box based on whether all others are checked or not.
}
});
});
Demo
Your selector is wrong:
.check input[type="checkbox"]
Above selects any input of type checkbox that has the ancestor with class .check. It'll match this:
<div class="check">
<input type="checkbox".../>
</div>
it should be:
input.check[type="checkbox"]
You closed the string here $('.check input[type='checkbox']') instead, you should use double quotes $('.check input[type="checkbox"]')

How to get previous checkbox value and compare

I am trying to create a checkbox limit based on a value change example: I have the following checkbox!
If the value of a checked checked box is different then the previous prompt an alert!
Some of the check boxes do have the same value. Not all of them!
Example:
<input name="" type="checkbox" value="here">(if this was checked)
<input name="" type="checkbox" value="here">(then this)
<input name="" type="checkbox" value="there">(would not allow prompt alert)
<input name="" type="checkbox" value="here">(would allow)
<input type="checkbox" name="checkbox2[]" onClick="setChecks(this)" value="`key`=<?php
echo $rspatient['key']?>" class="chk" id="chk<?php echo $a++?>" />
I have code that limits the number of checkboxes but I'm not sure how to compare previous values to the selected.
You probably want to make use of the prev() and next() jQuery functions. I don't understand well enough what you want to do, but something like $(':checkbox').change(function() { $(this).prev(); //this references the previous sibling }) would get you started
Maybe something like
$('input:checkbox').change(function() {
if ($(this).attr('checked') && $(this).prev().attr('checked') && $(this).attr('value') != $(this).prev().attr('value')) {
alert('you can't do that');
}
});
But like I said, i don't know what you're trying to do

Opening 3 divs based on whether checkbox is checked

I am using the script below to show and hide a div based on whether or not the checkbox is checked, this if so I can show/hide a paypal button until they accept the terms.
But we now want of offer three payment option so it will need to open/close 3 divs, I tried just copying the div 3 times but it still only opened one. Can any body help me with this please?
<script type="text/javascript">
function doInputs(obj){
var checkboxs = obj.form.c1;
var i =0, box;
document.getElementById('mydiv').style.display = 'none';
while(box = checkboxs[i++]){
if(!box.checked)continue;
document.getElementById('mydiv').style.display = '';
break;
}
}
</script>
<form>
<input type="checkbox" name="c1" onclick="doInputs(this)">
</form>
<div id="mydiv" style="display:none">
<input type="text">
</div>
Also it would be amazing if someone could help me add in another checkbox, and make the paypal buttons (divs) only show when BOTH are checked?
Thanks very much!
I also stole Marcus's answer but with the following improvements:
I use the jQuery document ready event so the code fires after the page loads
I simplified the logic
It works for multiple types of payment
http://jsfiddle.net/5Byes/3/
Using jQuery you can have an array or just two variables that are set to false. When a button is checked you set that equivalent value to the opposite of the current value (so if it was false, it would become true and vice-versa).
Here's a simple example of how you could accomplish this: http://jsfiddle.net/5Byes/
Only one element with particular ID is allowed on the page. If you want more — use class attribute.
On the other hand, you could wrap all divs with payments method in one div with ID, let's say, paymentsMethods and then show/hide it.
var paymentsDiv = document.getElementById('paymentsMethods');
if (box.checked) paymentsDiv.show(); else paymentsDiv.hide();
If you want 2 checkboxes — set onclick of both to same handler and change condition to box1.checked && box2.checked.
With jQuery (which is in your question tags) you could do $('#paymentsMethods').toogle() on checkbox click (see also $.hide() and $.show()).
If I understand correctly what you're looking for, you can do it like this:
HTML:
<input id="opt1cb" type="checkbox" value="Option 1" />Option 1<br />
<input id="opt2cb" type="checkbox" value="Option 2" />Option 2<br />
<input id="opt3cb" type="checkbox" value="Option 3" />Option 3<br />
<div class="option" id="opt1">Option 1</div>
<div class="option" id="opt2">Option 2</div>
<div class="option" id="opt3">Option 3</div>
<div class="option" id="opt23">Option 2 & 3</div>
jQuery:
$('.option').hide();
$('#opt1cb').click( function() {
if( $(this).prop("checked") ) {
$('#opt1').show();
} else {
$('#opt1').hide();
}
});
$('#opt2cb').click( function() {
if( $(this).prop("checked") ) {
$('#opt2').show();
if( $('#opt3cb').prop("checked") )
$('#opt23').show();
} else {
$('#opt2').hide();
$('#opt23').hide();
}
});
$('#opt3cb').click( function() {
if( $(this).prop("checked") ) {
$('#opt3').show();
if( $('#opt2cb').prop("checked") )
$('#opt23').show();
} else {
$('#opt3').hide();
$('#opt23').hide();
}
});
​
Working jsfiddle here: http://jsfiddle.net/bCDqa/
http://jsfiddle.net/5Byes/4/
I stole Marcus' fiddle and updated it to do what you want.

Categories