Creating an Associative Array using JQuery - javascript

I am trying to create an associative array using JQuery. I would like it to be filled with the values of the checkboxes a user has selected from the UI.
I was creating the array like this at first:
$contentArray = [];
$('.content-filter :checked').each(function(){
$contentArray.push(this.value);
})
but the problem with this is that when I pass it to a php script via Ajax it was making it very difficult to get values from it. I'd rather be able to get the values from the array based on the key associated with it.
So I decided to modify my code to this:
$contentArray = new Array(); //Hold checked "content" filters
//Content Filter - cycle through each filter and add value of checked ones to array
$('.content-filter :checked').each(function(){
$contentArray[this.value] = this.value;
})
however now when I perform console.log I am being told the contents of my array contains nothing.
Can anyone advise me on how to fix this issue and show me where I am going wrong?

Your filter is wrong - you need to remove the space before :checked, otherwise it will look for an element inside the checkbox which is checked, which obviously doesn't exist:
$contentArray = new Array(); //Hold checked "content" filters
//Content Filter - cycle through each filter and add value of checked ones to array
$('.content-filter:checked').each(function(){
$contentArray[this.value] = this.value;
})
console.log($contentArray);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" class="content-filter" value="1" />
<input type="checkbox" class="content-filter" value="2" checked="checked" />
<input type="checkbox" class="content-filter" value="3" checked="checked" />
<input type="checkbox" class="content-filter" value="4" />
<input type="checkbox" class="content-filter" value="5" />
However, as mentioned, this just creates a fragmented array. If you want truly associative keys, you should create an object (tho I don't see this being easier to process in php):
$contentObject = {}; //Hold checked "content" filters
//Content Filter - cycle through each filter and add value of checked ones to array
$('.content-filter:checked').each(function(){
$contentObject[this.value] = this.value;
})
console.log($contentObject);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" class="content-filter" value="1" />
<input type="checkbox" class="content-filter" value="2" checked="checked" />
<input type="checkbox" class="content-filter" value="3" checked="checked" />
<input type="checkbox" class="content-filter" value="4" />
<input type="checkbox" class="content-filter" value="5" />

Related

Display custom HTML5 data attributes from selected radio buttons

I am attempting to retrieve custom data attributes from selected radio buttons from multiple button groups and display them for the user.
Here is an example of the radio buttons I am working with:
<input type="radio" id="poolSmallButton" name="pool" class="calc" value="500" data-selection-name="Small Pool"/>
<input type="radio" id="poolMediumButton" name="pool" class="calc" value="1000" data-selection-name="Medium Pool"/>
<input type="radio" id="landscapingSmallButton" name="landscaping" value="100" class="calc" data-selection-name="Small Landscaping"/>
<input type="radio" id="landscapingMediumButton" name="landscaping" value="500" class="calc" data-selection-name="Medium Landscaping"/>
<span id="quote-items" name="quote-items"></span>
I am currently using this jQuery to extract the data attributes from the selected radio buttons but currently only the top-most radio button loaded in the DOM will only display as my output:
var itemNames = [$(".calc:checked").attr("data-selection-name")];
$("#quote-items").text(itemNames)
Thanks!
Whenever you use .attr(key) method it will always fetch you the value of first matched element. To get the value from all matched element, you need to iterate, there are various methods for that. .each() can be used to iterate and push the value in an array.
Here I have used .map() to get an array of attribute value for checked checkbox
$('.calc').change(function() {
var itemNames = $(".calc:checked").map(function() {
return $(this).attr("data-selection-name")
})
.get() //Get an array
.join(',') //Generate Comma seperate string;
$("#quote-items").text(itemNames);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" id="poolSmallButton" name="pool" class="calc" value="500" data-selection-name="Small Pool" />
<input type="radio" id="poolMediumButton" name="pool" class="calc" value="1000" data-selection-name="Medium Pool" />
<input type="radio" id="landscapingSmallButton" name="landscaping" value="100" class="calc" data-selection-name="Small Landscaping" />
<input type="radio" id="landscapingMediumButton" name="landscaping" value="500" class="calc" data-selection-name="Medium Landscaping" />
<span id="quote-items" name="quote-items"></span>
Additionaly, You can use Element.dataset property to access data-* prefixed attribute like
this.dataset.selectionName;
instead of
$(this).attr("data-selection-name");
How to
<input type="radio" id="poolSmallButton" name="pool" class="calc" value="500" data-selection-name="productname" ata-selection-price="productprice" />
$("#sonuc-v2").text(data-selection-price);
$("#sonuc-v2").text(data-selection-price);

Get value and text of selected checkboxes

I am trying to get an array of selected checkboxes values and text on button click
<input type="checkbox" name="checkbox[]" value="1" /><label>text1</label>
<input type="checkbox" name="checkbox[]" value="2" /><label>text2</label>
<input type="checkbox" name="checkbox[]" value="3" /><label>text3</label>
<input type="checkbox" name="checkbox[]" value="4" /><label>text4</label>
I'm getting values of the checkboxes but how to get text also in array
var checkboxes = document.getElementsByName('checkbox[]');
var vals = 0;
for (var i=0, n=checkboxes.length;i<n;i++) {
if (checkboxes[i].checked) {
vals += ","+checkboxes[i].value;
}
}
Thank you!
You can use map() to create an array of the values you require:
var labelValues = $(':checkbox:checked').map(function() {
return [ $(this).next('label').text(), this.value ];
}).get();
However given your desired output it would make more sense to create an object with the labels as the properties, something like this:
var obj = {};
$(':checkbox:checked').each(function() {
obj[$(this).next('label').text()] = this.value;
});
-- 2021 Update --
You can now simplify the map() call using an ES6 arrow function. In addition you could combine the checkbox value and label text in to an array of objects, like this:
$(':checkbox').on('change', () => {
let labelValues = $(':checkbox:checked').map((i, el) => ({
value: el.value,
text: el.nextElementSibling.textContent
})).get();
console.log(labelValues);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="checkbox[]" value="1" /><label>text1</label>
<input type="checkbox" name="checkbox[]" value="2" /><label>text2</label>
<input type="checkbox" name="checkbox[]" value="3" /><label>text3</label>
<input type="checkbox" name="checkbox[]" value="4" /><label>text4</label>
#Rory's answers is good to return both value and text into a single array. But as the OP is asking to return value and text into separate arrays, I would propose the following way to do that.
All you have to do is to use 2 arrays to get separate values from text.
Working JSFiddle here.
Run the below snippet to see the output in the console.
This example will return:
Selected checkbox Values in an array
Selected checkbox texts in an array
Selected checkbox in an array (In case if you want it)
var selectedCheckBoxValue = [];
var selectedCheckBoxText = [];
var selectedCheckBox = $(':checkbox:checked').map(function(i) {
selectedCheckBoxValue[i] = this.value;
selectedCheckBoxText[i] = $(this).next('label').text();
return this;
}).get();
//Selected Checkboxes Value in a seperate Array
console.log(selectedCheckBoxValue);
//Selected Checkboxes Text in a seperate Array
console.log(selectedCheckBoxText);
//Selected Checkboxes element in a seperate Array
console.log(selectedCheckBox);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="checkbox" name="checkbox[]" value="1" checked="true" />
<label>text1</label>
<input type="checkbox" name="checkbox[]" value="2" checked="true" />
<label>text2</label>
<input type="checkbox" name="checkbox[]" value="3" />
<label>text3</label>
<input type="checkbox" name="checkbox[]" value="4" checked="true" />
<label>text4</label>

validate array of checkbox using getElementById

I've got a bunch of checkboxes defined as an array:
<input type="checkbox" value="1" id="courseinfo[]">Content
<input type="checkbox" value="2" id="courseinfo[]">Reputation
<input type="checkbox" value="3" id="courseinfo[]">Duration
<input type="checkbox" value="4" id="courseinfo[]">Career
<input type="checkbox" value="5" id="courseinfo[]">Recommended
<input type="checkbox" value="6" id="courseinfo[]">Interests
<input type="checkbox" value="7" id="courseinfo[]">Other
I am trying to see if the last one (value=7) is checked, I tried:
q2 = document.getElementById("courseinfo[6]").value;
That doesn't seem to work.
How can I access the 7th one in the array and then check if its been checked?
I want to use pure javascript.
You don't have id attribute in your checkbox collection. I think you're meaning name attribute. Use getElementsByName to get elements to NodeList. Then get 6th element's value.
q2 = document.getElementsByName("facilities")[6].value;
Use this to check if checkbox is checked:
if(q2.checked) {
alert('You have checked the 6th checkbox!');
}
document.getElementById is used to get elements from their attribute id="".
What you need here is getElementsByTagName
var elems = document.getElementsByTagName('input');
if (elems[elems .length-1].checked) {
// do stuff
}

Get proper checkbox value using form.serialize

We are currently using $('form').serialize() to get all form information
This will return any checkbox values as "On" or "Off".
Is there any way to get a 1/0 or true/false value using this same method?
Yes. You can do it by adding a hidden input with the same name as checkbox which value will be submitted if checkbox is unchecked:
<input type="hidden" name="option" value="false"/>
<input type="checkbox" name="option" value="true"/>
It will submit both values if checkbox is checked. But server side will read the latest one (value of checkbox)
The value of a form control is always a string. You can use radio buttons to get different values for the same control name:
<form ...>
<input type="radio" name="whatever" value="true">true
<br>
<input type="radio" name="whatever" value="false">false
...
</form>
Only one can be checked, and only the checked name/value will be sent to the server.
If we have multiple checkboxed in our page like :
<input id="reminder" name="Check1" value="false" type="checkbox" />
<input id="alarm" name="Check2" value="false" type="checkbox" />
we have to bind the change event of these checkboxes and set its value to true or false.
$('input[type=checkbox]').on('change', function(){
var name = $(this).attr('name');
if($(this).is(':checked')){
$('input[name= "' +name +'"]').val(true);
$(this).val(true);
}
else{
$(this).val(false);
$('input[name= "' +name +'"]').val(false);
}
});
By default, checkbox value doesn't appear in $('form').serializeArray(), It appears when it is checked.
We have to keep one hidden field for each checkbox like :
<input type="hidden" value="false" name="Check1" />
<input type="hidden" value="false" name="Check2" />
Now when we serialize the form now, we get the correct value like :
Check1=true
Check2=false
<input type="checkbox" name="check1" value="true" id="check1">
just set the value
You can add a new class for check boxes and set value when clicked.
<input class="checkbox" id="someId" type="checkbox" value="false" />Checkbox
And use a small JQuery helper
$('.checkbox').click(function () {
$(this).val() == "false" ? $(this).val("true") : $(this).val("false");
});
Then you will be able to get the value of the check box or serialize a form.

JS / JQuery - Trouble with getting checkbox values

I have many checkboxes in a dynamically produced (ASP) photo gallery. Each checkbox has the name 'photos' and contains a photo ID in the value, like this:
<form name="selectForm" id="selectForm">
<input type="checkbox" onclick="selectPhoto(<%=rs1.Fields("photoID")%>)" id="checkbox_<%=rs1.Fields("photoID")%>" class="photos" name="photos" value="<%=rs1.Fields("photoID")%>">
</form>
Without submitting a form, when the user clicks the checkbox, I need to create a comma (,) separated list of all the checked values for the checkbox named 'photos'. So this is what I tested but it alerts 'undefined'! The ASP is correct, for those not familiar with it.
function selectPhoto(id) {
... other stuff that uses id ...
var allValues = document.selectForm.photos.value;
alert(allValues);
}
But as I said above, this returns 'undefined' and I can work out why. When a user selects a photo, I simply need to display a list of all the photo ID's that have been clicked e.g. 1283,1284,1285,1286...
Any ideas what I am doing wrong here? Or is there another way to achieve this?
Try this:
var allValues = [];
$('input.photos').each(function(){
allValues.push($(this).val());
});
alert(allValues.join(','));
I believe that the problem comes from the fact that "document.selectForm.photos" is not an input but an array. I have some code for you that worked:
<script>
function selectPhoto(id) {
var allCheckbox = document.selectForm.photos;
var allValues = []
for (var i=0; i<allCheckbox.length; i++){
if (allCheckbox[i].checked){
allValues.push(allCheckbox[i].value)
}
}
alert( allValues.join(',') )
}
</script>
<form name="selectForm" id="selectForm">
<input type="checkbox" onclick="selectPhoto(1)" id="checkbox_1" class="photos" name="photos" value="1">
<input type="checkbox" onclick="selectPhoto(2)" id="checkbox_2" class="photos" name="photos" value="2">
<input type="checkbox" onclick="selectPhoto(3)" id="checkbox_3" class="photos" name="photos" value="3">
<input type="checkbox" onclick="selectPhoto(4)" id="checkbox_4" class="photos" name="photos" value="4">
<input type="checkbox" onclick="selectPhoto(5)" id="checkbox_5" class="photos" name="photos" value="5">
</form>

Categories