Removing from array values of checkboxes in jQuery - javascript

I have a checkboxes like this:
while($userRow=$resultForUsers->fetch_assoc()){
$nameOfUser=$userRow['users_name'];
$userId=$userRow['user_facebook_id'];
$userFBPicture=$userRow['users_picture'];
echo "
<tr class='tr-data-users'>
<td class='text-center'>
<input type='checkbox' class='checkbox' onclick='if(this.checked){selo(this.value)}else{izbaci(this.value)}' value=$userId>
</td>
So, for each user in my database I'm having one checkbox with value of his id. I need id's of all checked users(i.e checkboxes) in one array. I did it this way:
<input type='checkbox' class='checkbox' onclick='if(this.checked){put(this.value)}else{remove(this.value)}' value=$userId>
var niz={};
var index=0;
function put(o){
niz[index++]=o;
console.log(niz);
}
So, console.log now displays id's of all checked checkboxes. What I want to do is if checkbox is unchecked then to remove that id(i.e chechbox value) from array. I tried it like this:
onclick='if(this.checked){put(this.value)}else{remove(this.value)}'
var niz={};
var index=0;
function put(o){
niz[index++]=o;
console.log(niz);
remove(o,niz);
}
function remove(o,niz){
if($.inArray(o,niz)){
console.log('radim');
var indexNiza= $.inArray(o,niz);
niz= $.grep(niz,function(a,o){
return (a!=o);
});
}
}
As you can see this else part should handle if checkbox is unchecked and remove that id from array, but it doesn't work. Would really appreciate help on this.

It seems that the code you have written is taking a very complex route for a simple job. You can see the following for a good example on how to obtain all of the values into their own arrays for the checked and unchecked states.
In the demonstration, I enumerate through the checked and unchecked checkboxes if the user changes the state of any checkbox, and store the checked values in an array named cbChecked and the unchecked values get stored in cbUnchecked
The key here is the selectors used:
Selector usage
Get all 'checked' objects
:checked
Get all 'unchecked' objects
:not(:checked)
Demonstration
$(document).ready(function() {
$("input[type='checkbox']").change(function() {
var cbChecked = new Array();
var cbUnchecked = new Array();
$("input[type='checkbox']:checked").each(function() {
cbChecked[cbChecked.length] = this.value;
});
$("input[type='checkbox']:not(:checked)").each(function() {
cbUnchecked[cbUnchecked.length] = this.value;
});
$("p#cbChecked").html( cbChecked.join() );
$("p#cbUnchecked").html( cbUnchecked.join() );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2> The checkbox form</h2>
<form id="foo">
<p>A : <input type="checkbox" id="a" value="a"></p>
<p>B : <input type="checkbox" id="b" value="b"></p>
<p>C : <input type="checkbox" id="c" value="c"></p>
<p>D : <input type="checkbox" id="d" value="d"></p>
<p>E : <input type="checkbox" id="e" value="e"></p>
<p>F : <input type="checkbox" id="f" value="f"></p>
</form>
<h2>Checked Values</h2>
<p id="cbChecked"></p>
<h2>Unchecked Values</h2>
<p id="cbUnchecked"></p>

Related

How to remove a part of the content of a div with jQuery?

When I click on a checkbox, I append some content to a div (#item_list)
if(cb_new.prop('checked')) {
$("#item_list").append("<input type='hidden' name='post[]' value="+ this.value +">");
} else {
// ??
}
When I uncheck the box I want that exact same string to be removed from the div. Keeping all the others that have a different value (this.value).
So for example I could have:
<div id="item_list">
<input type="hidden" name="post[]" value="102">
<input type="hidden" name="post[]" value="93">
</div>
But if I uncheck
<input type="checkbox" id="d-102-2" name="d-102" value="102" data-id="d-102">
I want :
<div id="item_list">
<input type="hidden" name="post[]" value="93">
</div>
If I check it again, I want it back.
How can I do that?
A vanilla JS solution would look like:
Updated according to your expanded requirements.
document.querySelector(`#item_list input[value='${this.value}']`).remove();
This will query the DOM, find an input element, with a value attribute whose value is equal to this.value, and remove it from the DOM with the remove() method.
A more detailed implementation isn't easy to give without having more information.
You can use the data attribute to assign unique id to the checkbox, once it is checked, input element with same data-uid is added and once unchecked we remove the input element with same data-uid
$(document).ready(function() {
$("#cb_new").change(function() {
if ($(this).prop('checked')) {
$("#item_list").append($("<input data-uid='"+$(this).data('uid')+"' type='text' name='post[]' class='newItem' value='" + $(this).val() + "'>"));
} else {
$('.newItem[data-uid='+$(this).data('uid')+']').remove();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="checkbox" id="cb_new" data-uid="8080" value="tick Me" name="test"/><label for="test">Tick Me</label>
<div id="item_list" style="border:1px solid tomato">
</div>

pass the checked checkbox value in javascript

This is the checkboxes in my HTML:
<input type="checkbox" name="sides" id="1" value="French Fries" >French Fries<br />
<input type="checkbox" name="sides" id="2" value="Baked Potato">Baked Potato<br />
<input type="checkbox" name="sides" id="3" value="Cole Slaw">Cole Slaw<br />
<input type ="button" value = "Enter my side dish selections" onclick="checkbox(sides.value1,sides.value2)"/>
What i want is when the user clicks the button, it should take first two checked boxes and then display it as:
function checkbox(dish1,dish2) {
document.getElementById("side_one").innerHTML = dish1;
document.getElementById("side_two").innerHTML = dish1;
}
I am confused on how to do this, can you please help me here.
You can select the first two checked inputs with [...document.querySelectorAll( ":checked" )].slice( 0, 2 );.
What it does is to create an Array from a NodeList made of all the elements that matches the :checked pseudo-class and slice it in an new Array of two items.
Then you just need to grab the .value of the found <input> elements:
document.querySelector('[type="button"]').onclick = (evt) => {
const checked = [...document.querySelectorAll( ":checked" )].slice( 0, 2 );
checkbox( ...checked.map( (input) => input.value ) )
};
function checkbox(dish1 = "", dish2 = "") {
document.getElementById("side_one").innerHTML = dish1;
document.getElementById("side_two").innerHTML = dish2;
}
<input type="checkbox" name="sides" id="1" value="French Fries" >French Fries<br />
<input type="checkbox" name="sides" id="2" value="Baked Potato">Baked Potato<br />
<input type="checkbox" name="sides" id="3" value="Cole Slaw">Cole Slaw<br />
<input type ="button" value = "Enter my side dish selections"/>
<p id="side_one"></p>
<p id="side_two"></p>
If you want it to search only in the content of a specific element, you just need to make the CSS selector in querySelectorAll more specific.
You can use something like the following:
Array.from(document.getElementsByName('entree')).filter(input => input.checked).map(input => input.value)
This makes an array out of node list of interest, filters out all unchecked elements and returns an array that will have zero or more values depending on what is checked. You can then .join() it or otherwise do as you see fit.
basically, radio is a NodeList, so you can do this
const radioValue = (radio.length > 0) ? radio[0].value : "";

Checkbox Functionality with Two Series of Checkboxes

I'm currently developing a form that has two containers with checkboxes. There first is the master and then there's the secondary which corresponds to the master.
The first container's checkboxes contain a data attribute value such as: "One", "Two", "Three", etc.
Upon clicking one of the master checkboxes (the onCheck function) it checks all the input data attribute values that have an input of "checked", and then proceeds to check every checkbox in the secondary container (which has an array of information in its data attribute) and if there's a match between any of the information, they get checked.
What I'm trying to figure out is the uncheck functionality (the offCheck function). When the user unchecks a master checkbox, it should look through each master input checkbox and if there's one that's checked and it corresponds to the data information in one of the secondary checkboxes, it shouldn't be unchecked. If there's no corresponding information, it gets unchecked.
Please let me know if you need clarification as this can be a bit confusing.
HTML:
<div class="master">
<input type="checkbox"
data-information="One"
/> Primary Checkbox One
<input type="checkbox"
data-information="Two"
/> Primary Checkbox Two
<input type="checkbox"
data-information="Three"
/> Primary Checkbox Three
</div>
<div class="secondary">
<input type="checkbox"
data-information='["One", "Seven", "Ten"]'
/> Secondary Checkbox One
<input type="checkbox"
data-information='["Two", "Three", "Ten"]'
/> Secondary Checkbox One
</div>
jQuery / JavaScript:
function onCheck(){
// Gather all information from checkboxes that are checked
var informationOne = [];
$(".master input:checkbox").each(function(){
if($(this).is(":checked")){
informationOne.push($(this).data("information"));
}
});
$('.secondary input:checkbox').each(function(){
var informationTwo = [];
informationTwo = $(this).data("information");
for(var i=0; i<informationTwo.length; i++){
if($.inArray(informationTwo[i], informationOne) != -1){
$(this).prop("checked", true);
}
}
});
}
function offCheck(){
}
$(".master input:checkbox").change("checked", function(){
if($(this).is(":checked")){
onCheck();
} else {
offCheck();
}
});
Welcome to StackOverflow, Nate!
I took a slightly different approach. Instead of asking, "what changed, and how does it affect the checkboxes?" this code says "something changed, set all the checkboxes according to the current state."
function setCheckboxes(){
[...document.querySelectorAll('.secondary input[type=checkbox]')].forEach((i) => {
i.checked = shouldBeChecked(i);
});
}
function shouldBeChecked(el) {
const matchingNumbers = JSON.parse(el.dataset.information);
return [...document.querySelectorAll('.master input[type=checkbox]:checked')].some((i) =>
matchingNumbers.includes($(i).data('information'))
);
}
$(".master input:checkbox").change("checked", function(){
setCheckboxes();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="master">
<input type="checkbox"
data-information="One"
/> Primary Checkbox One
<input type="checkbox"
data-information="Two"
/> Primary Checkbox Two
<input type="checkbox"
data-information="Three"
/> Primary Checkbox Three
</div>
<div class="secondary">
<input type="checkbox"
data-information='["One", "Seven", "Ten"]'
/> Secondary Checkbox One
<input type="checkbox"
data-information='["Two", "Three", "Ten"]'
/> Secondary Checkbox One
</div>

Dynamic Checkbox selector in jquery

I have a series of dyanmic checkboxes which are creating at runtime but with differnt Ids like this (patter is same)
ModellingTagID_1201
ModellingTagID_1202
ModellingTagID_1203
ModellingTagID_1204
I want to know that above check box change or not? how can i make a dyanmic event with dynamic selector? so that i can get that particular checkbox value has changed? is this kind of thing possible?
$jqLib("#ModellingTagID_*").change(function(){
var lastState =$jqLib("#ModellingTagAlternativePlanning").prop("disabled");
$jqLib("#ModellingTagAlternativePlanning").prop("disabled",!lastState);
});
you can apply same class to all those checkboxes
<li><input type="checkbox" id="yourcbid1" name="x" value="1" class="yourcbclass" /> cb1</li>
<li><input type="checkbox" id="yourcbid2" name="x" value="1" class="yourcbclass" /> cb2</li>
and then you can make function for it's change event like this.
$(function(){
$('.yourcbclass').on('change', function() {
if($(this).is(':checked'))
{
//do your stuff here
}
});
});
see if this helps..
Very simple using this way:--
$("#envoyer").click(function(e) {
var myArray = [];
$(":checkbox:checked").each(function() {
myArray.push(this.value);
});
if(myArray == ''){
alert('Please check');
}else{
alert("Checked: " + myArray.join(","));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
one<input type="checkbox" name='checkbox0' value="one_name" checked>
two<input type="checkbox" name='checkbox1' value="one_name1">
three<input type="checkbox" name='checkbox2' value="one_name2">
<input type="button" id="envoyer" value="Envoyer Reponse" />
</body>
</html>
From what I understand, your issue is to distinguish the unique id of the checkbox, which is being, changed. To achieve this, you can simply add a common class to all the elements, alongwith unique random ids.
cb_1<input type="checkbox" class="someclass" id='ModellingTagID_1201' value="value_1" checked>
cb_2<input type="checkbox" class="someclass" id='ModellingTagID_1202' value="value_2">
cb_3<input type="checkbox" class="someclass" id='ModellingTagID_1203' value="value_3">
And then you can simply bind a change event listener to the common class, and fetch the value of the random id, which has been changed, from inside the event listener.
$(document).ready(function(){
$('.someclass').on('change', function() {
alert($(this).attr("id"));
});
});

Looping through all checked checkboxes on page and pulling id into array not working

UPDATE
I have now solved it, changing this line:
idList.push(this.id);
to:
$(this).attr('id')
I am trying to loop through all of the checkboxes on my page and add the ID's of all that are checked to an array. I have it looping through each checkbox, and detecting whether or not it is checked, but I am having trouble adding the ID of each checked checkbox to an array.
Could someone tell me where I am going wrong?
Thanks.
Javascript:
if (element == 'deleteButton' || element == 'allowButton')
{
//For testing.
//alert("Button Clicked");
//Create an empty array, so it can be re-sized at run time.
var idList = [];
//Loop through all checkboxes, adding each ones id to an array.
$('#reported_rages').find('input[type="checkbox"]:checked').each(function () {
//this is the current checkbox
//For testing.
//alert("Checked");
//Add the current ID to the array
idList.push(this.id);
});
//return false; // or do something else.
}
alert(idList);
Here try implementing these ideas.
JSFiddle
/*sets variable to global so it can be accessed outside of function*/
var idList = [];
function run(){
/*clears the original variable*/
idList = [];
$('#data').find('input[type="checkbox"]:checked').each(function () {
idList.push(this.id);
});
/*prints after list is populated*/
console.log(idList);
$('#results').html(idList);
}
/*binds run function to click of submit*/
$('#submit').click(run);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='data'>
<input id='1' type='checkbox' />
<input id='2' type='checkbox' />
<input id='3' type='checkbox' />
<input id='4' type='checkbox' />
<input id='5' type='checkbox' />
</div>
<div id='results'></div>
<button id='submit'>Submit</button>

Categories

Resources