Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery get checkbox value if checked and remove value when unchecked

jQuery function to get checkbox value if checked and remove value if unchecked.

example here

<input type="checkbox" id="check" value="3" />hiiii

<div id="show"></div>

function displayVals(){
var check = $('#check:checked').val();
    $("#show").html(check);
}
var qqqq = window.setInterval( function(){
        displayVals()
    },
    10
);
like image 341
JS-Hero Avatar asked Jul 18 '13 07:07

JS-Hero


2 Answers

You don't need an interval, everytime someone changes the checkbox the change event is fired, and inside the event handler you can change the HTML of #show based on wether or not the checkbox was checked :

$('#check').on('change', function() {
    var val = this.checked ? this.value : '';
    $('#show').html(val);
});

FIDDLE

like image 183
adeneo Avatar answered Nov 15 '22 16:11

adeneo


Working Demo http://jsfiddle.net/cse_tushar/HvKmE/5/

js

$(document).ready(function(){
    $('#check').change(function(){
        if($(this).prop('checked') === true){
           $('#show').text($(this).attr('value'));
        }else{
             $('#show').text('');
        }
    });
});
like image 38
Tushar Gupta - curioustushar Avatar answered Nov 15 '22 16:11

Tushar Gupta - curioustushar