Check all or uncheck all in multi checkbox - javascript

I have this code for multi check-box
HTML:
<fieldset data-role="collapsible">
<legend>Pick one</legend>
<div data-role="controlgroup" id="ZIBI" align="right" >
</div>
</fieldset>
jQuery/JavaScript:
myArray1 = new Array(
"1","2","3","4","5","6"
);
$("#ZIBI").html('');
for (var i = 0; i < myArray1.length; i++) {
row = myArray1[i];
$("#ZIBI").append(
'<label for=' + row + '>' + row + '</label>' +
'<input type="checkbox" name="favcolor" id=' + row + ' value=' + row + '>');
}
$('#ZIBI').trigger('create');
how to check all or uncheck all by pressing any button ?
thanks

In this JsFiddle you'll find a method to check/uncheck all checkboxes within a given div, using a checkbox with id _main:
function checkAll(e){
e = e || event;
var from = e.target || e.srcElement
,cbs = this.querySelectorAll('input'), i=1;
if (/^_main$/i.test(from.id)){
for (;i<cbs.length;i+=1){
cbs[i].checked = from.checked;
}
} else {
var main = document.querySelector('#_main')
,j = cbs.length;
for (;i<cbs.length;i+=1){
j -= cbs[i].checked ? 0 : 1;
}
main.checked = j === cbs.length ? true : false;
}
}

Update
New elements should be added to $(".selector").controlgroup("container") not $(".selector") directly. If you add them to main div, elements won't be styled as a _controlgroup`.
You need to refresh .checkboxradio("refresh") checkbox or radio to apply jQM styles. Another point, .trigger("create") is deprecated as of jQM 1.4 and replaced with .enhanceWithin().
myArray1 = new Array(
"1", "2", "3", "4", "5", "6");
/* remove previous elements */
$("#ZIBI").controlgroup("container").html('');
for (var i = 0; i < myArray1.length; i++) {
row = myArray1[i];
/* add new ones to container */
$("#ZIBI").controlgroup("container").append(
'<label for=' + row + '>' + row + '</label>' +
'<input type="checkbox" name="favcolor" id=' + row + ' value=' + row + '>');
}
/* refresh controlgroup and enhance elements within */
$("#ZIBI").controlgroup().enhanceWithin();
/* check/uncheck on button click */
$("#foo").on("click", function () {
var status = $("#ZIBI [type=checkbox]").eq(0).prop("checked") ? false : true;
$("#ZIBI [type=checkbox]").prop("checked", status).checkboxradio("refresh");
});
Demo

You can try this:
HTML:
<fieldset data-role="collapsible">
<legend>Pick one</legend>
<div data-role="controlgroup" id="ZIBI" align="right" >
</div>
</fieldset>
<input type="checkbox" id="all" value="Toggle" />
jQuery:
$('#all').on('click', function() {
if(this.checked) {
$('#ZIBI').find('input[type=checkbox]').prop('checked', true);
} else {
$('#ZIBI').find('input[type=checkbox]').prop('checked', false);
}
});
Working Fiddle.

Related

using .on to listen for event not working

I am trying to use .on to listen for an event.
html:
<div class="form-group" id="group_names">
<label> Names: </label><br>
<input type="text" class="form-control name" placeholder="name1" id="name1" name ="name1"><br>
</div>
JS:
for (n = 1; n < inputLength+3 ; ++n) {
var test2 = document.getElementById(dude+n);
$(test2).on('change', '#group_names', forFunction);
}
The change to the input field is not being recognized.
Additionally, I am hoping .on will recognize changes made to new html i am injecting using the following function:
var dude = "name";
function forFunction() {
for (m = 1; m < inputLength + 1; ++m) {
var test = document.getElementById(dude + m)
if (test.value != "") {
var txt = "<input type=\"text\" class=\"form-control name\" placeholder=" + dude + (m + 1) + " id=" + dude + (m + 1) + " name=" + dude + (m + 1) + "><br>";
document.getElementById('group_names').insertAdjacentHTML('beforeend', txt);
//function updateHTML(txt)
}
}
}
I am not sure if my syntax for .on is correct. I am trying to use "#group_names" as the selector, but not sure if I am doing it right.
Thanks
You probably want to use event delegation on the parent div instead.
$('#group_names').on('change', 'input.form-control.name', forFunction);
Consider the following jQuery code.
$(function() {
var inputFields = $("input[id*='name']");
function forFunction(evt) {
console.log(evt.type);
inputFields.each(function(i, el) {
var n = i + 1;
if ($(el).val() != "") {
console.log("Value Detected");
$("<input>", {
type: "text",
class: "form-control name",
placeholder: "group" + n,
id: "group" + n,
name: "group" + n
}).insertBefore("#group_names");
}
});
}
inputFields.on("change", forFunction);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group" id="group_names">
<label> Names: </label><br>
<input type="text" class="form-control name" placeholder="name1" id="name1" name="name1"><br>
</div>
This should work for all of the Input items.

Disable unchecked check boxes in selected div element using jquery

I am creating check boxes dynamically using jquery. I want to disable unchecked check boxes as shown in the snippet,but i want to disable the check boxes only in their respective div elements and not in the other div elements which is what causing issue now.
I have written the code to disable/enable checkboxes based on their respective div tags and i have commented it as it is throwing error if enabled.
$($(".checkbox").eq(id).":checkbox[name='radio']:not(:checked)").prop('disabled', true);
Problem explanation : Here i am creating two div tags dynamically inside which check boxes are also created with same name. So if i check on checkbox in first div other checkbox gets disabled and other div tag gets created which works as expected. but if i check any option in second div tag other option in second div tag doesn't get disabled and also if i uncheck the checked option in first div tag both options get disabled in first div tag. I guess this is because all checkboxes have same names.
How can we disable checkboxes only in their respective div tags. I tried below code but didn't work
$($(".checkbox").eq(1).":checkbox[name='radio']:not(:checked)").prop('disabled', true);
Below snippet explains the problem more appropriately
Please help me.
function checkdiv(id, val) {
if ($(":checkbox[name='radio']:checked").length == 1)
$(":checkbox[name='radio']:not(:checked)").prop('disabled', true);
else
$(":checkbox[name='radio']:not(:checked)").prop('disabled', false);
var diva = Number(id) + 1;
var divb = Number(id) + 1;
//if(id.length != 0){
if (val.checked == true) {
if (diva < 2 && divb < 2) {
creatediv('maindiv')
}
}
// }
else {
var diva = Number(id) + 1;
var divb = Number(id) + 1;
$("#" + diva).remove();
$(".divot").eq(divb).remove();
}
}
function creatediv(main) {
var divid = $(".divin").length;
var divid1 = $(".divot").length;
var div = "<div class='col-xs-2 divin' id='" + divid + "' style='border:1px solid'><span class='header'></span></div><div class='col-xs-1 divot'></div>";
$('#' + main).append(div);
loadval(divid)
}
function loadval(div) {
var div1 = "<div class='checkbox'><label><input type='checkbox' name='radio' value='Head' onchange='checkdiv(" + div + ",this)'>Head</label><br><label><input type='checkbox' name='radio' value='Hand' onchange='checkdiv(" + div + ",this)'>Hand</label></div>";
$("#" + div).append(div1)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body onload="creatediv('maindiv')">
<div class="container">
<div class="form-group row" id="maindiv">
</div>
</div>
</body>
Have you tried ".find" in the jQuery API - this will only find elements within the specified selector - see the modifications to the "checkdiv" function ($('#' + id))
function checkdiv(id, val) {
if ($('#' + id).find(":checkbox[name='radio']:checked").length == 1)
$('#' + id).find(":checkbox[name='radio']:not(:checked)").prop('disabled', true);
else
$('#' + id).find(":checkbox[name='radio']:not(:checked)").prop('disabled', false);
var diva = Number(id) + 1;
var divb = Number(id) + 1;
//if(id.length != 0){
if (val.checked == true) {
if (diva < 2 && divb < 2) {
creatediv('maindiv')
}
}
// }
else {
var diva = Number(id) + 1;
var divb = Number(id) + 1;
$("#" + diva).remove();
$(".divot").eq(divb).remove();
}
}
function creatediv(main) {
var divid = $(".divin").length;
var divid1 = $(".divot").length;
var div = "<div class='col-xs-2 divin' id='" + divid + "' style='border:1px solid'><span class='header'></span></div><div class='col-xs-1 divot'></div>";
$('#' + main).append(div);
loadval(divid)
}
function loadval(div) {
var div1 = "<div class='checkbox'><label><input type='checkbox' name='radio' value='Head' onchange='checkdiv(" + div + ",this)'>Head</label><br><label><input type='checkbox' name='radio' value='Hand' onchange='checkdiv(" + div + ",this)'>Hand</label></div>";
$("#" + div).append(div1)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body onload="creatediv('maindiv')">
<div class="container">
<div class="form-group row" id="maindiv">
</div>
</div>
</body>

How to add dynamically created Checkboxes to Bootstrap row

I have added a bootstrap row. Now inside that I want to add checkbox such that checkboxes should display side by side not as line by line as it is now. Here is the HTML.
<div class="row" id="ReportRow">
<div class="col-md-12">
</div>
</div>
and here is the jquery
var Reports = "User, Admin, Detail, Summary";
var arrReportscheckBoxItems = Reports.split(',');
var reportscheckBoxhtml = ''
for (var i = 0; i < arrReportscheckBoxItems.length; i++) {
reportscheckBoxhtml += '<label style="font-weight: 600; color: #00467f !important;"><input type="checkbox" value=' + arrReportscheckBoxItems[i] + '>' + arrReportscheckBoxItems[i] + '</label><br\>';
}
$('#ReportRow').html(reportscheckBoxhtml);
Plesae help me to align it properly. Thanks.
Fiddle
Just remove the <br/> from ur code
var Reports = "User, Admin, Detail, Summary";
var arrReportscheckBoxItems = Reports.split(',');
var reportscheckBoxhtml = ''
for (var i = 0; i < arrReportscheckBoxItems.length; i++) {
reportscheckBoxhtml += '<label style="font-weight: 600; color: #00467f !important;"><input type="checkbox" value=' + arrReportscheckBoxItems[i] + '>' + arrReportscheckBoxItems[i] + '</label> ';
}
$('#ReportRow > .col-md-12').html(reportscheckBoxhtml);

Display the checkboxes selected into a section and the unselected into another one

I want to show the checkboxes selected into a div but actually I have a duplicate item in the list and I'm not sure how to display the unselected items into another div.
You can try out here http://jsfiddle.net/tedjimenez/7wzR5/
Here my code:
JS CODE
/* Array */
var list = new Array("valuetext000", "valuetext001", "valuetext002", "valuetext003", "valuetext004", "valuetext005", "valuetext006", "valuetext007", "valuetext008", "valuetext009", "valuetext010", "valuetext011", "valuetext012", "valuetext013", "valuetext014", "valuetext015", "valuetext016", "valuetext017")
var html = "";
/* Array will be converted to an ul list */
for (var i = 0; i < list.length; i++) {
html += "<input type='checkbox' name='boxvalue' value='" + list[i] + "' /><label>" + list[i] + "</label><br>";
}
$("#elmAv").append(html);
THE HTML CODE
<form>
<div id="elmAv"></div>
<div id="selectionResult"></div>
<script>
/* Function to display the items selected */
function showBoxes(frm) {
var checkedItems = "\n";
//For each checkbox see if it has been checked, record the value.
for (i = 0; i < frm.boxvalue.length; i++) {
if (frm.boxvalue[i].checked) {
checkedItems = checkedItems + "<li>" + frm.boxvalue[i].value + "<li>";
}
}
$("#elmAv").empty();
$("#selectionResult").append(checkedItems);
}
</script>
<input type="Button" value="Get Selection" onClick="showBoxes(this.form)" />
</form>
Simply add another div after selectionResult like this:
<div id="unselectedResult"></div>
And then update showBoxes() with the following code:
function showBoxes(frm) {
var checkedItems = "Checked:<br>\n";
var uncheckedItems = "Unchecked:<br>\n";
//For each checkbox see if it has been checked, record the value.
for (i = 0; i < frm.boxvalue.length; i++) {
if (frm.boxvalue[i].checked) {
checkedItems = checkedItems + "<li>" + frm.boxvalue[i].value + "</li>";
}
else {
uncheckedItems = uncheckedItems + "<li>" + frm.boxvalue[i].value + "</li>";
}
}
$("#elmAv").empty();
$("#selectionResult").append(checkedItems);
$('#unselectedResult').append(uncheckedItems);
}
Should get the result you're looking for.
This should work. Added another array listChecked to track checked values.
<script>
/* Array */
var list = new Array("valuetext000", "valuetext001", "valuetext002", "valuetext003", "valuetext004", "valuetext005", "valuetext006", "valuetext007", "valuetext008", "valuetext009", "valuetext010", "valuetext011", "valuetext012", "valuetext013", "valuetext014", "valuetext015", "valuetext016", "valuetext017")
var listChecked = new Array();
$(document).ready(function() {
displayUnchecked();
});
/* Array will be converted to an ul list */
function displayUnchecked()
{
var html = "";
for (var i = 0; i < list.length; i++) {
if ($.inArray(list[i], listChecked) == -1)
html += "<input type='checkbox' name='boxvalue' value='" + list[i] + "' /><label>" + list[i] + "</label><br>";
}
$("#elmAv").html(html);
}
</script>
</head>
<body>
<form>
<div id="elmAv"></div>
<div id="selectionResult"></div>
<script>
/* Display the items selected */
function showBoxes(frm) {
var checkedItems = "\n";
//alert('here');
//For each checkbox see if it has been checked, record the value.
for (i = 0; i < frm.boxvalue.length; i++) {
if (frm.boxvalue[i].checked) {
listChecked.push(frm.boxvalue[i].value);
}
}
$.each(listChecked, function (index, value)
{
checkedItems = checkedItems + "<li>" + value + "</li>";
});
//alert('here');
displayUnchecked();
//$("#elmAv").empty();
$("#selectionResult").html(checkedItems);
}
</script>
<input type="Button" value="Get Selection" onClick="showBoxes(this.form)" />
</form>
</body>

Remove options from select box if it is already selected in onother

I have a form. The user clicks the add button to add another state + text box for that state. When people select a state in the first box, I want it removed from any other select box that may be added so it can not be selected again.
<form action=state.php method=post>
<a href="javascript:addElement();" style='color:blue; text-decoration:underline;'>Add a State </a>
<a href='javascript:removeElement();' style='color:blue; text-decoration:underline;' >Remove </a><br /><br />
<script type="text/javascript">
var intTextBox=0;
//FUNCTION TO ADD TEXT BOX ELEMENT
function addElement() {
intTextBox = intTextBox + 1;
var contentID = document.getElementById('addresscontent');
var newTBDiv = document.createElement('div');
newTBDiv.setAttribute('id','strText'+intTextBox);
newTBDiv.innerHTML = "<select id='u" + intTextBox + "' name=b_state[" + intTextBox + "][statename]/><option value=''>Select a State</option><option value='AK'>AK</option><option value='AL'>AL</option><option value='AR'>AR</option><option value='AS'>AS</option><option value='AZ'>AZ</option><option value='CA'>CA</option></select> <span style='font-size:12px;'>URL (if different) </span><input style='border:1px solid black; ' size=60 type='text' id='u" + intTextBox + "' name=b__state[" +intTextBox + "][url] /><br>";
contentID.appendChild(newTBDiv);
}
//FUNCTION TO REMOVE TEXT BOX ELEMENT
function removeElement() {
if(intTextBox != 0) {
var contentID = document.getElementById('addresscontent');
contentID.removeChild(document.getElementById('strText'+intTextBox));
intTextBox = intTextBox-1;
}
}
</script>
<div id="addresscontent"></div>
</div>
<input type=submit value='go'>
Here are the steps you need:
1) Gather all of the relevant select fields into a node list:
document.getElementById("myBigForm").getElementsByTagName("select");
2) Now you need to loop through these select fields. For each select field you need to loop through the option elements
3) Perform a remove child if the option contains a certain value.
var removeState = function (x) {
"use strict";
var a = document.getElementById("myBigForm").getElementsByTagName("select"),
b = a.length,
c = 0,
d = [],
e = 0,
f = 0;
for (c = 0; c < b; c += 1) {
d = a[b].getElementsByTagName("option");
e = d.length;
for (f = 0; f < e; f += 1) {
if (d[f].value === x) {
a[b].removeChild(d[f]);
break;
}
}
}
};

Categories

Resources