Checkbox validation with different name - javascript

I am getting multiple dynamic checkbox with 2 different name one is InProcess and other one is Requested, if user selects check-boxes named InProcess then alert box should be displayed when he selects the checkbox containing the name requested, can anyone guide me how to do that ?

Like this? I assume more than one set and I also assume the container is static
$(".container").on("change", "[type=checkbox]", function() {
if ($(this).is("[name=Requested]") &&
$(this).siblings("[name=InProcess]").is(":checked")) {
alert("In progress")
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<input type="checkbox" name="InProcess" />
<input type="checkbox" name="Requested" />
</div>
<div class="container">
<input type="checkbox" name="InProcess" />
<input type="checkbox" name="Requested" />
</div>

You could do it like this:
$(document).on("change", "input[name='Requested']", function() {
if ($("input[name='InProcess']").prop("checked") == true && $(this).prop("checked") == true) {
alert("InProcess is checked");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="InProcess"/>
<input type="checkbox" name="Requested"/>

Related

Remove part of form when checkbox is checked

I'm trying to make a form that will hide and show some parts of the form. It working correctly in some tries. But when the user chooses and checks an option with class badCheckbox which is showing badField subsequently then user checks option without class badCheckbox which should showing 'goodField' than 'badField' is not hiding and still is shown.
And when a user tries to check options separately all work correctly only in upper mentioned case.
Is there any way to do it?
//Script to hide and show div
$('.badCheckbox').change(function() {
let checked = 0;
$('.badCheckbox').each(function() {
if (this.checked) {
checked += 1;
}
});
if (checked != 0) {
$('#badField').show();
$('#goodField').hide();
} else {
$('#badField').hide();
$('#goodField').show();
}
});
//script to check only one of three
$(".oneChecked").on('click', function() {
// in the handler, 'this' refers to the box clicked on
var $box = $(this);
if ($box.is(":checked")) {
var group = "input:checkbox[name='" + $box.attr("name") + "']";
$(group).prop("checked", false);
$box.prop("checked", true);
} else {
$box.prop("checked", false);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="checkin" type="checkbox" class="oneChecked badCheckbox" />
<input name="checkin" type="checkbox" class="oneChecked badCheckbox" />
<input name="checkin" type="checkbox" class="oneChecked" />
<div id="badField" style="display:none;">
<p>:((</p>
<input type="submit" />
</div>
<div id="goodField">
<p>NICE!!!</p>
<input type="submit" />
</div>
here is a short version
$('#checks').on('change', 'input[name="checkin"]', function (){
if( $(this).is(':checked') ){
$('#checks .oneChecked:checked').prop('checked', false);
$(this).prop('checked', true);
} else {
$('#checks .oneChecked:checked').prop('checked', false);
$(this).prop('checked', false);
}
if( $('#checks .badCheckbox:checked').is(':checked') ){
$('#badField').show();
$('#goodField').hide();
} else {
$('#badField').hide();
$('#goodField').show();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="checks">
<input name="checkin" type="checkbox" class="oneChecked badCheckbox"/>
<input name="checkin" type="checkbox" class="oneChecked badCheckbox"/>
<input name="checkin" type="checkbox" class="oneChecked"/>
</div>
<div id="badField" style="display:none;">
<p>:((</p>
<input type="submit"/>
</div>
<div id="goodField">
<p>NICE!!!</p>
<input type="submit"/>
</div>
Consider the following improvements.
$(function() {
function checkStuff(checked) {
if (checked) {
$('#badField').show();
$('#goodField').hide();
} else {
$('#badField').hide();
$('#goodField').show();
}
}
//script to check only one of three
$(".boxes").on('change', ".oneChecked", function() {
if ($(this).is(":checked")) {
$(".boxes input[type='checkbox']").prop("checked", false);
$(this).prop("checked", true);
checkStuff($(this).is(".badCheckbox"));
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="boxes">
<input name="checkin" type="checkbox" class="oneChecked badCheckbox" />
<input name="checkin" type="checkbox" class="oneChecked badCheckbox" />
<input name="checkin" type="checkbox" class="oneChecked" />
</div>
<div id="badField" style="display:none;">
<p>:((</p>
<input type="submit" />
</div>
<div id="goodField">
<p>NICE!!!</p>
<input type="submit" />
</div>
it's because you don't have an event when user click and the third checkbox.
Your function to show/hide message work when there are an update (change) on an input with the class .badCheckbox but when you click on the third (where doesn't have the class) your function is not called.
I think you should have a class on all your checkbox and use it in your function who lister the change.
Something like this :
$('.checkbox').change(function() {
let checked = 0;
$('.badCheckbox').each(function() {
// ...
});
And your html
<input name="checkin" type="checkbox" class="checkbox oneChecked badCheckbox"/>
<input name="checkin" type="checkbox" class="checkbox oneChecked badCheckbox"/>
<input name="checkin" type="checkbox" class="checkbox oneChecked"/>
There is a lot of optimization that can be done to improve your code, like using the radio to remove your oneChecked function or printing the right message when the checkbox is checked instead of using show/hide two div but i think you should see it in the future
I hope this can help you and welcome to StackOverflow
First of all, obviously your checkboxes have to act like radios. As I understand, that is what you want to do. So, I modifyed your script a little bit to make checkboses to act as they are radio inputs, and in the same time to show/hide paragraph, depending on if clicked element has class badCheckbox and it's state (checkd or not). Here is the result:
//Script to hide and show div
$('.oneChecked').click( (everyOne) => {
//handles click (and change) on every element with class oneChecked
//they all has it in your example
$('.oneChecked').each( (ind, currentOne) => {
//iterate to all elements with class oneChecked
//and compare if matches clicked one
if ( !$(currentOne).is($(everyOne.target)) ) {
//other instance, not clisked one, so clear it
//to simulate behaviour of radio input
$(currentOne).prop('checked', false);
}
});
//checks if clicked element is bad or not and show/hide your p
if ($(everyOne.target).hasClass('badCheckbox') && $(everyOne.target).prop('checked')){
console.log('b-s/h');
$('#badField').show();
$('#goodField').hide();
} else {
console.log('s/b-h');
$('#badField').hide();
$('#goodField').show();
}
});
Here is an workign example in CodePen: https://codepen.io/kalatchev/pen/gOpJBOv

How to use Javascript/JQuery to verify that at least two fields in a checkbox are selected?

I am trying to create Javascript verification code for a form, so that each section of the form is verified after hitting "submit". I am having trouble writing the code so that the checkbox section of the form verifies that two or more boxes have been selected. I tried to start simple by writing the code so that a div, errorcheckbox, would display a message if no checkbox is selected at all. However it does not work. Here is the HTML and script for the code pertaining to the checkbox:
HTML:
<form action="#" method="POST">
<div class="contactForm">
<label for="checkbox" id="checkbox" name="checkbox">Contactee Type: </label><br>
<div id="errorcheckbox" class="error"></div>
<input type="checkbox" name="type1" value="Individual">Individual<br>
<input type="checkbox" name="type2" value="Catering">Business:Catering<br>
<input type="checkbox" name="type3" value="Partner">Business:Partner<br>
</div>
<div class="button"><input type="button" name="submit" id="submit" value="Submit"></div>
</form>
and the Javascript:
$("document").ready(function(){
console.log("Loaded");
$("#submit").click(function(){
checkContactee();
});
$("#checkbox").change(function(){
console.log("Something in contactee changed");
checkContactee();
});
function checkContactee(){
if (document.getElementById("checkbox").checked == false){
$("#errorcheckbox").html("<p>You missed this field</p>");
$("#errorcheckbox").addClass("showerror");
}
else{
$("#errorregarding").html("");
$("#errorregarding").removeClass("showerror");
}
}
Right now, the code does nothing. The errorcheckbox div doesn't appear, and there is no change in the console log if a checkbox item is selected. So, this is one problem I'm having. I still need to verify that two or more of the boxes are checked. I'm hoping to do this by adding an if else statement to the checkContactee function, but am not sure how.
Looking at your code I would recommend a couple of things. Your check boxes look like you want to capture multiple values for a contact type, so they should have the same name attribute. Each check box should have it's own label and where you have a label now you should use a fieldset and legend.
By wrapping the checkboxes in a fieldset we can then use that as part of the validation process.
$("document").ready(function() {
console.log("Loaded");
$("fieldset[data-mincheckboxchecked] [type=checkbox]").on("click", function() {
console.log("Click")
//Get the parent fieldset
let $parent = $(this).closest("fieldset[data-mincheckboxchecked]");
validateMultiCheckBox($parent);
});
});
function validateMultiCheckBox($parent) {
console.log($parent)
//Get minimum checked from the data attribute
let minCheked = $parent.data("mincheckboxchecked");
minChecked = parseInt(minCheked, 10);
//Get the number of checked checkboxes in the parent
let numCheked = $parent.find("[type=checkbox]:checked").length;
//Validation Logic
if (numCheked < minCheked) {
$parent.find(".error").html("<p>Please select at least " + minChecked + " option" + (minCheked !== 1 ? "s" : "") + "</p>");
$parent.find(".error").addClass("showerror");
return false;
} else {
$parent.find(".error").html("");
$parent.find(".error").removeClass("showerror");
return true;
}
}
$("#submit").click(function() {
var isValid = false;
var multiCheckValid = true;
//Validate each group of multi checkboxes
$("fieldset[data-mincheckboxchecked]").each(function() {
console.log(this);
if (!validateMultiCheckBox($(this))) {
multiCheckValid = false;
}
})
//Normally you'e set this to return false, leaving like
//this for demo purposes
console.log(multiCheckValid);
return isValid;
});
.error {
display: none;
color: red;
}
.error.showerror {
display: block;
}
fieldset label {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#" method="POST">
<div class="contactForm">
<fieldset data-mincheckboxchecked="2">
<legend>Contactee Type: </legend>
<div id="errorcheckbox" class="error"></div>
<label><input type="checkbox" name="contactType" value="Individual">Individual</label>
<label><input type="checkbox" name="contactType" value="Catering">Business:Catering</label>
<label><input type="checkbox" name="contactType" value="Partner">Business:Partner</label>
</fieldset>
<fieldset data-mincheckboxchecked="1">
<legend>One Required: </legend>
<div id="errorcheckbox" class="error"></div>
<label><input type="checkbox" name="oneReq" value="1">A Thing</label>
<label><input type="checkbox" name="oneReq" value="2">Another Thing</label>
<label><input type="checkbox" name="oneReq" value="3">Yet another thing</label>
</fieldset>
<fieldset data-mincheckboxchecked="3">
<legend>Top 3 Movies: Three required</legend>
<div id="errorcheckbox" class="error"></div>
<label><input type="checkbox" name="movie" value="Top Gun">Top Gun</label>
<label><input type="checkbox" name="movie" value="Terminator">Terminator</label>
<label><input type="checkbox" name="movie" value="Sound Of Music">Sound OF Music</label>
<label><input type="checkbox" name="movie" value="Mission Impossible">Mission Impossible</label>
</fieldset>
</div>
<div class="button"><input type="button" name="submit" id="submit" value="Submit"></div>
</form>
This way it's extensible and not reliant on Ids.
You can use the :checked which the selector to get the checked items.
function validate() {
console.log('Total Checked = ' + $('.contactForm input[type="checkbox"]:checked').length);
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<div class="contactForm">
<label for="checkbox" id="checkbox" name="checkbox">Contactee Type: </label><br>
<div id="errorcheckbox" class="error"></div>
<input type="checkbox" name="type1" value="Individual">Individual<br>
<input type="checkbox" name="type2" value="Catering">Business:Catering<br>
<input type="checkbox" name="type3" value="Partner">Business:Partner<br>
<button onclick="validate()">Validate</button>
</div>
use a class for your checkboxes and select that or use tag name and type to select tags,
you are using the id of a label tag for checking checkboxes
, use .is() method in jquery to check is checked
$("document").ready(function(){
console.log("Loaded");
$("#submit").click(function(){
checkContactee();
});
$("input[type='checkbox']").change(function(){
console.log("Something in contactee changed");
checkContactee();
});
function checkContactee(){
if ($("input[type='checkbox']").is(':checked'){
$("#errorcheckbox").html("<p>You missed this field</p>");
$("#errorcheckbox").addClass("showerror");
}
else{
$("#errorregarding").html("");
$("#errorregarding").removeClass("showerror");
}
}
var checkedCount=$("input[name^='type']:checked).length - this pulls all inputs, looks for those with the name beginning with "type", keep the ones that are checked, and returns how many are check (here, assigned to the checkedCount variable). I'll leave further validation/scolding of the user up to you

Show button when at lease 1 checkbox in a list checkboxes is checked

I have some code that works fine; it displays a button when a checkbox is checked. But now I want to change something and in that case there will be more checkboxes (they are generated by the content of a database so the number is not clear now).
But the solution is based on the ID of an element and having multiple the same ID's is not valid ánd it does not work.
I have the code here: https://codepen.io/anon/pen/jKOLew?editors=1111. As you can see only the first checkbox enables the div, the second doesn't.
Can somebody tell me how to solve this?
The code is this:
html:
<input type="checkbox" id="chkMessage" />Do you have Passport?<input type="checkbox" id="chkMessage" />Do you have Passport? <div id="dvMessage" style="display: none">Passport Number: <input type="text" /></div>`
And javascript:
`$(function() { $("#chkMessage").click(function() { if $(this).is(":checked")) { $("#dvMessage").show(); $("#AddMessage").hide(); } else { $("#dvMessage").hide(); $("#AddMessage").show(); } });});`
You use the same id twice. An id is suppose to be unique.
Here I changed it to be a class, and now it works just fine
$(function() {
$(".chkMessage").click(function() {
if ($(this).is(":checked")) {
$("#dvMessage").show();
$("#AddMessage").hide();
} else {
$("#dvMessage").hide();
$("#AddMessage").show();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="chkMessage" />Do you have Passport?
<input type="checkbox" class="chkMessage" />Do you have Passport?
<div id="dvMessage" style="display: none">
Passport Number:
<input type="text" />
</div>
Additionally, if you want to make sure the button is shown when either checkbox is selected, you could do something like this
$(function() {
$(".chkMessage").click(function() {
$("#dvMessage").hide();
$("#AddMessage").show();
$(".chkMessage").each(function() {
if ($(this).is(":checked")) {
$("#dvMessage").show();
$("#AddMessage").hide();
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="chkMessage" />Do you have Passport?
<input type="checkbox" class="chkMessage" />Do you have Passport?
<div id="dvMessage" style="display: none">
Passport Number:
<input type="text" />
</div>
If you by any chance can't control the rendered HTML, you can use the attribute selector [attribute="value"] to grab elements with the same id
$(function() {
$("[id='chkMessage']").click(function() {
$("#dvMessage").hide();
$("#AddMessage").show();
$("[id='chkMessage']").each(function() {
if ($(this).is(":checked")) {
$("#dvMessage").show();
$("#AddMessage").hide();
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="chkMessage" />Do you have Passport?
<input type="checkbox" id="chkMessage" />Do you have Passport?
<div id="dvMessage" style="display: none">
Passport Number:
<input type="text" />
</div>

how to hide and show named divs according to radio value?

This one is quite similar to my other question on:
how to hide and show named divs according to enum value?
Idea here is slightly different, though. The toggle() jQuery function is related to a radio button which is coded below:
<div id="recurrent">
<label for="recurrent">Recurrent? </label>
<input type="radio" id="idtrue" name="recurrent" value="true">Yes
<input type="radio" id="idfalse" name="recurrent" value="false" checked>No
</div>
The div to toggle is:
<div id="ifRecurrentTrue">
/// something
</div>
And the adapted jQuery from the other question is:
$('#recurrent select').on('change', function () {
var value = this.value;
$('#ifRecurrentTrue').toggle(value == true);
}).change();
I bet it's just a matter of different functions, right?
Again, thanks in advance!
You need to find the input elemetns by its name, so use the attribute equals selector instead of the element selector select
$('#recurrent input[name="recurrent"]').on('change', function() {
$('#ifRecurrentTrue').toggle(this.checked && this.id == 'idtrue');
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="recurrent">
<label for="recurrent">Recurrent?</label>
<input type="radio" id="idtrue" name="recurrent" value="true">Yes
<input type="radio" id="idfalse" name="recurrent" value="false" checked>No
</div>
<div id="ifRecurrentTrue">
/// something
</div>
Did't see the element with select tag on provided code, could be input. Replace select with input like following:
$('#recurrent input').on('change', function () {
var value = this.value;
$('#ifRecurrentTrue').toggle(value == true);
}).change();
$(document).ready(function() {
$('input:radio[name=recurrent]').on('change', function () {
var values = this.value;
$('#ifRecurrentTrue').toggle(values =='true');
}).change();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div id="recurrent">
<label for="recurrent">Recurrent? </label>
<input type="radio" id="idtrue" name="recurrent" value="true">Yes
<input type="radio" id="idfalse" name="recurrent" value="false" checked>No
</div>
<div id="ifRecurrentTrue">
/// something
</div>

How to limit the checked checkboxes to just one at a time?

I am trying to create a filter using checkboxes. I need to only have one checkbox checked at a time. How do I do this?
Scenario: The page has a catalog of watches. The user wants to filter the watches according to for men or for women
Here is my code:
$("#filter-options :checkbox").click(function()
{
$(".collection-wrapper .strap-wrapper").hide();
$("#filter-options :checkbox:checked").each(function()
{
$("." + $(this).val()).fadeIn();
});
if($('#filter-options :checkbox').filter(':checked').length < 1)
{
$(".collection-wrapper .strap-wrapper").fadeIn();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Filter Items</h3>
<ul id="filter-options">
<li><input type="checkbox" value="filter_man" data-filter_id="man"> Man</li>
<li><input type="checkbox" value="filter_woman" data-filter_id="woman"> Woman</li>
</ul>
<div class="collection-wrapper">
<div class="strap-wrapper filter_man">
<h2>man</h2>
<p></p>
</div>
<div class="strap-wrapper filter_woman">
<h2>woman</h2>
<p></p>
</div>
<div class="strap-wrapper filter_man filter_woman">
<h2>man / woman</h2>
<p></p>
</div>
<div class="strap-wrapper filter_woman">
<h2>woman</h2>
<p></p>
</div>
</div>
Thanks in advance!
Checkboxes are used for selecting multiple values of choices. What you need is Radio Buttons. They are used exactly for this purpose. One can select only one radio button at a time. So replace your code with:
<ul id="filter-options">
<li><input type="radio" name="filter" value="filter_man" data-filter_id="man"> Man</li>
<li><input type="radio" name="filter" value="filter_woman" data-filter_id="woman"> Woman</li>
</ul>
See an example here: http://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_input_type_radio
Radio buttons are what you are looking for ;)
take at look at these links:
jQuery api demo
Fiddle example
HTML:
<form id="myForm">
<input type="radio" name="myRadio" value="1" /> 1 <br />
<input type="radio" name="myRadio" value="2" /> 2 <br />
<input type="radio" name="myRadio" value="3" /> 3 <br />
</form>
JS
$('#myForm input').on('change', function() {
alert($('input[name="myRadio"]:checked', '#myForm').val());
});
You could use radio buttons or you could do something like:
$('input[type=checkbox]').change(function(){
if ($('input[type=checkbox]:checked').length > 1) {
this.checked = false;
}
})
You could just use radio buttons, but if you want to do it with checkboxes, solution is pretty simple.
When you click on one of the checkboxes, select all the checkboxes and remove "checked" state, and then just add checked on clicked checkbox
Something like this:
// On checkbox click
$("#filter-options input[type=checkbox]").click(function(event) {
// Uncheck all checkboxes
$("#filter-options input[type=checkbox]").prop("checked", false);
// Check that one that you clicked
$(this).prop("checked", true)
});

Categories

Resources