Check if checkbox checked property is not empty using jQuery - javascript

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

Related

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

How to hide element based on id in JQuery?

I have dynamic table and one of my columns are two radio buttons. I have to check for the values of those two and if value id greater than 0 I have two hide them both. I have a problem to find the way how to pass ID that I set on the label that holds both radio buttons. Here is my HTML code:
<label id="hideRadio_5">
<input type="radio" name="block" class="blockYes" id="block_1" value="2245"/>
<span>Yes</span>
<input type="radio" name="block" class="blockNo" id="block_2" value="2245"/>
<span>No</span>
</label>
<label id="hideRadio_6">
<input type="radio" name="block" class="blockYes" id="block_1" value="0"/>
<span>Yes</span>
<input type="radio" name="block" class="blockNo" id="block_2" value="0"/>
<span>No</span>
</label>
and here is mu JQuery code:
$j( document ).ready(function() {
/*$j('.blockYes').each(function() {
if($j(this).val() > 0){
$j('.hideRadio').hide();
}
});*/
$j('input.blockYes[value="0"]').prop("checked", true);
$j('input.blockNo[value="-1"]').prop("checked", true);
$j('input.blockNo[value=""]').prop("checked", true);
});
JQuery that I use above works properly and checks radio buttons based on the values but my logic to hide the label does not work. Problem is because I used the class on my labels and in that case all radio buttons were hidden. Then I switched to ID and now I do not how to pass that ID from each label and check the value. If value is greater than 0 I want to HIDE that label. If anyone can help with this problem please let me know. Thanks.
Do it this way
$('.blockYes').each(function() {
if($(this).val() > 0){
$(this).parent().hide();
}
});
Fiddle: Demo

Add Value from One Text Input Field to A Pre Populated Input Field

I have an input field that gets populated by the values of checkboxes in a form. That part works perfectly fine, so the input field labeled total will display the sum of checkbox1 + checkbox2 etc. depending on which boxes are checked. My client added the extra obstacle of having a text input field where users can manually enter any additional costs and this gets added to the sum of total as well.
This is what the form currently looks like:
<div class="checkbox">
<label>
<input type="checkbox" name="checkbox" id="outside" class="sum" value="1" data-toggle="checkbox"/>
Outside Wash
</label>
</div><br/>
<div class="checkbox">
<label>
<input type="checkbox" name="checkbox" id="aclean" class="sum" value="1" data-toggle="checkbox"/>
A - Clean: Wash Vacuum, Windows, Wheels/Tires, Wax
</label>
</div><br/>
<div class="checkbox">
<label>
<input type="checkbox" name="checkbox" id="bclean" class="sum" value="1" data-toggle="checkbox">
B - Clean: Same as A above <em>PLUS:</em> Shampoo Interior, Clean/Dress Interior Panels, Remove Bugs/Tar.
</label>
</div><br/>
<div class="checkbox">
<label>
<input type="checkbox" name="checkbox" id="cclean" class="sum" value="1" data-toggle="checkbox">
C - Clean: Same as B above <em>PLUS:</em> Compound Polish Exterior, Clean/Dress Moldings as Needed.
</label>
</div>
These are the 2 text input fields. The total field currently grabs the sum of those checkboxes. The inputSpecial field is where the user will manually type in any additional charges.
<label for="inputSpecial">Special Price</label><br/>
<input type="special" class="form-controlv sum" id="inputSpecial" placeholder="Enter Price for Any Additional Services">
<label for="total"><strong>Total Price</strong></label><br/>
<input type="text" class="form-control" id="total">
And lastly, here is the javascript that is running behind the form and adding the values. I'd like to build on this code rather than scrapping it for something else.
$(document).ready(function() {
function updateSum() {
$("#total").val($(".sum:checked").length);
}
// run the update on every checkbox change and on startup
$("input.sum").change(updateSum);
updateSum();
})
You want to use parseFloat when adding the value else you will add concatenate a string of numbers.
Checking to see if the value isNaN will also handle any invalid values and use 0 instead of NaN.
Add the change event to handle changed to #inputSpecial as well. Also changed length to value to get valid sum of values.
https://jsfiddle.net/SeanWessell/gwco6uj3/
$(document).ready(function() {
function updateSum() {
var total = 0;
var $special = $('#inputSpecial');
$(".sum:checked").each(function() {
var val = isNaN(parseFloat(this.value)) ? 0 : parseFloat(this.value);
total += val;
})
var addl = isNaN(parseFloat($special.val())) ? 0 : parseFloat($special.val());
$("#total").val(Math.round((total + addl) * 100) / 100);
}
// run the update on every checkbox change and on startup
$("input.sum,#inputSpecial").change(updateSum);
updateSum();
});
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
You could do it like this:
$("#total").val($(".sum:checked").length + parseFloat($("#inputSpecial").val());
However, I don't think that $(".sum:checked").length is the best way to do the initial summation. It assumes that all four checkboxes have the same monetary value (which is exactly $1).
So you'd probably want something more like:
var sumTotal = 0;
$(".sum:checked").each(function() {
sumTotal += $(this).val();
});
sumTotal += parseFloat($("#inputSpecial").val()
$("#total").val(sumTotal);

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

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"]')

Categories