I have 3 input types :
<input type="checkbox" name="check[0]" value="randomval">
<input type="checkbox" name="check[0]" value="randomval">
<input type="checkbox" name="check[0]" value="randomval">
I have a jquery script that is triggered on a click and append 3 input type like the following, the script just keeps adding the trio of inputs, as much as needed by the user:
<input type="checkbox" name="check[1]" value="randomval">
<input type="checkbox" name="check[1]" value="randomval">
<input type="checkbox" name="check[1]" value="randomval">
There is also a delete button that deletes the 3 inputs.
I'm looking for a way that on each clicks, Jquery loops though all the checkboxes and rename the "name" attribute so it's never missing a number.
Because right now i'm having a problem that when the user deletes inputs I have some names like :
check[0], check[3]
missing :
check[1] and check [2]
So is there a way to loop on each click and reset all the names to be from 1 to number of trio inputs I have ?
Thanks
Just remove index from checkbox names. use
<input type="checkbox" name="check[]" value="randomval">
and you're OK.
DEMO
Also see
HTML multiple input with same name
HTML form input tag name element array with JavaScript
According to comment, to re-assign new index you can do something like below on after each delete and new add:
function reIndex() {
var inputs = $('input[name^=check]');
inputs.each(function (i, el) {
this.name = 'check[' + (i+1) + ']';
});
}
DEMO
Every delete you can iterate the checkboxes and renumber them. Check the DEMO below
function deleteGroup(node){
$(node).closest('.pool').remove();
var counter = 0, arrayIndex = -1, itemCount = 3;
$('#all input[type=checkbox]').each(function(){
++arrayIndex;
if((arrayIndex)%itemCount==0){++counter;}
$(this).prop('name','check['+counter+']');
})
}
function add(){
var idx = ($('#all .pool:last input[type=checkbox]').prop('name').substring(6,7))*1 + 1;
$('#all').append('<div class=pool>'
+'<input type="checkbox" name="check['+idx+']" value="randomval">'
+'<input type="checkbox" name="check['+idx+']" value="randomval">'
+'<input type="checkbox" name="check['+idx+']" value="randomval">'
+'<button onclick="deleteGroup(this)" >Remove</button>'
+'</div>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="all">
<div class=pool>
<input type="checkbox" name="check[0]" value="randomval">
<input type="checkbox" name="check[0]" value="randomval">
<input type="checkbox" name="check[0]" value="randomval">
<button onclick="deleteGroup(this)" >Remove</button>
</div>
<div class=pool>
<input type="checkbox" name="check[1]" value="randomval">
<input type="checkbox" name="check[1]" value="randomval">
<input type="checkbox" name="check[1]" value="randomval">
<button onclick="deleteGroup(this)" >Remove</button>
</div>
</div>
<button onclick="add()" >Add</button>
Related
for single id i did like this but how to get all id on click of button when check the universal checkbox for all the columns
My Html File:-
<td><input type="checkbox" name="option" value="{{item.customerid}} " required ></td>
<input type="button" value="Transfer" (click)="getclickedevent($event)">
My Javascript file:-
getclickedevent(event) {
let id = $("input:checkbox[name=option]:checked").val();
console.log("The Required checkbox checked is "+ id)
}
make all the id's children of one master id
then use this
var div = // getElementById, etc
var children = div.childNodes;
var elements = [];
for (var i=0; i<div.childNodes.length; i++) {
var child = div.childNodes[i];
if (child.nodeType == 1) {
elements.push(child)
}
}
I hope you don't mind but I took the approach of refactoring your code.
Here is the HTML:
<td>
<input type="checkbox" name="option" value="{{item.customerid}}" required >
</td>
<input type="button" value="Transfer">
<div id='options'>
<br><input name='options' type="checkbox">
<br><input name='options' type="checkbox">
<br><input name='options' type="checkbox">
<br><input name='options' type="checkbox">
<br><input name='options' type="checkbox">
</div>
And here is the jQuery. I used jQuery because you missed native javascript and jQuery in your code:
$('input[type="button"][value="Transfer"]').click( function() {
let id = $("input:checkbox[name=option]").is(':checked');
$('input[name="options"]').each(function() {
this.checked = id;
});
});
You can see it all working here.
You can get all checked checkboxes values inside button click event handler using jquery .map() method like:
var ids = $("input:checkbox[name=option]:checked").map(function(){
return $(this).val();
}).get();
console.log(ids) //==> ['xxx', 'xxx', 'xxx', ...]
This will give a basic array containing all checked checkboxes values.
DEMO:
$("#checkAll").click(function() {
$("input:checkbox[name=option]").prop('checked', this.checked);
var ids = $("input:checkbox[name=option]:checked").map(function() {
return $(this).val();
}).get();
console.log(ids)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="checkAll">Check All
<hr />
<input type="checkbox" name="option" value="1">Item 1
<input type="checkbox" name="option" value="2">Item 2
<input type="checkbox" name="option" value="3">Item3
This should work for you. ↓↓
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<input type="checkbox" onclick="$('input[name*=\'customer_store\']').prop('checked', this.checked);"/> Select / Deselect<br>
<input type="checkbox" name="customer_store[]" value="xyz"/>xyz<br>
<input type="checkbox" name="customer_store[]" value="abc"/>abc<br>
Add ID to your button inputs and call on them as selectors for .click().
Add a function to get the click on the select all button and set all inputs to checked used an added class of option for to select the input elements that are check boxes.
Define an empty array to hold your values. Run your checked values through .each() loop and assign them to the array.
Those values will now live in the options array.
$(document).ready(function() {
$('#selectall').click(function(){
$('.option').prop("checked", true);
});
$('#transfer').click(function() {
var options = [];
$.each($("input[type='checkbox']:checked"), function() {
options .push($(this).val());
});
console.log(options);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="option" type="checkbox" name="option" value="{{item.customerid}}">
<input class="option" type="checkbox" name="option" value="{{item.customerid}}">
<input class="option" type="checkbox" name="option" value="{{item.customerid}}">
<input class="option" type="checkbox" name="option" value="{{item.customerid}}">
<input type="button" id="transfer" value="Transfer">
<input type="button" id="selectall" value="Select All">
I have a list of check boxes with different values.
<input type="checkbox" value="55" id="myId">
<input type="checkbox" value="65" id="myId">
<input type="checkbox" value="75" id="myId">
<input type="checkbox" value="85" id="myId">
<input type="checkbox" value="95" id="myId">
When I'm getting those values using js that will take only value=55 only. It is due to the same id="myId"
var x = "";
$("input[type='checkbox']").change(fucntion(){
if(this.checked){
x = x+","+x;
}
});
When run that will load only 55 values like-: 55,55,55,55
Attribute id should be unique. You can use an array instead of string variable. Then simply add or remove item based on the check box status:
var x = [];
$("input[type='checkbox']").change(function(){
if(this.checked){
x.push(this.value);
}
else {
var index = x.indexOf(this.value);
x.splice(index, 1);
}
console.log(x.join(','));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="55" id="">55
<input type="checkbox" value="65" id="">65
<input type="checkbox" value="75" id="">75
<input type="checkbox" value="85" id="">85
<input type="checkbox" value="95" id="">95
First of all don't use multiple same ids on your page, id should be unique on entire page, try data attributes instead
$("input[type='checkbox']").change(function(){
var x = "";
$("[data-id=myId]").each(function(){
if(this.checked){
x = x + $(this).val() + ",";
}
});
console.log(x);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="55" data-id="myId">
<input type="checkbox" value="65" data-id="myId">
<input type="checkbox" value="75" data-id="myId">
<input type="checkbox" value="85" data-id="myId">
<input type="checkbox" value="95" data-id="myId">
If selection order isn't important can map() the checked values to new array every change
Your string concatenation approach doesn't take into account unchecking a previously checked input
$(':checkbox').change(function(){
var vals = $(':checkbox:checked').map(function(){
return this.value
}).get()
console.log(vals.join())
})
// insert values as text for demo
.wrap(function(){
return $('<label>',{text:this.value})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="55" >
<input type="checkbox" value="65" >
<input type="checkbox" value="75">
<input type="checkbox" value="85" >
<input type="checkbox" value="95" >
Note that ID's must be unique in a page
At the end of my HTML site I want to show the name of all checked checkboxes.
For example, if I have following checkboxes:
<input type="checkbox" name="Product1" value="149" id="checkbox_1" autocomplete="off"/>
<input type="checkbox" name="Product2" value="249" id="checkbox_2" autocomplete="off"/>
<input type="checkbox" name="Product3" value="349" id="checkbox_3" autocomplete="off"/>
The name of all the ones who are checked, should be listed on any position on the same page without pressing a button.
Like this, if he choosed 2 and 3:
You choosed following products:
Product2
Product3
If he choosed nothing, nothing should appear.
var names = $(':checkbox:checked').map(function(){ return this.name; });
if (names.length) {
console.log(names.get().join(','));
}
It would be better if they had a shared class though, then you could make the selector better with
$('.theclass').filter(':checked').map(function(){ return this.name; });
//demo example
$(function(){
//get all the products
var $allProducts = $('.product');
//get the area to write the results to
var $selectedProductsListing = $('#selectedProducts');
//get the label
var $selectedProductsLabel = $('#selectedProductsLabel');
//when you click a checkbox, do the logic
$allProducts.on('click', function(){
//set the content of the results
$selectedProductsListing.html(
//only return those that are checked
$allProducts.filter(':checked').map(function(index, checkbox){
//return a div string with the name for display
return '<div>'+ checkbox.name +'</div>';
}).get().join('') //get the array of strings and join them by nothing
);
//hide the label if no checkboxes are selected
if ($selectedProductsListing.text().trim().length) {
$selectedProductsLabel.show();
} else {
$selectedProductsLabel.hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="Product1" value="149" class="product" id="checkbox_1" autocomplete="off"/>
<input type="checkbox" name="Product2" value="249" class="product" id="checkbox_2" autocomplete="off"/>
<input type="checkbox" name="Product3" value="349" class="product" id="checkbox_3" autocomplete="off"/>
<div id="selectedProductsLabel" style="display:none">Products Selected:</div>
<span id="selectedProducts"></span>
you could check below snippet:
$("input").click(function(){
var seList = $("input:checked").map(function(v){
return (this.name);
})
$("#info").html(seList.join("<br>"))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<input type="checkbox" name="Product1" value="149" id="checkbox_1" autocomplete="off"/>
<input type="checkbox" name="Product2" value="249" id="checkbox_2" autocomplete="off"/>
<input type="checkbox" name="Product3" value="349" id="checkbox_3" autocomplete="off"/>
<div id="info">
</div>
I would like to make the data from this jquery submit go into one variable that I can put into html. I am using the append button to add html to my form, but can't figure out how to make the data variable into an array of each check box value .
https://jsfiddle.net/soljohnston777/k5yc1y2a/2/
JQuery:
$(".checkboxadd").click(function(){
$('[id^="add_policies_checkbox"]').each(function(i, v){
//alert(this.value);
if($(v).prop('checked')){
var data=$(v).val();
$("#div_to_add_this_checkbox_value").append("<input type=hidden name='pnpID_instructions' value=\'"+data+"\' />P&P #'s: "+data+"");}
});
});//end ajaxifypolicies
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="1" id="add_policies_checkbox1"/>
<input type="checkbox" value="2" id="add_policies_checkbox2"/>
<input type="checkbox" value="3" id="add_policies_checkbox3"/>
<button class="checkboxadd">Submit</button>
<div id="div_to_add_this_checkbox_value"></div>
<div> Check mark all 3 then hit submit, What I want is the output like an array:<br>P&P #'s:1,2,3 <br> (and the hidden value="1,2,3")
</div>
To convert an array to a string you can use array.join(',').
$(".checkboxadd").click(function() {
var data = [];
$('[id^="add_policies_checkbox"]').each(function(i, v) {
if ($(v).prop('checked')) {
data.push($(v).val());
}
});
console.log(data);
$("#div_to_add_this_checkbox_value").html('P&P #s:' + data.join(',') + "<input type='hidden' name='pnpID_instructions' value='"+data.join(',')+"' />");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="1" id="add_policies_checkbox1" />
<input type="checkbox" value="2" id="add_policies_checkbox2" />
<input type="checkbox" value="3" id="add_policies_checkbox3" />
<button class="checkboxadd">Submit</button>
<div id="div_to_add_this_checkbox_value"></div>
I would like to know how to add checkboxes on input type number change.
By default I have :
HTML CODE
<label for checkbox_number>Number of checkboxes :</label>
<input id="checkbox_number" name="checkbox_number" type="number" size="1" maxlength="1" value="1" onkeydown="change_cb()"/>
<input id="checkbox1" type="checkbox" name="checkbox[]" value="cb1">
If I change my checkbox number to 2, I would like javascript/ajax add
<input id="checkbox2" type="checkbox" name="checkbox[]" value="cb2">
Same as if I change my change number to 1, it has to remove one checkbox.
I already did same thing but with table (add one row or remove one row) but here i don't know how to add new element (on my first script I don't add new table, just new row)...
Need help to write my JS function change_cb()
EDIT TO GIVE YOU MY ANSWER
I find how to do this with DADE help (thank you DADE) :
HTML CODE (same)
<label for="cb_number">How many checkboxes ?</label>
<input id="cb_number" name="cb_number" type="number" size="1" maxlength="1" value="1">
<div class="my_cb_result"></div>
jQuery CODE
$(window).ready(function() {
$('#cb_number').on('keyup mouseup', function() {
var number = parseInt($(this).val());
$('input[type="checkbox"]').remove();
$('label[class="to_del"]').remove();
for (var i=1;i<=number;i++) {
var data = '<label for="checkbox" class="to_del">Label of my checkbox</label><input id="checkbox'+i+'" type="checkbox" name="checkbox[]" value="'+i+'">';
}
$('.my_cb_result').append(data);
});
});
JSFiddle with comments
Try this:
var ele = '<input id="checkbox2" type="checkbox" name="checkbox[]" value="cb2">';
document.getElementById("yourElementID").appendChild(ele);
HTML:
<label for checkbox_number>Number of checkboxes :</label>
<input id="checkbox_number" name="checkbox_number" type="number" size="1" maxlength="1" value="0">
<div class="inputs"></div>
JS:
$('#checkbox_number').on('keyup mouseup', function() {
var number = parseInt($(this).val());
$('input[type="checkbox"]').remove();
for (var i=1;i<=number;i++) {
var data = '<input id="checkbox'+i+'" type="checkbox" name="checkbox[]" value="cb'+i+'">';
$('.inputs').append(data);
}
});
JSFiddle with comments
Do you mean if checkbox_number's value is set to "2" that you'd like to render the second checkbox?
If so, you should use onblur or similar on checkbox_number to run a function that will render the new one via a getElementById and appendChild.
IE:
<script type="text/javascript">
function change_cb() {
var secondCheckbox = '<input id="checkbox_number2" name="checkbox_number" type="number" size="1" maxlength="1" value="1" />";
document.getElementById("yourForm").appendChild(secondCheckBox);
}
</script>
<div id="yourForm">
<label for checkbox_number>Number of checkboxes :</label>
<input id="checkbox_number" name="checkbox_number" type="number" size="1" maxlength="1" value="1" onblur="change_cb()"/>
<input id="checkbox1" type="checkbox" name="checkbox[]" value="cb1">
</div>
edit: From what you're posting, you shouldn't need Ajax, by the way.