dynamic variable name from form input name - javascript

How would i create a dynamic variable name based on all the forms input checkbox list names? This is what i have so far
var nameArray = [];
$.each($("#store-filter input").serializeArray(), function(i, field) {
nameArray[field.name] = field.value;
});
alert(nameArray[0]);
for (i = 0; nameArray.length > i; i++)
{
//alert(nameArray[i]);
var nameArray[i] = nameArray[i].value;
var nameArray[i]+'_checked_values' = $(\'input[name="nameArray[i]+[]"]:checked\').map(function() {
return this.value;
}).get();
}
alert(make); //variable name from name="make[]"
sample HTML
<form id="store-filter" action:"javascript:void(0);">
<span id="store">
<input id="store_0" value="2" name="store[]" type="checkbox"> <label for="store_0">Store 1</label>
<input id="store_1" value="3" name="store[]" type="checkbox"> <label for="store_1">Store 2</label>
<input id="store_2" value="3" name="store[]" type="checkbox"> <label for="store_2">Store 3</label>
</span>
<span id="make">
<input id="make_0" value="2" name="make[]" type="checkbox"> <label for="make_0">make
1</label>
<input id="make_1" value="3" name="make[]" type="checkbox"> <label for="make_1">make
2</label>
<input id="make_2" value="4" name="make[]" type="checkbox"> <label for="make_2">make
3</label>
</span>
<span id="time">
<input id="time_0" value="2" name="time[]" type="checkbox"> <label for="time_0">time 1</label>
<input id="time_1" value="3" name="time[]" type="checkbox"> <label for="time_1">time 2</label>
<input id="time_2" value="4" name="time[]" type="checkbox"> <label for="time_2">time 3</label>
</span>
</form>
so later on in my code i can create a url string ?make=1,2,3&store=40,5,6&time=1,2,3,4 etc
the $_GET parameters are taken from the input check boxes name's dynamically

I'd suggest the following approach, obviously I'm binding to the click of a button, you should add that to the event/interaction of your choice:
function makeQueryString() {
function keyValues(idPref) {
// using the pass-in 'id' as a key:
var key = idPref,
// searching within the element identified with that 'id' for
// other elements whose 'id' *starts* with that string:
values = $('#' + idPref + ' input[id^="' + idPref + '"]').map(function() {
// iterating over those found elements and, if the value is *not* the
// defaultValue (value on page-load), *or* the checked state is not the
// default state (checked/unchecked as on page-load):
if (this.value !== this.defaultValue || this.checked !== this.defaultChecked) {
// we return the value:
return this.value;
}
// get() converts to a JavaScript Array, join() concatenates Array elements
// to form a string:
}).get().join(',');
// if there is a key, and there are associated values, we return a 'key=value,value2'
// string, otherwise we return an empty string:
return key && values.length ? key + '=' + values : '';
}
// we return the value obtained after iterating over the form's span elements
// that have an [id] attribute:
return $('form span[id]').map(function(){
// obtaining the 'key=value1,value2' strings from the called-function:
return keyValues(this.id);
// converting those returned elements into an Array, and joining with & characters:
}).get().join('&');
}
$('#test').click(function(e) {
e.preventDefault();
console.log(makeQueryString());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="test">test</button>
<form id="store-filter" action: "javascript:void(0);">
<span id="store">
<input id="store_0" value="2" name="store[]" type="checkbox"> <label for="store_0">Store 1</label>
<input id="store_1" value="3" name="store[]" type="checkbox"> <label for="store_1">Store 2</label>
<input id="store_2" value="3" name="store[]" type="checkbox"> <label for="store_2">Store 3</label>
</span>
<span id="make">
<input id="make_0" value="2" name="make[]" type="checkbox"> <label for="make_0">make
1</label>
<input id="make_1" value="3" name="make[]" type="checkbox"> <label for="make_1">make
2</label>
<input id="make_2" value="4" name="make[]" type="checkbox"> <label for="make_2">make
3</label>
</span>
<span id="time">
<input id="time_0" value="2" name="time[]" type="checkbox"> <label for="time_0">time 1</label>
<input id="time_1" value="3" name="time[]" type="checkbox"> <label for="time_1">time 2</label>
<input id="time_2" value="4" name="time[]" type="checkbox"> <label for="time_2">time 3</label>
</span>
</form>
References:
CSS:
Attribute-presence and value ([attribute],[attribute="value"]) selectors.
JavaScript:
Array.prototype.join().
defaultChecked and defaultValue (HTMLInputElement).
jQuery:
get().
map().

You are in Javascript, you do not need to declare the size of your arrays, there is no propblems by adding/removing anything from an Object/Array.
You should create a variable make then get the values in. Finally, you will be able to get it back.
var make;
$.each($("#store-filter input").serializeArray(), function(i, field) {
make[i] = field.name;
});
Later in your code, you will use the array make.
make[0];
EDIT:
Here is an example i did for you: http://jsfiddle.net/kjkzm8qm/
NOTE: Your $.each($("#store-filter input").serializeArray() ... is useless, you should select all your inputs by adding a class AND, you should END your input tags by adding a / at the end.
HTML
<input name="test" class="inputs" />
JAVASCRIPT
$.each($(".inputs"), function(){ });

Update for david's answer.
If you want to remove & then add this code below
For this check the key value is not null
let keyValue = keyValues(this.id);
if (keyValue != ''){
return keyValue;
}

Related

How to check checkboxs based on text string HTML/JS

Is it possible to check checkbox based on string text using js or jQuery:
$(':checkbox').filter(function() {
return $(this).parent().next('label').text() === 'Text 1';
}).prop('checked', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="selectit"><input value="171" type="checkbox" name="post_category[]" id="in-category-171">Text 1</label>
<label class="selectit"><input value="172" type="checkbox" name="post_category[]" id="in-category-172">Text 2</label>
<label class="selectit"><input value="173" type="checkbox" name="post_category[]" id="in-category-173">Text 3</label>
(JSFiddle)
A JS example. It grabs the labels, finds the label with the text you pass in as an argument to the function, and if that label is found checks it's corresponding checkbox.
function checkBoxFromLabelText(str) {
// Select all the labels and coerce the array-like node-list
// into an array
const labels = [...document.querySelectorAll('label')];
// `find` the label with the text content you supplied
// as a string argument to the function
const label = labels.find(label => label.textContent.trim() === str);
// If it exists find the label's checkbox and check it
if (label) label.querySelector('[type="checkbox"]').checked = true;
}
checkBoxFromLabelText('Text 1');
<label class="selectit"><input value="171" type="checkbox" name="post_category[]" id="in-category-171">Text 1</label>
<label class="selectit"><input value="172" type="checkbox" name="post_category[]" id="in-category-172">Text 2</label>
<label class="selectit"><input value="173" type="checkbox" name="post_category[]" id="in-category-173">Text 3</label>
Your code is almost there, you just need to remove next('label') as parent() already gives you a reference to the label.
Also note that you can make the code a little more succinct with an arrow function:
$(':checkbox').filter((i, el) => $(el).parent().text().trim() === 'Text 1').prop('checked', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="selectit"><input value="171" type="checkbox" name="post_category[]" id="in-category-171">Text 1</label>
<label class="selectit"><input value="172" type="checkbox" name="post_category[]" id="in-category-172">Text 2</label>
<label class="selectit"><input value="173" type="checkbox" name="post_category[]" id="in-category-173">Text 3</label>

How to check all checkbox when check on one checkbox and click on a button and get the values?

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">

How to get multiple checkboxes values using id

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

Multiple ID with Javascript and PHP

I have to do a simple work.
I have:
echo' <div class="col-sm-12" id="recensioni_titolo">
<form role="form" id="review-form" method="post" action="php\insert_comment.php">
<div class="row">
<div class="col-sm-8">
<div class="form-group">
<input type="text" class="form-control" name="Titolo" id="titolo_review" placeholder="Titolo">
<input type="text" class="form-control" name="ID_locale" id="titolo_review" value="'.$id_Local.'" style="visibility: hidden; position:fixed;">
</div>
</div>
<div class="col-sm-4">
<fieldset class="rating">
<input type="radio" id="star5'.$id_Local.'" name="Voto" value="5" /><label class = "full" for="star5'.$id_Local.'" title="Ottimo - 5 stelle"></label>
<input type="radio" id="star4'.$id_Local.'" name="Voto" value="4" /><label class = "full" for="star4'.$id_Local.'" title="Buono - 4 stelle"></label>
<input type="radio" id="star3'.$id_Local.'" name="Voto" value="3" /><label class = "full" for="star3'.$id_Local.'" title="Discreto - 3 stelle"></label>
<input type="radio" id="star2'.$id_Local.'" name="Voto" value="2" /><label class = "full" for="star2'.$id_Local.'" title="Insufficiente - 2 stelle"></label>
<input type="radio" id="star1'.$id_Local.'" name="Voto" value="1" /><label class = "full" for="star1'.$id_Local.'" title="Pessimo - 1 stella"></label>
</fieldset>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<textarea class="form-control textarea" rows="3" name="Review" id="review" placeholder="Inserisci una descrizione.."></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<button type="button" class="btn main-btn pull-right" name="submit_review" id="submit_review'.$id_Local.'">Invia</button>
</div>
</div>
This code is generating the same thing for 5 times. I'have to find one method to declare and use the id="review-form" in a unique mode because with this code:
$(document.getElementsByName("submit_review")).unbind().click(function() {
var chx = document.getElementsByName("Voto");
for (var i=0; i<chx.length; i++) {
// If you have more than one radio group, also check the name attribute
// for the one you want as in && chx[i].name == 'choose'
// Return true from the function on first match of a checked item
if (chx[i].type == 'radio' && chx[i].checked) {
$.ajax({
url : "php/insert_comment.php",
type : "post",
data : $("#review-form").serialize(),
success : function(data){
$.ajax({
url : "php/reviews.php",
type : "post",
data: {'id_Local' : $('.modal').attr('data-modal')},
success : function(data){
$('#box_recensioni').html(data);
chx[i].checked=false;
}
})
}
})
return true;
}
}
// End of the loop, return false
alert("Inserisci almeno il voto!!")
return false;
});
I have only the first element is working.
I can generate the id with "id'.$variable'" but I don't know how to refers to every single id in the javascript file.
Thank you to all in advance
In HTML, an ID is supposed to be unique :
The id global attribute defines a unique identifier (ID) which must be unique in the whole document.
This is why JavaScript can grab only the first occurence of an ID, since it's supposed to be the only one. You may want to replace those multiple IDs with classes, which is at least correct in HTML5 and will be also smarter in Javascript.
Here is a link to the post in the Mozilla documentation of IDs in HTML, to be sure that you understand the role of this tag.
As other's have said using the same ID would be useless instead you may want to use a class identifier. And assuming you want to create multiple form elements... and you don't have a unique identifier to use in your scripts you may try the following which I haven't tested...
I see you have already gotten the radio button
var chx = document.getElementsByName("Voto");
and performed a check on it under your if statement
if (chx[i].type == 'radio' && chx[i].checked) {
if so, maybe you can try to get the closest form element of the radio button that you are dealing with (i.e. checked) by doing something like
var thisForm = chx[i].closest('form')
--and later do thisForm.serialize();
check this out for more detail in using closest
You can create an array, then use an loop through each radio button pushing the id into the array. Then use the array for the ids.
var radioIds = new Array();
$('.rating input[name="Voto"]').each(function(){
radioIds.push($(this).attr('id'));
});
console.log(radioIds)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-4">
<fieldset class="rating">
<input type="radio" id="star54" name="Voto" value="5" /><label class="full" for="star54" title="Ottimo - 5 stelle"></label>
<input type="radio" id="star44'" name="Voto" value="4" /><label class="full" for="star44" title="Buono - 4 stelle"></label>
<input type="radio" id="star34" name="Voto" value="3" /><label class="full" for="star34" title="Discreto - 3 stelle"></label>
<input type="radio" id="star24'" name="Voto" value="2" /><label class="full" for="star24" title="Insufficiente - 2 stelle"></label>
<input type="radio" id="star14" name="Voto" value="1" /><label class="full" for="star14" title="Pessimo - 1 stella"></label>
</fieldset>
</div>

I have multiple checkboxes, and want to make a rule for 2 of them so that if I select 1 the other cannot be selected

​<form>
<label for="1">Text 1</label>
<input type="checkbox" name="1" value="something1" id="1"><br>
<label for="2">Text 2</label>
<input type="checkbox" name="2" value="something2" id="2"><br>
<label for="3">Text 3</label>
<input type="checkbox" name="3" value="something3" id="3"><br>
<label for="4">Text 4</label>
<input type="checkbox" name="4" value="something4" id="4">
</form>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
Those are the checkboxes , I have tried to search all over the internet and didn't find anything.
I want to allow the user to check id 3 and 4 BUT if he checks 1 , then 2 is not available to check, or if he checks 2 then 1 is not available to check.
And to the unavailable to add a class .. named ..
grade-out{ color: #DDD;}
Hope u understand the problem. Thanks in Advance !!
I would add data-groupid attribute to your checkboxes to identify which group they belong to. And then add a click handler to checkboxes belonging to group, which would disable all other checkboxes in the same group when checked and enable them when unchecked..
Assumming your markup is consistent and labels are always predecessors of respective checkboxes, you can easily target them using the prev() method.
$('input:checkbox[data-group]').click(function() {
var groupid = $(this).data('group');
var checked = $(this).is(':checked');
if(checked) {
$('input:checkbox[data-group=' + groupid + ']').not($(this))
.attr('disabled', 'disabled')
.prev().addClass('grade-out');
} else {
$('input:checkbox[data-group=' + groupid + ']')
.removeAttr('disabled')
.prev().removeClass('grade-out');
}
});
DEMO
I would assign an attribute data-disable to disable certain elements and check onchange.
This is how I would do it:
<form>
<label for="1">Text 1</label>
<input type="checkbox" name="1" value="something1" id="1" data-disable="2,3"><br>
<label for="2">Text 2</label>
<input type="checkbox" name="2" value="something2" id="2" data-disable="1"><br>
<label for="3">Text 3</label>
<input type="checkbox" name="3" value="something3" id="3"><br>
<label for="4">Text 4</label>
<input type="checkbox" name="4" value="something4" id="4">
</form>​​​
and script:
$('input:checkbox​​​​​​​​​​​​​​​​​​')​.on('change', function(){
var toUncheck = $(this).attr('data-disable');
var self = $(this);
$.each(toUncheck.split(','), function(el, val){
if(self.attr('checked') == 'checked'){
$('#'+val).attr('disabled', 'disabled');
} else {
$('#'+val).removeAttr('disabled');
}
});
});​
JSFiddle Demo
You could use radio form inputs. Anyway, if it's a must to use checkboxes then you could use some javascript (with jQuery, for example)
$('#1,#2').click(function(){
var $this = $(this);
var theOtherId = $this.attr('id') == 1 ? 2 : 1;
var theOtherOne = $('#'+theOtherId);
if( $this.is(':checked') ) theOtherOne.attr('checked',false);
});
It this what you're looking for?
Re-worked example: demo fiddle
$('#1,#2').click(function(){
var $this = $(this);
var theOtherId = $this.attr('id') == 1 ? 2 : 1;
var theOtherOne = $('#'+theOtherId);
if( $this.is(':checked') ) theOtherOne.attr('disabled',true);
else theOtherOne.attr('disabled',false);
});
Although there are more complex and flexible solutions above if you wish a solid but clear usage sample look at this. Using id's make things easier.
http://jsfiddle.net/erdincgc/uMhbs/1/
HTML (added class and id) ;
<form>
<label for="1">Text 1</label>
<input class="checks" type="checkbox" id="option1" name="option1" value="something1" id="1"><br>
<label for="2">Text 2</label>
<input class="checks" type="checkbox" id="option2" name="option2" value="something2" id="2"><br>
<label for="3">Text 3</label>
<input class="checks" type="checkbox" id="option3" name="option3" value="something3" id="3"><br>
<label for="4">Text 4</label>
<input class="checks" type="checkbox" id="option4" name="option4" value="something4" id="4">
</form>
And JS
$('.checks').click(function(){
op1 = $('#option1') ;
op2 = $('#option2') ;
this_id = $(this).attr("id") ;
this_state = $(this).attr("checked");
if(this_id =="option1"){
if( this_state == "checked" ){
op2.attr("disabled",true);
}
else {
op2.attr("disabled",false);
}
op2.prev().toggleClass('disabled');
}
if(this_id=="option2"){
if( this_state=="checked" )
op1.attr("disabled",true);
else {
op1.attr("disabled",false);
}
op1.prev().toggleClass('disabled');
}
});
Use $("#element_id").hide(); for disabling the check box
Use $("#element_id").attr("checked", true); to check if the check box is selected
Use $("#element_id").addclass(); to add class to an element so in short search for jQuery selectors and you will find the solutions
Vist for more information http://api.jquery.com/category/selectors/ I hope I help take care

Categories