How to Get the value of checked checkbox in javascript?

#1

Hi,

This is my Checkbox …

<li>
<input type="checkbox" id="scf1" value="Unmarried"/>
<label for="scf1">Unmarried</label>
</li>
<li>
<input type="checkbox" id="scf2" value="Divorced"/>
<label for="scf2">Divorced</label>
</li>
<li>
<input type="checkbox" id="scf3" value="Widowed" />
<label for="scf3">Widowed</label>
</li>
<li>
<input type="checkbox" id="scf4" value="Seperated"/>
<label for="scf4">Seperated</label>
</li>
</ul>
<a   onclick="funms()" class="list-view-more-btn">Search</a> 

and this one is javascript-ajax

function funms()
{
 var scf1=document.getElementById('scf1').value;
 var scf2=document.getElementById('scf2').value;
 var scf3=document.getElementById('scf3').value;
 var scf4=document.getElementById('scf4').value;
 //alert(scf1);

$.ajax({
***********************
});

}

So here i want to get only selected option values only …, in that above code will get all checkbox values if it is not selected also…,

kindly guide me…,

thanks,

#2

Hello !
Try this: scf1= $('#scf1').val();

#3

You need to get the .checked property. It will either be a boolean true or false. A web search would have given you this answer without waiting around for someone to reply in a forum.

1 Like
#4

You can do something like that:

var selectedValues = [],
    inputIds = ['scf1', 'scf2', 'scf3', 'scf4'];
inputIds.forEach(function (id) {
    var input = document.getElementById(id);
    if (input.checked)
        selectedValues.push(input.value);
});

selectedValues contains all the checked values.