Javascript get the value of checkbox if checked without button clicked

htmljavascriptjquery

javascript get the value of checkbox if checked without button clicked

I am struck in the middle of project, please help..

how to get the check box value from the class name or from by name or by id through alert so that the particular value I can pass…

I am sorry to ask..I am new the jquery and javascript..

This is my HTML …

<input type="checkbox" name='cbox' value="red" class="theClass"/>red
<input type="checkbox" name='cbox' value="green" class="theClass"/>green
<input type="checkbox" name='cbox' value="yer" class="theClass"/>yer
<input type="checkbox" name='cbox' value="asdasd" class="theClass"/>asdasd
<input type="checkbox" name='cbox' value="radgdfged" class="theClass"/>radgdfged
$(function(){

$('input[type=checkbox]').on('change', function() {
   alert($(this).val());
    console.log($(this).val());
});

});

I googled much …but every where onclick the button than only will get all checkbox values..
I am getting the values using the onclick button ….but the thing is getting the value without using the button…
My concern is getting the value if checkbox is checked..

eg: if i checked red , i should get alert 'red'…..

Best Solution

jQuery:

$('input[type=checkbox]').on('change', function() {
    console.log($(this).val());
});

Javascript:

var cbs = document.querySelectorAll('input[type=checkbox]');
for(var i = 0; i < cbs.length; i++) {
    cbs[i].addEventListener('change', function() {
        console.log(this.value);
    });
}

EDIT:

If you want the value only if the checkbox is checked.

jQuery:

$('input[type=checkbox]').on('change', function() {
    if($(this).is(':checked'))
        console.log($(this).val());
});

Javascript:

var cbs = document.querySelectorAll('input[type=checkbox]');
for(var i = 0; i < cbs.length; i++) {
    cbs[i].addEventListener('change', function() {
        if(this.checked)
            console.log(this.value);
    });
}

jsfiddle DEMO

P.s. for jQyery put your code inside:

$(function() {
    //code here
});