Reputation: 4247
So I've got code that looks like this:
<input class="messageCheckbox" type="checkbox" value="3" name="mailId[]">
<input class="messageCheckbox" type="checkbox" value="1" name="mailId[]">
I just need Javascript to get the value of whatever checkbox is currently checked.
EDIT: To add, there will only be ONE checked box.
Upvotes: 283
Views: 1366858
Reputation: 19944
You may query the checkboxes by their name,
<input type="checkbox" value="1" name="checkboxName">
<input type="checkbox" value="2" name="checkboxName">
<input type="checkbox" value="3" name="checkboxName">
document.querySelector("input[name='checkboxName']:checked").value
Upvotes: 0
Reputation: 137
var checkedValue = document.getElementById("myCheck").checked;
checkedValue will be equal to 'true' or 'false'
Upvotes: 0
Reputation: 51
This would be a more simpler approach
const values = Array.from(document.querySelectorAll('[name="mailId[]"]:checked')).map((p) => p.value);
Upvotes: 0
Reputation: 8388
if you using after an event occurred you can use
const selected = event.target.checked; //true or false
An example would be if you want to track selected items, here is an example using react react-hook-form react material ui, it would be better than using value
from rendered field
that give wrong values
...
const [selectedQuestions, setSelectedQuestions] = useState(0);
const handleSelectedQuestions = (checked) => {
if (checked) {
setSelectedQuestions((prev) => prev + 1);
} else {
setSelectedQuestions((prev) => prev - 1);
}
};
<Controller
key={item.id}
control={control}
name={`question-${item.id}`}
defaultValue={false}
render={({ field: { onChange } }) => (
<Grid key={item.id} item xs={12}>
<QuestionCard
item={item}
handleOpen={handleOpen}
isLoading={isLoading}
isError={isError}
onChange={(event) => {
handleSelectedQuestions(event.target.checked);
onChange(event);
}}
/>
</Grid>
)}
/>
...
export default function QuestionsCard({ item, handleOpen, onChange }) {
return (
...
<FormControlLabel
control={
<Checkbox
// checked={value}
onChange={onChange}
sx={{
'& svg': {
fontSize: '1.266rem',
},
}}
/>
}
/>
)
}
Upvotes: 1
Reputation: 12757
You could use following ways via jQuery
or JavaScript
to check whether checkbox
is clicked.
$('.messageCheckbox').is(":checked"); // jQuery
document.getElementById(".messageCheckbox").checked //JavaScript
To obtain the value checked in jQuery:
$(".messageCheckbox").is(":checked").val();
Upvotes: 2
Reputation: 382
Surprised to see no working vanilla JavaScript solutions here (the top voted answer does not work when you follow best practices and use different IDs for each HTML element). However, this did the job for me:
Array.prototype.slice.call(document.querySelectorAll("[name='mailId']:checked"),0).map(function(v,i,a) {
return v.value;
});
Upvotes: 2
Reputation: 7948
pure javascript and modern browsers
// for boolean
document.querySelector(`#isDebugMode`).checked
// checked means specific values
document.querySelector(`#size:checked`)?.value ?? defaultSize
<form>
<input type="checkbox" id="isDebugMode"><br>
<input type="checkbox" value="3" id="size"><br>
<input type="submit">
</form>
<script>
document.querySelector(`form`).onsubmit = () => {
const isDebugMode = document.querySelector(`#isDebugMode`).checked
const defaultSize = "10"
const size = document.querySelector(`#size:checked`)?.value ?? defaultSize
// 👇 for defaultSize is undefined or null
// const size = document.querySelector(`#size:checked`)?.value
console.log({isDebugMode, size})
return false
}
</script>
Upvotes: 0
Reputation: 5615
None of the above worked for me but simply use this:
document.querySelector('.messageCheckbox').checked;
Upvotes: 378
Reputation: 812
In my project, I usually use this snippets:
var type[];
$("input[name='messageCheckbox']:checked").each(function (i) {
type[i] = $(this).val();
});
And it works well.
Upvotes: -7
Reputation: 331
If you want to get the values of all checkboxes using jQuery, this might help you. This will parse the list and depending on the desired result, you can execute other code. BTW, for this purpose, one does not need to name the input with brackets []. I left them off.
$(document).on("change", ".messageCheckbox", function(evnt){
var data = $(".messageCheckbox");
data.each(function(){
console.log(this.defaultValue, this.checked);
// Do something...
});
}); /* END LISTENER messageCheckbox */
Upvotes: 0
Reputation: 1512
None of the above worked for me without throwing errors in the console when the box wasn't checked so I did something along these lines instead (onclick and the checkbox function are only being used for demo purposes, in my use case it's part of a much bigger form submission function):
function checkbox() {
var checked = false;
if (document.querySelector('#opt1:checked')) {
checked = true;
}
document.getElementById('msg').innerText = checked;
}
<input type="checkbox" onclick="checkbox()" id="opt1"> <span id="msg">Click The Box</span>
Upvotes: 3
Reputation: 141
<input class="messageCheckbox" type="checkbox" onchange="getValue(this.value)" value="3" name="mailId[]">
<input class="messageCheckbox" type="checkbox" onchange="getValue(this.value)" value="1" name="mailId[]">
function getValue(value){
alert(value);
}
Upvotes: 5
Reputation: 2303
If you're using Semantic UI React, data
is passed as the second parameter to the onChange
event.
You can therefore access the checked
property as follows:
<Checkbox label="Conference" onChange={(e, d) => console.log(d.checked)} />
Upvotes: 0
Reputation: 20414
This does not directly answer the question, but may help future visitors.
If you want to have a variable always be the current state of the checkbox (rather than having to keep checking its state), you can modify the onchange
event to set that variable.
This can be done in the HTML:
<input class='messageCheckbox' type='checkbox' onchange='some_var=this.checked;'>
or with JavaScript:
cb = document.getElementsByClassName('messageCheckbox')[0]
cb.addEventListener('change', function(){some_var = this.checked})
Upvotes: 16
Reputation: 808
$(document).ready(function() {
var ckbox = $("input[name='ips']");
var chkId = '';
$('input').on('click', function() {
if (ckbox.is(':checked')) {
$("input[name='ips']:checked").each ( function() {
chkId = $(this).val() + ",";
chkId = chkId.slice(0, -1);
});
alert ( $(this).val() ); // return all values of checkboxes checked
alert(chkId); // return value of checkbox checked
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="checkbox" name="ips" value="12520">
<input type="checkbox" name="ips" value="12521">
<input type="checkbox" name="ips" value="12522">
Upvotes: 7
Reputation: 48793
For modern browsers:
var checkedValue = document.querySelector('.messageCheckbox:checked').value;
By using jQuery
:
var checkedValue = $('.messageCheckbox:checked').val();
Pure javascript without jQuery
:
var checkedValue = null;
var inputElements = document.getElementsByClassName('messageCheckbox');
for(var i=0; inputElements[i]; ++i){
if(inputElements[i].checked){
checkedValue = inputElements[i].value;
break;
}
}
Upvotes: 343
Reputation: 1731
I am using this in my code.Try this
var x=$("#checkbox").is(":checked");
If the checkbox is checked x
will be true otherwise it will be false.
Upvotes: 145
Reputation: 8939
in plain javascript:
function test() {
var cboxes = document.getElementsByName('mailId[]');
var len = cboxes.length;
for (var i=0; i<len; i++) {
alert(i + (cboxes[i].checked?' checked ':' unchecked ') + cboxes[i].value);
}
}
function selectOnlyOne(current_clicked) {
var cboxes = document.getElementsByName('mailId[]');
var len = cboxes.length;
for (var i=0; i<len; i++) {
cboxes[i].checked = (cboxes[i] == current);
}
}
Upvotes: 27
Reputation: 11148
Use this:
alert($(".messageCheckbox").is(":checked").val())
This assumes the checkboxes to check have the class "messageCheckbox", otherwise you would have to do a check if the input is the checkbox type, etc.
Upvotes: 5