Robert E
Robert E

Reputation: 740

Clear specific form elements when checkbox is unchecked

Can anyone give me a basic example of how to clear specific form inputs (each with it's own unique ID) when a checkbox is unchecked? I've tried a handful of solutions but just can't quite seem to get this working reliably. I need this to only happen when the box is unchecked, which seems to be giving me issues.

Upvotes: 1

Views: 4051

Answers (4)

FosterZ
FosterZ

Reputation: 3911

​$(document).ready(function(){
    $('#chk').live('change',function(){
     if(!$(this).is(':checked'))
       $('input').val('');              
    });
})​;​

here is the working fiddle JSFiddle

Upvotes: 1

nachito
nachito

Reputation: 7035

Very simple example, to get you started. Uses jQuery 1.7.1. http://jsfiddle.net/fPKX8/

HTML:

<input id="in1" name="in1" value="pizza" /><br />
<input id="in2" name="in2" value="chips" /><br />
<input id="in3" name="in3" value="beer" /><br />

<input id="check1" name="check1" type="checkbox" />

jQuery:

$('#check1').on('click', function () {
    if (!$(this).is(':checked')) {
        $('#in1, #in2').val('');
    }
});

Upvotes: 1

solarise
solarise

Reputation: 453

A rough example might be...

<input type='checkbox' id='clear_text' />
<input type='text' id='text_box' value='Contents' />
<script>
$(function(){
    $("#clear_text").click(function(){
        if(!$(this).is(":checked")){ //checks if the checkbox/this is selected or not
            $("#text_box").val(""); //empty the input value
        } else { } //nothing
    });
});
</script>

Upvotes: 2

James Fu
James Fu

Reputation: 496

In the checkbox's onClick(), investigate the checkbox's value, then perform whatever action you wish, including clearing the forms. Does this meet your need?

Upvotes: 1

Related Questions