ondrej ondrej - 1 month ago 5
jQuery Question

Get numeric value only from form that has ids as array with JQuery?

I was searching for solution, but did not find any

I have this code:

<form name="frm_hs100">
<input id="hs100[1]" name="hs100[1]" type="checkbox">
<input id="hs100[2]" name="hs100[2]" type="checkbox">
</form>

$('[name^=hs100]').click(function() {
if ($(event.target).is(":checked")){
//true
}
else {
//false
}
console.log(event.target.id);
});


console.log prints "hs100[1]", but how do I get only #1 or #2 based on clicked checkbox?

Answer

Use classes and data-attributes

$('.my_box').on('click', function() {
    if ( this.checked ){
        //true
    } else {
        //false
    }
    console.log( $(this).data('value') );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="frm_hs100">
    <input id="hs100[1]" class="my_box" data-value="1" name="hs100[1]" type="checkbox">
    <input id="hs100[2]" class="my_box" data-value="2" name="hs100[2]" type="checkbox">
</form>

Comments