I am trying to count how many checkboxes the user checked so I could disable the other input so it will enter the database. How can I run on different elements $(" . ") using an array of different classes because I have a few groups of inputs in my form.
<script>
var countChecked = function() {
var n = $( ".neutral:checked" ).length;
alert( n + (n === 1 ? " is" : " are") + " checked!" );
};
countChecked();
$( "input[type=checkbox]" ).on( "click", countChecked );
</script>
// Count ALL checked boxes.
console.log($(":checked").length)
// Count checkboxes for a set of given classes.
console.log($(".one, .two, .three, .four").filter(":checked").length)
// Or given as array
let targets = [".one", ".two", ".three", ".four"];
console.log($(targets.join(",")).filter(":checked").length)
// or without the dot
targets = ["one", "two", "three", "four"];
console.log($(targets.map(x => `.${x}`).join(",")).filter(":checked").length)
// or if you want to do something separately for each class
const handleCheckboxes = (cls) => {
var n = $(`.${cls}:checked`).length;
console.log(`${n} of class ${cls} ${n === 1 ? "is" : "are"} checked!`);
// do even more stuff here
};
targets.forEach(handleCheckboxes);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="one" type="checkbox" checked>
<input class="two" type="checkbox" checked>
<input class="two" type="checkbox" checked>
<input class="two" type="checkbox" checked>
<input class="three" type="checkbox">
<input class="three" type="checkbox">
<input class="four" type="checkbox" checked>
<input class="four" type="checkbox">
You can simply loop through all classes
//Array
var array = ["class1", "class2", "class3", "class4", "class5"];
//Loop
array.forEach((className, classIndex) => {
var n = $('.' + className + ':checked').length;
var term = n === 1 ? "is" : "are";
console.log(n + ' of ' + className + term + ' checked');
});
Related
I am developing simple Cordova application with some MySQL database retrieve data with help of jquery.
I want to display database content in tabs.
This is my HTML code
<ul id="tabs-swipe-demo" class="tabs">
</ul>
<div id="tabs"></div>
this is my JS code
$(document).ready(function(){
$('ul.tabs').tabs({
swipeable : true
});
var url_string = document.URL;
var url = new URL(url_string);
var unit = url.searchParams.get("unit");
var subject = url.searchParams.get("subject");
$("#logo-container").text(unit);
var ans;
var url="http://api.tectiqcompany.com/units.php?table="+subject;
$.getJSON(url,function(result){
console.log(result);
$.each(result, function(i, field){
var que = field.COL2;
var a = field.COL3;
var b = field.COL4;
var c = field.COL4;
var d = field.COL6;
ans = field.COL7;
var desc = field.COL8;
if(i == 0){
$(".tabs").append('<li class="tab"><a class="active" href="#test-swipe-'+(i+1)+'">'+(i+1)+'</a></li>');
}else{
$(".tabs").append('<li class="tab">'+(i+1)+'</li>');
}
$("#tabs").append('<div id="test-swipe-'+(i+1)+'" class="col s12"><div style="padding: 15px;">'+(i+1)+'. '+que+'<p><input name="group1" type="radio" id="test1" /><label for="test1">'+a+'</label></p><p><input name="group1" type="radio" id="test2" /><label for="test2">'+b+'</label></p><p><input name="group1" type="radio" id="test3" /><label for="test3">'+c+'</label></p><p><input name="group1" type="radio" id="test4" /><label for="test4">'+d+'</label></p></div></div>');
});
});
});
this is output:
OUTPUT SCREENSHOP
I am using Materializecss and JQuery latest Version.
Add your swipeable tabs code after appending the html to tabs.
Take a look,
$(document).ready(function() {
var url_string = document.URL;
var url = new URL(url_string);
var unit = url.searchParams.get("unit");
var subject = url.searchParams.get("subject");
$("#logo-container").text(unit);
var ans;
var url = "http://api.tectiqcompany.com/units.php?table=" + subject;
$.getJSON(url, function(result) {
console.log(result);
$.each(result, function(i, field) {
var que = field.COL2;
var a = field.COL3;
var b = field.COL4;
var c = field.COL4;
var d = field.COL6;
ans = field.COL7;
var desc = field.COL8;
if (i == 0) {
$(".tabs").append('<li class="tab"><a class="active" href="#test-swipe-' + (i + 1) + '">' + (i + 1) + '</a></li>');
} else {
$(".tabs").append('<li class="tab">' + (i + 1) + '</li>');
}
$("#tabs").append('<div id="test-swipe-' + (i + 1) + '" class="col s12"><div style="padding: 15px;">' + (i + 1) + '. ' + que + '<p><input name="group1" type="radio" id="test1" /><label for="test1">' + a + '</label></p><p><input name="group1" type="radio" id="test2" /><label for="test2">' + b + '</label></p><p><input name="group1" type="radio" id="test3" /><label for="test3">' + c + '</label></p><p><input name="group1" type="radio" id="test4" /><label for="test4">' + d + '</label></p></div></div>');
});
$('ul.tabs').tabs({
swipeable: true
});
});
});
I've looked at lots of posts but I couldn't find anything that works in my case. I need to display of a preview of the user's signature in their profile, with the options to not show their phone number and/or email address so I have a checkbox for each.
Here's my HTML for the checkboxes:
<div class="checkbox">
<label>
<input type="checkbox" name="showInSignature[]" id="showPhoneId" value="showPhone" class="checkbox style-0" checked="checked">
<span>Teléfono</span>
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="showInSignature[]" id="showEmailId" value="showEmail" class="checkbox style-0" checked="checked">
<span>Dirección de e-mail</span>
</label>
</div>
and here is the jQuery:
var fname = $('#personalOptionsForm').find('[name="fname"]').val(),
lname = $('#personalOptionsForm').find('[name="lname"]').val(),
cellphone = $('#personalOptionsForm').find('[name="cellphone"]').val(),
email = $('#personalOptionsForm').find('[name="email"]').val(),
if ($('#showPhoneId').is(':checked') = true) {
showPhone = 1;
} else {
showPhone = 0;
},
// showPhone = (($('input[name="showInSignature[]"]')['showPhone'].checked = true) ? 1 : 0),
// showEmail = (($('input[name="showInSignature[]"]')['showEmail'].checked = true) ? 1 : 0),
str = "<strong>" + fname + " " + lname + "</strong><br /><br />" + ((showPhone = 1) ? 'Teléfono: ' + cellphone + '<br />' : '') + "E-mail: " + email + "",
html = $.parseHTML( str );
$('#signaturePreview').append(html);
If I comment out the IF (as I've commented out other tries I've made) and the ternary operator in the str var it works but NOTHING is displayed when trying to use a dynamic value (like the phone checkbox). There's only two methods there but I've tried many more. None of them work. Nothing is appended.
How can I do it? Thanks in advance!
showPhone = $('#showPhoneId').is(':checked');
surely that's all you need. It returns a boolean
$(document).ready(function() {
alert('Is Checked: ' + $('#showPhoneId')[0].checked);
console.log(typeof $('#showPhoneId')[0].checked);
console.log($('#showPhoneId')[0].checked === true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkbox">
<label>
<input type="checkbox" name="showInSignature[]" id="showPhoneId" value="showPhone" class="checkbox style-0" checked="checked">
<span>Teléfono</span>
</label>
</div>
In your code you are using assignment operator "=" which means
a = b (value of b is assigned to a),
in your case you are trying to assign true to $('#showPhoneId').is(':checked')
kindly"==" instead
var fname = $('#personalOptionsForm').find('[name="fname"]').val() ,
lname = $('#personalOptionsForm').find('[name="lname"]').val() ,
cellphone = $('#personalOptionsForm').find('[name="cellphone"]').val(),
email = $('#personalOptionsForm').find('[name="email"]').val(),
//dummy values
fname = 'abc', lname="dksjdn",
cellphone = "98989898", email = "abc#gmail.com";
if($('#showPhoneId').is(':checked') == true) {
showPhone = 1;
} else {
showPhone = 0;
};
// showPhone = (($('input[name="showInSignature[]"]').is(':checked') == true) ? 1 : 0),
// showEmail = (($('input[name="showInSignature[]"]').is(':checked') == true) ? 1 : 0),
str = "<strong>" + fname + " " + lname + "</strong><br /><br />" + ((showPhone == 1) ? 'Teléfono: ' + cellphone + '<br />' : '') + "E-mail: " + email + "",
html = $.parseHTML( str );
$('#signaturePreview').append(html);
please refer https://jsbin.com/rolodozode/1/edit?html,js,output
I have a form (commonStuff) cloned this way (and an html page, designed in jquery mobile, where the form appears multiple times, cloned):
var commonClone = commonStuff.cloneNode(true);
and this function
function renameNodes(node) {
var i;
if (node.length) {
for (i = 0; i < node.length; i += 1) {
renameNodes(node[i]);
}
} else {
// rename any form-related elements
if (typeof node.form !== 'undefined') {
node.id = currentPrefix + '_' + node.id;
node.name = currentPrefix + '_' + node.name;
// This assumes that form elements do not have child form elements!
} else if (node.children) {
renameNodes(node.children);
}
}
}
which add a prefix 'form1_', 'form_2' (the currentPrefix) to id and names of any element in the form and is applied to commonClone (and so recursively to his sons).
renameNodes(commonClone);
It work perfectly in case of text inputs like
<div data-role="fieldcontain" class="ui-field-contain ui-body ui-br">
<label for="foo" class="ui-input-text">Age:</label>
<input type="text" name="age" id="age" value="" class="ui-input-text ui-body-c ui-corner-all ui-shadow-inset">
</div>
But it fails on radio buttons like
<div data-role="fieldcontain">
<fieldset data-role="controlgroup" data-type="horizontal">
<legend>Address:</legend>
<input type="radio" name="radio-address" id="radio-address_female" value="1" checked="checked" />
<label for="radio-address_female">Address 1</label>
<input type="radio" name="radio-address" id="radio-address_male" value="2" />
<label for="radio-address_male">Address 2</label>
</fieldset>
</div>
applying the renaming to the outer divs like 'fieldcontain' and 'controlgroup'. It works if i remove those two divs but the graphical effect is unacceptable...
As far as now, i got the problem is in the last 'else if' block for it doesn't care of siblings, but I don't really know how to fix this. Any idea?
EDIT: This code comes from this answer How to create a tabbed html form with a common div
As you use jQuery mobile, jQuery will be available.
I hope this code will point you in the right direction:
var i = 0;
$("form").each(function() {
$(this).find("input, select").each(function() {
$(this).attr("id", "form" + i + "_" + $(this).attr("id"));
$(this).attr("name", "form" + i + "_" + $(this).attr("name"));
});
$(this).find("label").each(function() {
$(this).attr("for", "form" + i + "_" + $(this).attr("for"));
});
i++;
});
EDIT:
I understand your current approach fails with labels. Consider to wrap your input elements inside the label tag. In that case, you won't need the for-attribute. This is in accordance with the docs: http://api.jquerymobile.com/checkboxradio/
Consider this:
HTML
<form>
<div data-role="fieldcontain">
<fieldset data-role="controlgroup" data-type="horizontal">
<legend>Address:</legend>
<label><input type="radio" name="radio-address" id="radio-address_female" value="1" checked="checked" />Address 1</label>
<label><input type="radio" name="radio-address" id="radio-address_male" value="2" />Address 2</label>
</fieldset>
</div>
<div data-role="fieldcontain" class="ui-field-contain ui-body ui-br">
<label><input type="text" name="age" id="age" value="" class="ui-input-text ui-body-c ui-corner-all ui-shadow-inset">Age:</label>
</div>
</form>
jQuery
var i = 0, currentPrefix = "form";
$("form").each(function() {
$(this).find("input, select").each(function() {
$(this).attr("id", currentPrefix + i + "_" + $(this).attr("id"));
$(this).attr("name", currentPrefix + i + "_" + $(this).attr("name"));
});
i++;
});
Workin fiddle: https://jsfiddle.net/EliteSystemer/8sx6rnwo/
Truly, this is far from elegant, but a solution, anyway. In any node, this searches manually for input and labels, changing id, names and 'for' attribute in case of labels.
function renameNodes(node) {
var i;
if (node.length) {
for (i = 0; i < node.length; i += 1) {
renameNodes(node[i]);
}
} else {
// rename any form-related elements
if (typeof node.form !== 'undefined') {
node.id = currentPrefix + '_' + node.id;
node.name = currentPrefix + '_' + node.name;
var inputs = node.getElementsByTagName('input');
for (i = 0; i < inputs.length; ++i) {
inputs[i].id = currentPrefix + '_' + inputs[i].id;
inputs[i].name = currentPrefix + '_' + inputs[i].name;
}
var labels = node.getElementsByTagName('label');
for (i = 0; i < labels.length; ++i) {
labels[i].setAttribute('for', currentPrefix + '_' + labels[i].getAttribute("for"));
}
} else if (node.children) {
renameNodes(node.children);
}
}
}
Hi guys I have a "datatable" with the following checkboxes on it:
<input type="checkbox" name="total_balance[]" id="total_balance" class="total_balance" value="<?= $balance['supplierID'] ?>" />
<input type="checkbox" name="no_payment[]" id="no_payment" class="no_payment" value="<?= $balance['supplierID'] ?>" />
That is a loop, so I've hundred of the same names but with different values by row.
So what I want is when I check the total_balance[] that has the value=1, for example, it's uncheck, if is checked, the no_payment[] with value=1, and so on.. like if I click the total_balance[] with value=32, uncheck the no_payment with value=32...
How to I do that in jquery??
I've tried like that:
$('input[name="total_balance"]').change(function() {
console.log(this.value);
var val = this.value;
$('input:no_payment[value="' + val + '"]').attr('checked', false);
});
$('input[name="no_payment"]').change(function() {
console.log(this.value);
var val = this.value;
$('input:total_balance[value="' + val + '"]').attr('checked', false);
});
but doesn't work
tks!
got it:
$('.total_balance').click(function() {
var val = this.value;
$('.no_payment[value="' + val + '"]').attr('checked', false);
});
$('.no_payment').click(function() {
var val = this.value;
$('.total_balance[value="' + val + '"]').attr('checked', false);
})
I'm using Eric Hynds jQuery MultiSelect Widget that is being populated from a javascript file. The issue is that either selection adds to both sides. Option 1-3 should only add to Main1-3, same for option/Main 4-6. Please see my fiddle of how it works and the issue http://jsfiddle.net/3u7Xj/112/
I think it would be eaisiest to break it out something like
var lbl = $("#MDCselect").val();
if (number1.checked) {...
('.holder').append...
var lbl2 = $("#ClinicalSelect").val();
if (number2.checked) {...
('.holder2').append...
currently
$(document).ready(function () {
$(".multiselect").multiselect({
header: "Choose up to 5 areas total",
click: function (event, ui) {
var number1 = $("#MDCselect").children(":checked").length,
number2 = $("#Clinicalselect").children(":checked").length;
if (ui.checked && ((number1 + number2 >= 5) || $(this).children(":checked").length >= 5)) {
return false;
}
var lbl = ui.value;
if (ui.checked) {
var ctrl = '<input type="checkbox" name="chk" checked="checked" class="chk" id="' + lbl.replace(/[^a-z0-9\s]/gi, '').replace(/[,\s]/g, '') + '">';
$("[id^=id]:checked").each(function () {
$(this).nextAll('.holder:first').append('<div>' + ctrl + lbl + '</div>');
});
} else {
$("[id^=id]:checked").each(function () {
$(this).nextAll('.holder:first').find('#' + lbl.replace(/[^a-z0-9\s]/gi, '').replace(/[,\s]/g, '')).parent().remove();
})
}
},
selectedList: 5
});
$(".checkers").click(function () {
if (!$(this).is(':checked')) {
$(this).nextAll('.holder:eq(0)').find('div input').parent().remove();
} else {
var checkedOnes = $('#MDCselect').nextAll('.ui-multiselect-menu').find('ul li input:checked');
$(".holder").html("");
for (var i = 0; i < checkedOnes.length; i++) {
var lbl = checkedOnes.eq(i).attr('value');
var ctrl = '<input type="checkbox" name="chk" checked="checked" class="chk" id="' + lbl.replace(/[^a-z0-9\s]/gi, '').replace(/[,\s]/g, '') + '">';
$("[id^=id]:checked").each(function () {
$(this).nextAll('.holder:first').append('<div>' + ctrl + lbl + '</div>');
});
}
}
});
});
I'm not entirely sure if I get what you want to do, try this and let me know if it is what you want, here is the fiddle if you want to try it http://jsfiddle.net/8xBcd/
I put the mains in a containing div, that way is easier to make selectors for the diferent mains. check the fiddle please.
<div id="main1-3" >
<input type="checkbox" name="chk1" value="Main1" id="id1" class='checkers'/><label for="Main1"><b>Main1</b></label>
<div class="holder"></div>
</br>
<input type="checkbox" name="chk2" value="Main2" id="id2" class='checkers'><label for="Main2"><b> Main2</b></label>
<div class="holder"></div>
</br>
<input type="checkbox" name="chk3" value="Main3" id="id3" class='checkers'><label for="Main3"><b> Main3</b></label>
<div class="holder"></div>
</div>
<select id="MDCselect" multiple="multiple" class="multiselect">
<option>1</option>
<option>2</option>
<option>3, this space</option>
</select><br>