How to create multiple checkbox handlers in jQuery? - javascript

I have these 2 checkboxes:
<form action="">
<input id="bikeCheckbox" type="checkbox" name="bikeCheckbox" value="Bike">I have a bike<br>
<input id="carCheckbox" type="checkbox" name="carCheckbox" value="Car">I have a car
</form>
The events for each checkbox:
jQuery(function () {
$("#carCheckbox").click(function () {
if($("#carCheckbox").is(":checked")) {
alert("it works");
}
})
});
jQuery(function () {
$("#carCheckbox").click(function () {
if($("#bikeCheckbox").is(":checked")) {
alert("it works");
}
})
});
Now what I want to do is create a for or some kind of loop to create event handlers for multiple checkboxes. So far I am stuck at this code:
jQuery(function () {
var infoArray = ["car", "bike"];
for(var i = 0; i < infoArray.length; i++) {
var id = "#" + infoArray[i] + "Checkbox";
$(id).click(function () {
var myCheckbox = "#" + infoArray[i] + "Checkbox;
if($(myCheckbox).is(":checked")) {
alert("it works");
}
})
}
});
Any help is greatly appreciated.

<form action="">
<input id="bikeCheckbox" class="mybox" type="checkbox" name="bikeCheckbox" value="Bike">I have a bike<br>
<input id="carCheckbox" class="mybox" type="checkbox" name="carCheckbox" value="Car">I have a car
</form>
$('#save_value').click(function(){
$('.mybox:checked').each(function(){
alert($(this).val());
}); });
you try to add class name same for ever check box and used the

You don't need to create an array to save all these values and loop these.
And you definitely don't need a function for each checkbox!
Add a class to your checkboxes you want to check, for example :
<form action="">
<input id="bikeCheckbox" class="mycheckbox" type="checkbox" name="bikeCheckbox" value="Bike">I have a bike<br>
<input id="carCheckbox" class="mycheckbox" type="checkbox" name="carCheckbox" value="Car">I have a car
</form>
Then you can easily loop like this:
jQuery(function () {
// Whenever any of these checkboxes is clicked
$("input.mycheckbox").click(function () {
// Loop all these checkboxes which are checked
$("input.mycheckbox:checked").each(function(){
alert("it works");
// Use $(this).val() to get the Bike, Car etc.. value
});
})
});

use JQuery's each function
jQuery(function () {
$(":checkbox").click(function () {
$(':checkbox:checked').each(function(i){
alert("it works");
});
});
}

if you want to do it by some grouping, like if you want to see only in some of the checkbox in a group, you can use the class name like this below
<form action="">
<input id="bikeCheckbox" class="myCheckBoxGroup" type="checkbox" name="bikeCheckbox" value="Bike">I have a bike<br>
<input id="carCheckbox" class="myCheckBoxGroup" type="checkbox" name="carCheckbox" value="Car">I have a car
</form>
jQuery(function () {
$(".myCheckBoxGroup").click(function () {
$(".myCheckBoxGroup").each(function(){
if($(this).is(":checked")) {
alert("this is checked");
}
});
})
});

Try this.
<input id="chk_bikeCheckbox" type="checkbox" onclick='UpdateIdinHF(this);' name="bikeCheckbox" value="Bike">
<input id="chk_carCheckbox" class="mycheckbox" onclick='UpdateIdinHF(this);' type="checkbox" name="carCheckbox" value="Car">
function UpdateIdinHF(obj) {
var id = $(obj).attr('id');
var name = $(obj).attr('name');
var value = parseInt($(obj).attr('value'));
var IsChecked = $(obj).is(':checked');
$('input[id*="chk_' + name + '"]').each(function () {
if (parseInt($(this).val()) != 0) {
if (IsChecked == true) {
$(this).attr('checked', 'checked');
}
else {
$(this).removeAttr('checked');
}
}
});
}

You can try this also
<script TYPE="text/javascript">
jQuery(function () {
var infoArray = ["car", "bike"];
for(var i = 0; i < infoArray.length; i++) {
var id = "#"+infoArray[i]+"Checkbox";
$(id).click(function () {
if($(id).is(":checked")) {
alert("it works");
}
})
}
});
</script>

You don't need to define classes. Use the following snippet to directly access to the checkbox you have clicked.
$(document).on("click", "input[type='checkbox']", function (e) {
console.log(e.target);
});

Related

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.

Asp.net enable/disable checkboxList with jQuery

I have this kind of structure:
Radio Buttons:
o Enable o Disable
Check Boxes
[]checkBox1
[]checkBox2
[]checkBox3
[]checkBox4
The Above controls are generated dynamically.
<asp:RadioButtonList runat="server" ID="rbSubsidiaries" onclick = "Radio_Click()"/>
<asp:CheckBoxList runat="server" ID="cblSubsidiaries" Enabled="False"/>
What I want is: When the user click on the RadioButton Enable All the checkboxes get enable otherwise disable.
I am at the point where I can see that if the user has clicked on enable radio button.
function Radio_Click() {
if ($('#<%=rbSubsidiaries.ClientID %> input:checked').val() == 'enable') {
alert('enable is clicked');
}
}
But I don't know how to enable all the checkBoxes.
Picture that Contains the the rendered structure of the CheckBoxList. First Two check Boxes.
Try something like this:
$("#cblSubsidiaries > input[type='checkbox']").prop("disabled", false)
Update:
$("#contentpage_0_content_0_cblSubsidiaries input[type=checkbox]").prop("disabled",false)
This is the code which will help you
Html
<input type="radio" name="check" value="enable" class="enableList">Enable
<input type="radio" name="check" value="disable" class="disableList">Disable
<div class="container">
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car </div>
Script
$(document).ready(function () {
$('.enableList').change(function () {
if ($(this).prop('checked') == true) {
$('.container').find('input:checkbox').each(function () {
alert ("enable check box");
});
}
});
$('.disableList').change(function () {
if ($(this).prop('checked') == true) {
$('.container').find('input:checkbox').each(function () {
alert("disable check box");
});
}
});
});
this is working fidler
https://jsfiddle.net/Ln7y6v0n/
Something like this should work:
$('#contentpage_0_content_0_cblSubsidiaries input[type=checkbox]').each(function() {
$(this).prop('checked', true);
});
$(document).ready(function () {
$('#<%=RadioButtonList1.ClientID%>').change(function () {
$('#<%=RadioButtonList1.ClientID%>').each(function () {
var checked = $(this).find('input:radio:checked');
if (checked.val() == "Enable") {
$('#<%=CheckBoxList1.ClientID%>').each(function () {
var checked = $(this).find('input:checkbox');
checked.prop('checked', true);
});
}
else {
$('#<%=CheckBoxList1.ClientID%>').each(function () {
var checked = $(this).find('input:checkbox');
checked.prop('checked', false);
});
}
});
});
});
protected void Page_Load(object sender, EventArgs e)
{
ListItem item = new ListItem();
item.Text = "Enable";
item.Value = "Enable";
RadioButtonList1.Items.Add(item);
ListItem item1 = new ListItem();
item1.Text = "Disable";
item1.Value = "Disable";
RadioButtonList1.Items.Add(item1);
for (int i = 1; i <= 4; i++)
{
ListItem chkitem = new ListItem();
chkitem.Text = "Checkbox" + i;
chkitem.Value = "Checkbox" + i;
CheckBoxList1.Items.Add(chkitem);
}
}
<div>
<asp:RadioButtonList ID="RadioButtonList1" runat="server"></asp:RadioButtonList>
<br />
<hr />
<asp:CheckBoxList ID="CheckBoxList1" runat="server"></asp:CheckBoxList>
</div>

How to input a 'onchange' event on several checkbox

I have this checkbox:
<input type="checkbox" name="foo[]" value="111111">
<input type="checkbox" name="foo[]" value="222222">
<input type="checkbox" name="foo[]" value="333333">
And i'm trying to get the value from the selected checkbox
$("input:checkbox[name^='foo']").each(function(){
var val = $(this).val();
alert(val);
});
But the event isn't called.. Am I doing something wrong?
Sorry for bad english!
Don't use each.
Use .on('change') for your event. Also this.value is easier than $(this).val().
http://jsfiddle.net/65u2t/
$("input:checkbox[name^='foo']").on('change', function () {
var val = this.value;
alert(val);
});
USe is(":checked") to check whether the checkbox is checked
$("input:checkbox[name^='foo']").click(function () {
$("input:checkbox[name^='foo']").each(function () {
if ($(this).is(":checked")) {
alert($(this).val());
}
});
});
Demo
Something very fundamental many of us for get is DOM ready:
$(function() {
$(":checkbox[name^='foo']").on('change', function () {
alert(this.value + ' --- ' + this.checked);
});
});
JS FIDDLE DEMO

JQuery UI Diaglog to populate checkbox values to parent

I have a requirement that a user should select the checkbox values from a pop-up and click on submit on pop-up and the selected values should get displayed back to the parent page.
I was playing with some radio box values which I am able to push to the Parent window but struggling with checkbox values.
Here is what my pop-up looks like and my code is
<p>Please Select a language:</p>
<div id="myDialog" title="Select Language">
<br /><br />
<input type="checkbox" name="countryCheckbox[]" value="English" checked = "checked" /> English <br/>
<input type="checkbox" name="countryCheckbox[]" value="French" /> French <br/>
<input type="checkbox" name="countryCheckbox[]" value="Norwagian" /> Norwagian <br/>
<input type="checkbox" name="countryCheckbox[]" value="Swedish" /> Swedish <br/>
<input type="checkbox" name="countryCheckbox[]" value="Hindi" /> Hindi <br/>
<input type="checkbox" name="countryCheckbox[]" value="Chinese" /> Chinese <br/>
<br /><br />
<label for="yes">Yes!</label><input type="radio" id="yes" value="yes" name="question" checked="checked"><br>
<label for="no">No!</label> <input type="radio" id="no" value="no" name="question">
</div>
<p id="text">Selected Languages are: </p>
and my Jquery code that works for the selected radio button is as below
$(function(){
var execute = function(){
var answer;
$("input").each(function(){
(this.checked == true) ? answer = $(this).val() : null;
});
$("<p>").text("You selected " + answer).appendTo($("body"));
$("#myDialog").dialog("close");
}
var cancel = function() {
$("#myDialog").dialog("close");
}
var dialogOpts = {
buttons: {
"Submit": execute,
"Cancel": cancel
}
};
$("#myDialog").dialog(dialogOpts);
});
I'm trying to add the following JQuery code to display the selected checkbox values on the parent pages
$('#myDialog').submit(function(ev){
ev.preventDefault();
var arr = [];
$('input:checkbox:checked').each(function(){
arr.push($(this).val());
});
$(opener.document).contents().find("#text").text(arr.join(","));
self.close();
});
Please suggest as I'm still struggling to integrate the JQuery code of selected checkboxes to be displayed on the parent page.
you would need to iterate over each input and then store that in an array to append it to the body..
$(function () {
var execute = function () {
var answer = [];;
$("input").each(function () {
if (this.checked) answer.push(this.value);
});
for (var i = 0; i < answer.length ; i++)
$("<p>").text("You selected " + answer[i]).appendTo($("body"));
};
});
Check Fiddle
Code
$(function () {
var execute = function () {
var answer = [];;
$("input").each(function () {
if (this.checked) answer.push(this.value);
});
for (var i = 0; i < answer.length; i++)
$("<p>").text("You selected " + answer[i]).appendTo($("body"));
};
var cancel = function () {
$("#myDialog").dialog("close");
}
var dialogOpts = {
buttons: {
"Submit": execute,
"Cancel": cancel
}
};
$("#myDialog").dialog(dialogOpts);
});
EDIT
var cancel = function () {
$("#myDialog").dialog("close");
}
var saveAndCancel = functionI() {
execute();
cancel();
}
var dialogOpts = {
buttons: {
"Submit": saveAndCancel ,
"Cancel": cancel
}
};

Categories

Resources