jQuery Check and Uncheck all doesn't work - javascript

I have a list of checkboxes that I want to select and unselect.
The problem currently is that when I click All, all items in the list are added to an array called filter. However when I click All again, the list is repopulated with the items again. It is supposed to empty the filter array and uncheck all checkboxes.
How can I uncheck all the boxes if I select the All checkbox again?
The list consist of:
if(!empty($items)){ ?>
<input class="form-check-input select-item" data-item="All" type="checkbox" value="All" id="All">
<label class="form-check-label item-label" for="All">All </label>
<?php foreach ($items as $entry): ?>
<input class="form-check-input select-item" data-item="<?php echo $entry['short_name'];?>" type="checkbox" value="<?php echo $entry['short_name'];?>" id="<?php echo $entry['short_name'];?>">
<label class="form-check-label item-label" for="<?php echo $entry['short_name'];?>"><?php echo $entry['full_name'];?> </label>
<?php endforeach; ?>
<?php } ?>
This is the JavaScript I have at the moment:
$(".select-item").click(function(e){
var item = $(this).data('item');
if(item=="All") {
console.log($('#items input:checkbox').length);
if(filterAllChecked()) {
console.log("in");
$('#items input:checkbox').prop('checked',"");
filter = [];
} else {
$('#items input:checkbox').prop('checked', 'checked');
var items = $("#items input:checkbox:checked").map(function(){
return $(this).val();
}).get();
filter = items;
console.log($('#items input:checkbox').filter(":checked").length);
}
} else {
var index = $.inArray(item,filter);
if(this.checked && index === -1) {
filter.push(item);
} else {
filter.splice(index,1);
}
}
console.log(filter);
});
This is the check to see if all items have been selected:
function filterAllChecked(){
var checkboxes = $("#items input:checkbox");
return checkboxes.length === checkboxes.filter(":checked").length;
}

try this
$(".select-item").click(function(){
if($(this).attr('data-item') == 'All'){
if($(this).hasClass('select-item-checked')){
$(this).removeClass('select-item-checked');
$('.select-item').not('[data-item="All"]').prop('checked', false);
}else{
$('.select-item').not('[data-item="All"]').prop('checked', true);
$(this).addClass('select-item-checked');
}
}
var filter = $.makeArray($('.select-item:checked').not('[data-item="All"]').map(function(k,v){return $(v).val();}));
console.log(filter);
});
demo : https://jsfiddle.net/mo9khobg/5/

You should create a separate function getChecked() to get new values.
See Example:
function getChecked() {
var filter = [];
$('input:checkbox').not($('#All')).each(function(){
if ($(this).is(':checked')) {
filter.push($(this).val());
}
})
console.log(filter);
}
$('input:checkbox').not($('#All')).on('click', function(){
if (!$(this).is(':checked')) { $('#All').prop('checked', false); }
getChecked();
})
$('#All').on('click', function(){
($(this).is(':checked')) ? $('input:checkbox').not($(this)).prop('checked', true) : $('input:checkbox').not($(this)).prop('checked', false);
getChecked();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="form-check-input select-item" data-item="All" type="checkbox" value="All" id="All"> Check All <br>
<input type="checkbox" name="name1" value="name1"> Name 1
<input type="checkbox" name="name2" value="name2"> Name 2
<input type="checkbox" name="name3" value="name3"> Name 3

If you want have control of the array you can do it this way:
var inputArray = []
$('input').on('click', function(event){
console.log(event.target.checked)
modifyArray(event.target)
})
$('#selectAll').on('click', function(el){
$('.input').each(function(index, el){
console.log(el)
el.checked = !el.checked
modifyArray(el)
})
});
function modifyArray(el) {
console.log(el.checked)
if(el.checked){
if(inputArray.indexOf(el.name) === -1){
inputArray.push(el.name)
}
}else{
let index = inputArray.indexOf(el.name)
console.log(index)
inputArray.splice(index, 1)
}
console.log(inputArray)
}
Jsfiddle here:
https://jsfiddle.net/L2pacjp5/29/

Related

How to Linking two checkbox Array together JavaScript

I want to connect two checkbox together , so that When clicked main checkbox then checked its child.
with below code I retrieve data from database:
while($row = mysqli_fetch_array($query_show_all_receivers))
{
$option .= ' <pre> <input onclick="func()" type="checkbox" class="checkbox-inline" name="check_Main[]" value = "'.$row['user_username'].'">'. row['user_username'].'
<input type="checkbox" class="checkbox-inline" name="check_child[]" id="check_child[]" value = "'.$row['user_mobile'].'"> '.$row['user_mobile'].'
</pre>';
}
and show the items:
<?php echo $option; ?>
How possible if Main box checked then will checked its child too.
Its my JavaScript code but I think have to use via loop:
It just work first child not others.
<script>
function func()
{
document.getElementById('check_child[]').checked = true ;
}
</script>
Thanks for your consideration.
IDs should be unique. In your case, you could use the query's row number in order to build an unique ID with a common prefix, it's generally good practice.
Here's a CodePen that works
https://codepen.io/Raven0us/pen/abvJqLP
<label for="checkbox-parent">Parent</label>
<input type="checkbox" onchange="func(event)" name="checkbox_parent" id="checkbox-parent">
<div>
<label for="checkbox-child-1">Child 1</label>
<input type="checkbox" name="checkbox_child_1" id="checkbox-child-1" class="checkbox-child">
<label for="checkbox-child-2">Child 2</label>
<input type="checkbox" name="checkbox_child_2" id="checkbox-child-2" class="checkbox-child">
<label for="checkbox-child-3">Child 3</label>
<input type="checkbox" name="checkbox_child_3" id="checkbox-child-3" class="checkbox-child">
</div>
I changed onclick to onchange, some people prefer click, mostly for legacy reasons (I think?), but I wouldn't. Moreover, I passed the actual event to the function, so it's available if we want to check stuff about it.
function func(event) {
document.querySelectorAll('.checkbox-child').forEach(checkboxChild => {
checkboxChild.checked = event.target.checked;
})
}
The handler gets all the related checkboxes, based on a common class which can repeat, unlike IDs, and loop through the returned NodeList and update their value based on parent checkbox value. So, checking or unchecking parent will update children as well.
Parent and child checkboxes
with above script by #CoolEsh I could solve this problem and update with loop to specific every parents and their children :
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.5.1/jquery.min.js"> </script>
<script>
var checkboxHandlerObj = {
init: function() {
$('#customerServices input:checkbox[class="parent"]').click(checkboxHandlerObj.parentClicked);
$('#customerServices input:checkbox[class^="parent-"]').click(checkboxHandlerObj.childClicked);
},
parentClicked: function() {
if ($(this).attr('checked')) {
$('#customerServices input:checkbox[class="parent-' + $(this).attr('id') + '"]').attr('checked', 'checked');
} else {
$('#customerServices input:checkbox[class="parent-' + $(this).attr('id') + '"]').removeAttr('checked');
}
},
childClicked: function() {
var temp = $(this).attr('class').split('-');
var parentId = temp[1];
if ($(this).attr('checked')) {
$('#' + parentId).attr('checked', 'checked');
} else {
var atLeastOneEnabled = false;
$('#customerServices input:checkbox[class="' + $(this).attr('class') + '"]').each(function() {
if ($(this).attr('checked')) {
atLeastOneEnabled = true;
}
});
if (!atLeastOneEnabled) {
$('#' + parentId).removeAttr('checked');
}
}
}
};
checkboxHandlerObj.init();
</script>
and PHP loop:
<div id="customerServices">
<?php
$x = 1;
$id = 1;
while($x <= 5) {
$x++;
$option .= '<input id="'.$id.'" class="parent" type="checkbox" name="check_Main[]" value = "1">1
<input type="checkbox" name="check_child[]" class="parent-'.$id.'" value = "2"> 2 <br> ';
$id++ ;
}
echo $option;
?>
</div>
It worked with unique Id. Thanks For #Ravenous and #evolutionxbox

How to access One div inside other div

I have a Two div when i click on the first div checkbox i want to use second div checkbox value.
var NewData = '<div class="divClassOne">
<input type="checkbox" class="chkremCFAllLevel1" value="HelloOne" name="chkOne"
id="check1" data-markerAllLevel1="12"></div>';
$("#sectionlistNew").append(NewData);
var NewDataTwo = '<div class="divClassTwo">
<input type="checkbox" class="chkremCFAllLevel2" value="HelloTwo" name="chkTwo"
id="check2" data-markerAllLevel2="12"></div>';
$("#sectionlistNewTwo").append(NewDataTwo);
$("#sectionlistNew").on('click', '.chkremCFAllLevel1', function () {
marker_refAllLevel1 = $(this).attr('data-markerAllLevel1');
console.log(marker_refAllLevel1);
});
When i click i want to compare data-markerAllLevel1 and data-markerAllLevel2 value.
Solution
$("#sectionlistNew").on('click', '.chkremCFAllLevel1', function () {
checkedvalueAllCheckBoxLevel1 = [];
marker_refAllLevel1 = $(this).attr('data-markerAllLevel1');
console.log(marker_refAllLevel1);
$("input[name=chkRolesALLLevel2]").each(function () {
if ($(this).attr("data-markerCheckBoxAllLevel2") == marker_refAllLevel1) {
console.log($(this).attr("data-markerCheckBoxAllLevel2"));
$('input[name="chkRolesALLLevel2"][data-markerCheckBoxAllLevel2="' + marker_refAllLevel1 + '"]').attr('disabled', false);
}
});
});
Code:
var NewData = '<div class="divClassOne"> <input type="checkbox" class="chkremCFAllLevel1" value="HelloOne" name="chkOne" id="check1" data-markerAllLevel1="12"></div>';
$("#sectionlistNew").append(NewData);
var NewDataTwo = '<div class="divClassTwo"> <input type="checkbox" class="chkremCFAllLevel2" value="HelloTwo" name="chkTwo" id="check2" data-markerAllLevel2="12"></div>';
$("#sectionlistNewTwo").append(NewDataTwo);
$("#sectionlistNew").on('click', '.chkremCFAllLevel1', function() {
marker_refAllLevel1 = $(this).attr('data-markerAllLevel1');
marker_refAllLevel2 = $('#check2').attr('data-markerAllLevel2');;
if (marker_refAllLevel1 == marker_refAllLevel1) {
console.log('Its both are same' + marker_refAllLevel1 + '=' + marker_refAllLevel2);
} else {
console.log('Its both are not same');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="sectionlistNew"></div>
<div id="sectionlistNewTwo"></div>
You need to explain more, what are you trying to do.
HTML:
<input type="checkbox" class="chkremCFAllLevel1" value="HelloOne" name="chkOne" id="check1" data-markeralllevel1="12">
<input type="checkbox" class="chkremCFAllLevel2" value="HelloTwo" name="chkTwo" id="check2" data-markeralllevel2="12">
Jquery:
$(document).ready(function() {
$("input[data-markerAllLevel1]").change(function () {
let markerAllLevel1 = $(this).data('markeralllevel1')
let markerAllLevel2 = $('[data-markeralllevel2]').data('markeralllevel2')
console.log(`${markerAllLevel1} == ${markerAllLevel2}`)
if(markerAllLevel1 == markerAllLevel2){ /* compare here whatever you need (not sure what you mean) */
if($(this).is(':checked')){
$('input[data-markeralllevel2]').prop('checked', true);
} else {
$('input[data-markeralllevel2]').prop('checked', false);
}
}
/* if you need to set value to another one, use this */
$('input[data-markeralllevel2]').val($(this).val())
console.log($('input[data-markeralllevel2]').val())
});
$("input[data-markeralllevel2]").change(function () {
let markerAllLevel1 = $('input[data-markeralllevel1]').data('markeralllevel1')
let markerAllLevel2 = $(this).data('markeralllevel2')
console.log(`${markerAllLevel1} == ${markerAllLevel2}`)
if(markerAllLevel1 == markerAllLevel2){ /* compare here whatever you need (not sure what you mean) */
if($(this).is(':checked')){
$('input[data-markeralllevel1]').prop('checked', true);
} else {
$('input[data-markeralllevel1]').prop('checked', false);
}
}
/* if you need to set value to another one, use this */
$('input[data-markeralllevel1]').val($(this).val())
console.log($('input[data-markeralllevel1]').val())
});
});

how to get the value of checkbox currently unchecked in multi select dropdown list?

I am have created a multi select filter. For each of the options selected the new div element will be created with it's id is the value of checkbox selected. Till here it's working fine. But now I want to remove those div who's options(checkboxes) are un selected. I tried the below,
if(!($(this).is(":checked"))){
alert('is un-checked: ' + $(this).val());
}
but it's not working. Giving value of null. Can anyone please suggest me how can I achieve this?
CODE:
if (window.XMLHttpRequest)
{
areq = new XMLHttpRequest();
} else
{
areq = new ActiveXObject("Microsoft.XMLHTTP");
}
areq.onreadystatechange = function () {
if ((areq.readyState == 4) && (areq.status == 200)) {
document.getElementById("details7").innerHTML= areq.responseText;
var c=areq.responseText;
$('.matrb').SumoSelect({
triggerChangeCombined: false,
okCancelInMulti: true,
});
$('.matrb').on('change', function() {
if ($('option:selected', this).is(':checked')) {
alert('is checked: ' + $(this).val());
am=$(this).val();
nm=$(this).find('option:selected').attr("name");
am = am.toString().match(/\w+$/)[0];
console.log("am is:"+c);
}
else if(!($(this).is(":checked"))){
alert('is un-checked: ' + $(this).val());
}
if (window.XMLHttpRequest)
{
breq = new XMLHttpRequest();
} else
{
breq = new ActiveXObject("Microsoft.XMLHTTP");
}
breq.onreadystatechange = function () {
if ((breq.readyState == 4) && (breq.status == 200)) {
if(!( document.getElementById(am))){
var namee=document.createElement('p');
var newDiv=document.createElement('div');
newDiv.setAttribute('id', am);
newDiv.setAttribute("style","display:inline;");
namee.setAttribute("style","display:inline;");
var htm=breq.responseText;
newDiv.innerHTML=htm;
namee.innerHTML=nm;
console.log(htm);
console.log(newDiv);
document.getElementById("details8").appendChild(namee);
document.getElementById("details8").appendChild(newDiv);
}
var uncheckedValues = $("select#id").find('option').not(':selected');
var uncheckedArray = uncheckedValues.map(function () { return this.value;}).get();
console.log(uncheckedArray);
First of all, you need to bind change event for each checkbox so that whenever any checkbox is clicked (current one in your case) you can check if it is checked or unchecked.
$('#parent_container_selector').find('input[type="checkbox"]').each(function(index, element) {
$(this).on('change', function(){
//this is your current event! Grab it and do your logic here.
if($(this).is(':checked') == false)
{
//delete your required elements..
}
});
});
Something like this perhaps:
$('#checkboxes_container_id').find('input[type="checkbox"]')‌​.on('change', function (e) {
$('#checkboxes_container_id').find('input[type="checkbox"]').each(function(index, element) {
if (!$(this).is(':checked')) {
alert('is un-checked: ' + $(this).val());
return false; // in case you only want ONE alert
}
});
}
$('input[type=checkbox]').not(':checked')
$('#test').on('click', function() {
console.log($('input[type=checkbox]').not(':checked').length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<button id="test">Test</button>
$('input[type=checkbox]').on('change', function() {
if(!this.checked){
console.log('unchecked checkbox');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<button id="test">Test</button>
You can use "not" for the selecion
$('[attribute="value"]:not(":checked")').each(function() {
alert($(this).val());
});
Check this https://jsfiddle.net/wrajesh/3ga508x3/3/
Finally I found the solution. below is the code for that,
$('#myselect').on('change', function() {
var $sel = $(this),
val = $(this).val(),
$opts = $sel.children(),
prevUnselected = $sel.data('unselected');
// create array of currently unselected
var currUnselected = $opts.not(':selected').map(function() {
return this.value
}).get();
// see if previous data stored
if (prevUnselected) {
// create array of removed values
var unselected = currUnselected.reduce(function(a, curr) {
if ($.inArray(curr, prevUnselected) == -1) {
a.push(curr)
}
return a
}, []);
// "unselected" is an array
if(unselected.length){
alert('Unselected is ' + unselected.join(', '));
}
}
$sel.data('unselected', currUnselected)
}).change();
posting this because it may help someone.

Two Radio buttons, a textarea and a number box, how to check if textarea is filled when radio1 is Yes and/or 2 is no

Here are the radios and textarea etc.
if(mysql_num_rows($canview) > 0) { ?>
<!-- Questions on return send all this to database then to place where dept. heads can see it-->
<div id = "returnform" >
<form action="" method="post">
<h4>Are any of the item(s) missing?</h4>
Yes<input type ="radio" name ="missing" id = "missing1" value = "Yes" required>
No<input type ="radio" name ="missing" id = "missing2" value = "No" >
<div class = "lossnum">
<input type="number" name="lossnum" id = "lossnum" placeholder="0">
</div>
<h4>Was every item put back/plugged in correctly?</h4>
Yes<input type ="radio" name ="putback" id = "putback1" value = "Yes" required>
No<input type ="radio" name ="putback" id = "putback2" value = "No">
<div class = "returncomments">
<h4>what happened?</h4>
<textarea name="comments"></textarea>
</div>
</div>
<input name="item_id" type="hidden" value="<?php echo $item->get_id(); ?>" />
<h4>Are you sure you want to return these <?php echo $item->get_name(); ?>? </h4>
<input type="submit" id="submit" name="submit" value="Return" />
right now all i have to change this is this:
$(document).ready(function () {
$(".lossnum").hide();
$(".comments").hide();
$(".returncomments").hide();
$(".commentup").hide();
$("#missing1").click(function () {
$(".lossnum").show();
$(".comments").show();
$(".returncomments").show();
});
$("#missing2").click(function () {
$(".lossnum").hide();
if($('#putback2').is(':checked')){
$(".comments").show();
$(".returncomments").show();
}
else{
$(".comments").hide();
$(".returncomments").hide();
}
});
$("#putback2").click(function () {
$(".comments").show();
$(".returncomments").show();
});
$("#putback1").click(function () {
if($('#missing2').is(':checked')){
$(".comments").hide();
$(".returncomments").hide();
}
else{
$(".comments").show();
$(".returncomments").show();
}
});});
this makes it so the textarea opens if 1 is yes and/or 2 is no, the only problem is if you then change the radios to no1/yes2 (which should be the only way the textarea does not show) it stays there, how would i make it so that it only shows up when something other than yes for 1 and/or no for 2 is true, and if that is changed it goes away and if it is not true does not show up.
Next I would like to make is so that when either 1 = Yes or/and 2 = no , the textarea is required to be filled out
you can for the most part ignore lost num
here is a JSfiddle for it
var itemMissing = false
, itemPluggedIn = true;
function updateCommentsDisplay(itemMissing, itemPluggedIn) {
if(itemMissing || !itemPluggedIn) {
$('#comments').show();
} else {
$('#comments').hide();
}
}
$('#nb-of-missing-items-field').hide();
updateCommentsDisplay(itemMissing, itemPluggedIn);
$('#missing input[name="missing-items"]').on('change', function () {
if(this.value === 'Yes') {
$('#nb-of-missing-items-field').show();
itemMissing = true;
} else {
$('#nb-of-missing-items-field').hide();
itemMissing = false;
}
updateCommentsDisplay(itemMissing, itemPluggedIn);
});
$('#plugged-in input[name="plugged-in-items"]').on('change', function () {
if(this.value === 'Yes') {
itemPluggedIn = true;
} else {
itemPluggedIn = false;
}
updateCommentsDisplay(itemMissing, itemPluggedIn);
});
http://jsfiddle.net/L7et15du/7/
Is that what you want to achieve?

Set Attr Required when a checkbox for that field is checked

I have some looping rows which each row has a check box. And in each row there is a dropdown list which I want it to be set as required when the checkbox in the row is selected.
MARK NAME QUANTITY
---------------------------------------------------
[] inputForName1 Choose => 1,2,3,4,5
---------------------------------------------------
[] inputForName2 Choose => 1,2,3,4,5
---------------------------------------------------
[] inputForName3 Choose => 1,2,3,4,5
---------------------------------------------------
[] inputForName4 Choose => 1,2,3,4,5
---------------------------------------------------
[] inputForName5 Choose => 1,2,3,4,5
---------------------------------------------------
[SUBMIT]
(here [] is a Check-Box, and Choose => is a dropdown selection)
echo' <tr>
<td><input name="checkbox[]" type="checkbox" value="'.$i++.'" /></td>
<td><input name="items[]" type="text" value="'.$obj->items.'"></td>
echo' <td><select name="esquantity[]" required >
<option value="" >Choose Quantity</option>';
for ($q=1; $q <= $obj->quantity; $q++) {
echo' <option value="'.$q.'"> '.$q.' </option>'; }
echo' </select></td>';
echo'</tr>';
}
}
?>
<input type="submit" name="Submit" value="Submit">
</form>
</table>
<?php
if($_SERVER["REQUEST_METHOD"] == "POST") {
foreach($_POST['checkbox'] as $i) {
$product_name=$_POST['items'][$i];
$product_quan=$_POST['esquantity'][$i];
mysql_query("INSERT INTO estockClaims (items,
esquantity)
VALUES ('$product_name',
'$product_quan')");
}
}
?>
The problem is when I check only two checkboxes and I submit them, it asks me to select all the dropdown list in the quantity column.
Sketch of Jquery
<script type="text/javascript">
$(document).ready(function(){
$('input[type="checkbox"]').on('change', function(e)){
// var thisCheckbox = $(this);
var thisCheckbox = $('select[name="esquantity"]');
var thisRow = thisCheckbox.closest('tr');
if($(this.is(':checked')) {
}
.attr('required'));
}
}
</script>
I guess you didn't forget tags: <table><form> and close the input tags also <input ... />
So for your code you can try this (PHP/HTML part):
$i++;
echo' <tr>
<td><input name="checkbox['.$i.']" type="checkbox" value="'.$i.'" id="chb'.$i.'" onchange="enableList(this);" /></td>
<td><input name="items['.$i.']" type="text" value="'.$obj->items.'" /></td>';
echo' <td><select name="esquantity['.$i.']" id="select'.$i.'" disabled onchange="checkSelect(this)">
<option value="" >Choose Quantity</option>';
for ($q=1; $q <= $obj->quantity; $q++) {
echo' <option value="'.$q.'"> '.$q.' </option>'; }
echo' </select></td>';
echo'</tr>';
Then I've noticed in the SUBMIT part:
if($_SERVER["REQUEST_METHOD"] == "POST") {
foreach($_POST['checkbox'] as $key => $i) {
$product_name=$_POST['items'][$key];
$product_quan=$_POST['esquantity'][$key];
//more code
}
}
And the Javascript part:
function enableList(element) {
var select = document.getElementById("select"+element.id.substring(element.id.length-1));
if(element.checked === true){
select.disabled = false;
checkSelect(select);
}else{
select.disabled = true;
select.selectedIndex = 0;
}
}
function checkSelect(element){
if(!validate_select(element)){
element.setCustomValidity("Choose an option");
}else{
element.setCustomValidity("");
}
}
function validate_select(select){
if(select.selectedIndex === 0){
return false;
}else{
return true;
}
}
EDITED: In order to achieve the new purpose (submit only if at least one input is checked):
Add to the checkbox one class as an identifier: class="chb_group" (so you don't have to worry about other checkboxes)... and an id for the submit button maybe: id="btn_submit" and disabled by default
So you add:
function enableSubmit(){
if (document.querySelector('.chb_group:checked')) {
document.getElementById('btn_submit').disabled = false;
} else {
document.getElementById('btn_submit').disabled = true;
}
}
And call it in:
function enableList(element) {
var select = document.getElementById("select"+element.id.substring(element.id.length-1));
enableSubmit();
.....
}
NOTE: This code will work only in "modern" browsers because of some functions and properties like: setCustomValidity and querySelector
That is a javascript answer. Here's the Jquery answer: http://jsfiddle.net/n13wbran/5/
You can change the req attribute which I assigned myself on checkbox change event:
$("input[name^='checkbox']").change(function () {
var id = this.name.substring(8);
if (this.checked) {
$("[name='esquantity" + id + "']").attr("req", "true");
} else {
$("[name='esquantity" + id + "']").attr("req", "false");
}
});
Then on Submit click, check the lists with req == "true" and do the following:
$("input[name='Submit']").click(function () {
var i;
for(i = 1; i <= parseInt($("[name^='esquantity']").length); i++) {
if ($("[name='esquantity[" + i + "]']").attr("req") == "true" &&
$("[name='esquantity[" + i + "]']").val() == "")
alert("Please select a value for the required lists");
}
});

Categories

Resources