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
Related
I'm trying to make it where the user can only select 1 checkbox at a time on a page.
Here's my code so far:
function onlyOne(checkbox) {
var checkboxes = document.getElementsByName('active', 'inactive',
'showall')
checkboxes.forEach((item) => {
if (item !== checkbox) item.checked = false
})
}
<strong>Active</strong>
<input type="checkbox" name="active" value="Yes" onclick="onlyOne(this)">
<strong>Inactive</strong>
<input type="checkbox" name="inactive" value="Yes" onclick="onlyOne(this)">
<strong>Show All</strong>
<input type="checkbox" name="showall" value="Yes" onclick="onlyOne(this)">
What keeps happening is it will work sometimes and sometimes they can select more than 1 checkbox. What do I need to tweak to get it working all the time.
HTML DOM getElementsByName() Method Gets all elements with the specified name
So In your code It's getting only the first name active ;
as a result the length of the list of checkboxs is 1 this is why your code doesn't work correctly.
If you want to make sure that what i am saying is true change your code to this and your logic will work just fine:
function onlyOne(checkbox) {
var checkboxes = document.getElementsByName('active');
checkboxes.forEach((item) => {
if (item !== checkbox)
item.checked = false;
})
}
<strong>Active</strong>
<input type="checkbox" name="active" value="Yes" onclick="onlyOne(this)">
<strong>Inactive</strong>
<input type="checkbox" name="active" value="Yes"
onclick="onlyOne(this)">
<strong>Show All</strong>
<input type="checkbox" name="active" value="Yes" onclick="onlyOne(this)">
As the others recommended use the radio buttons it's much easier I just wanted to clear this for you.
EDIT :
If you still want to use checkbox use querySelectorAll instead of your getElementsByName
var checkboxes = document.querySelectorAll('[name="active"], [name="inactive"], [name="showall"]');
You can use radio buttons to do this, it needs no JavaScript and is supported by pretty much everything, Internet Explorer included. They can be used like so:
<div>
<strong>Active</strong>
<input type="radio" name="select" id="active" checked> <!-- Checked means that it is initially selected -->
</div>
<div>
<strong>Inactive</strong>
<input type="radio" name="select" id="inactive">
</div>
<div>
<strong>Show All</strong>
<input type="radio" name="select" id="showall">
</div>
Notice how because they are all technically the same input, they all have to have the same name, but you can instead use IDs to tell between them if you really need to.
Using radio buttons would be the preferred choice. But if you do want to use checkboxes, you can use the following approach.
<strong>Active</strong>
<input type="checkbox" name="chkbox" value="Yes" onclick="onlyOne(this)">
<strong>Inactive</strong>
<input type="checkbox" name="chkbox" value="Yes"
onclick="onlyOne(this)">
<strong>Show All</strong>
<input type="checkbox" name="chkbox" value="Yes" onclick="onlyOne(this)">
<script>
function onlyOne(checkbox) {
var checkboxes = document.getElementsByName('chkbox')
checkboxes.forEach((item) => {
item.checked = false
})
checkbox.checked = true
}
</script>
Note that the name attribute for all the input fields are the same.
getElementsByName() only takes one argument. The other arguments you're giving are being ignores, so you're only processing the active checkbox.
Give all your checkboxes the same class, and use getElementsByClassName() instead.
function onlyOne(checkbox) {
var checkboxes = Array.from(document.getElementsByClassName('radio'))
checkboxes.forEach((item) => {
if (item !== checkbox) item.checked = false
})
}
<strong>Active</strong>
<input type="checkbox" name="active" value="Yes" class="radio" onclick="onlyOne(this)">
<strong>Inactive</strong>
<input type="checkbox" name="inactive" value="Yes" class="radio" onclick="onlyOne(this)">
<strong>Show All</strong>
<input type="checkbox" name="showall" value="Yes" class="radio" onclick="onlyOne(this)">
You are using getElementsByName incorrectly as you can only pass one name to it and it is not an Array so you can't forEach it.
You can use querySelectorAll to query by multiple names and use forEach from the Array prototype.
function onlyOne(checkbox) {
var checkboxes = document.querySelectorAll('[name=active],[name=inactive],[name=showall]')
Array.prototype.forEach.call(checkboxes, (item,i) => {
if (item !== checkbox) item.checked = false
})
}
<strong>Active</strong>
<input type="checkbox" name="active" value="Yes" onclick="onlyOne(this)">
<strong>Inactive</strong>
<input type="checkbox" name="inactive" value="Yes"
onclick="onlyOne(this)">
<strong>Show All</strong>
<input type="checkbox" name="showall" value="Yes" onclick="onlyOne(this)">
While using a radio button control might be the way to go, that just really a comment and not an answer.
I want to show the total number of checkboxes that user has selected on the page. Here is my code.
<input type="checkbox" name="fruit" />A
<input type="checkbox" name="fruit" />B
<input type="checkbox" name="fruit" />C
<p>Total Number of Items Selected = <p>
Please provide the javascript code needed to achieve this. I know this has been asked before but i failed to benefit from those answers as they required me to edit the JS code to fit to my HTML, which i am not capable of at this point.
You could use .querySelectorAll() method to select all the elements you want to target then use length method that will return the number of cheched element like :
document.querySelectorAll('input[name="fruit"]:checked').length;
_______________________________________________^^^^^^^ //Used to select just checked inputs
NOTE: The use of name selector input[name="fruit"] target just the desired input's instead of all the document checkbox's.
Live example using jQuery :
$('input[name="fruit"]').click(function() {
console.log(document.querySelectorAll('input[name="fruit"]:checked').length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="fruit" />A
<input type="checkbox" name="fruit" />B
<input type="checkbox" name="fruit" />C
You can use a querySelector.
document.querySelectorAll("input:checked").length;
Note that this will select all checkboxes in the document. If you just want to refer to a certain group of checkboxes, give all the checkboxes in the group the same name and refer to them like this:
document.querySelectorAll("input[name='name']:checked").length;//replace 'name' with the name of the checkboxes
<input type="checkbox" name="fruit" />A
<input type="checkbox" name="fruit" />B
<input type="checkbox" name="fruit" />C
<p id="result">Total Number of Items Selected = <p>
<script>
showChecked();
function showChecked(){
document.getElementById("result").textContent = "Total Number of Items Selected = " + document.querySelectorAll("input:checked").length;
}
document.querySelectorAll("input[name=fruit]").forEach(i=>{
i.onclick = function(){
showChecked();
}
});
</script>
While you've requested a JavaScript solution, this can be achieved with CSS alone:
/* specifies the named counter that will be incremented by
each checked check-box: */
input[type=checkbox]:checked {
counter-increment: checked;
}
/* shows the counter in the '::after' pseudo-element of the
sibling <p> element: */
p::after {
content: ' ' counter(checked);
}
<input type="checkbox" name="fruit" />A
<input type="checkbox" name="fruit" />B
<input type="checkbox" name="fruit" />C
<p>Total Number of Items Selected =</p>
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);
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" />
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
}