validate array of checkbox using getElementById - javascript

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
}

Related

Check if any radio input is checked

if (document.querySelector("input[name='maca']")).getAttribute("checked")
<input type="radio" name="maca" id="maca1">
<input type="radio" name="maca" id="maca2">
I want to check if any one of the input type radio buttons with the same name is checked.
Select every radio button with that name with querySelectorAll, then use Array.some to check whether one of the items in the list is checked:
const radioButtons = document.querySelectorAll('input[name="maca"]')
const oneChecked = [...radioButtons].some(e => e.checked)
console.log(oneChecked)
<input type="radio" name="maca" id="maca1">
<input type="radio" name="maca" id="maca2" checked>
Alternatively, you can try selecting the checked radio button (with the :checked pseudo-class) and see if an element was selected:
if(document.querySelector('input[name="maca"]:checked')){
console.log('checked')
}
<input type="radio" name="maca" id="maca1">
<input type="radio" name="maca" id="maca2" checked>

get checkbox selected value

I have multiple checkboxes that get generated by a php code and the HTML looks like this:
<input name="checkbox" id="checkbox" value="firstBox" type="checkbox">
<input name="checkbox" id="checkbox" value="secondBox" type="checkbox">
However when I try to get the selected value by the user using below script
document.getElementById('checkbox').value
I always get 'firstBox' even when the secondBox is selected. Please help me solving this
IDs are identifiers for specific elements. Therefore, they must be unique.
An alternative is setting the same name and use the function querySelectorAll to get the checked checkboxes.
Use this selector to get the checked options: [name="checkbox"]:checked
document.querySelector('#check').addEventListener('click', function() {
var checked = Array.from(document.querySelectorAll('[name="checkbox"]:checked'));
checked.forEach(function(e) {
console.log(e.value);
});
});
<input name="checkbox" name="checkbox" value="firstBox" type="checkbox">
<input name="checkbox" name="checkbox" value="secondBox" type="checkbox">
<button id='check'>Check</button>
IDs must be unique.
<input name="checkbox" id="checkbox1" value="firstBox" type="checkbox">
<input name="checkbox" id="checkbox2" value="secondBox" type="checkbox">
Get value of first checkbox:
document.getElementById('checkbox1').value
Get value of second checkbox
document.getElementById('checkbox2').value

select checkbox by name and check if it checked javascript

I am trying to test if checkbox is checked.
I have more inputs and they have different names.
I managed to select the input but I can't seem to check if it wa selected. If I add to the condition '= true' it is checked once I load the page. If I leave it just .checked it doesn't do anything
Have I selected the input right? Please note I want to select it by name rather than id or class
Why is it that once the page loads my condition for if statement doesn't work?
<input type="checkbox" name="name1">
<input type="checkbox" name="name2">
<input type="checkbox" name="name3">
<input type="checkbox" name="name4">
const firstInput = document.getElementsByName('name1');
if (firstInput[0].checked) {
console.log('checked');
}
You are selecting element with name "1" but don`t have element with such name.
If you want to select all inputs which name attribute starts with "name":
const firstInput = document.querySelectorAll('[name^=name]')
You need to add attribute to that input. Attach an onclick listener and invoke
getAttribute
setAttribute
to manipulate 'checked' attribute;
<input type="checkbox" onclick="myFunction()" name="name1">
<input type="checkbox" onclick="myFunction()" name="name2">
<input type="checkbox" onclick="myFunction()" name="name3">
<input type="checkbox" onclick="myFunction()" name="name4">
function myFunction() {
var $element = document.getElementsByName('name1')[0];
var checked = $element.getAttribute('checked') === 'true';
$element.setAttribute('checked', !checked);
console.log($element.getAttribute('checked'));
}

As for all the tags input with the specified attribute to set, for example, attribute checked = false?

Put tags input type = "radio" with its attribute data-group:
<input type="radio" id="id1" data-group="group1">
<input type="radio" id="id2" data-group="group1"><br>
<input type="radio" id="id3" data-group="group2">
<input type="radio" id="id4" data-group="group2"><br>
How at all elements of input type="radio", which is data-group "group1", set the checked=false?
You can use the attribute selector:
$('input[type="radio"][data-group="group1"]').prop('checked', false);
Or filter():
$('input[type="radio"]').filter(function() {
return $(this).data('group') == 'group1';
}).prop('checked', false);
The best way to group radio buttons is to use the name attribute; the browser will then group them together for you, unchecking others when you check another member of the same group. That's the purpose of input[type=radio]:
<input type="radio" id="id1" name="group1">
<input type="radio" id="id2" name="group1"><br>
<input type="radio" id="id3" name="group2">
<input type="radio" id="id4" name="group2"><br>
And if you wanted to make all of the name="group1" ones unchecked, then:
$("input[type=radio][name=group1]").prop("checked", false);
But if you want to use your current structure, and you're asking how to set them all unchecked, then you can use an attribute selector:
$("input[type=radio][data-group=group1]").prop("checked", false);

Creating an Associative Array using JQuery

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

Categories