9

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
);

3 Answers 3

21

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

Sign up to request clarification or add additional context in comments.

2 Comments

I want to put the value in var, How can I do that??
How can this be adapted to use multiple checkboxes to add and remove values from the #show div?
7

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('');
        }
    });
});

Comments

5

There is another way too:

  1. Using the new property method will return true or false.

    $('#checkboxid').prop('checked');

  2. Using javascript without libs

    document.getElementById('checkboxid').checked

  3. Using the JQuery's is()

    $("#checkboxid").is(':checked')

  4. Using attr to get checked

    $("#checkboxid").attr("checked")

i prefer second option.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.