felix001
felix001

Reputation: 16711

Add and Remove an input box

Im trying to add and remove an input box based on when a box is ticked. However I seem to be having a few issues. One thin that Im unsure of is how I can link the $this (div) with additional attributes.

HTML:

<form>
    Lifetime Secs <input id="sec" type="checkbox" name="sec" value="sec" /> <br />
    Lifetime KBytes <input id="kb" type="checkbox" name="kb" value="kb" />
</form>

JavaScript:

$("#input1, #input2").click(function() {
    if ($("this:checked").length) {
        $(this).after('<input type="text" name="input" id="inputbox" />');
    } else {
        $('this input').remove();
    }
});

JSFiddle: http://jsfiddle.net/felix001/eA32C/22/

Thanks,

Upvotes: 0

Views: 130

Answers (4)

UncleZen
UncleZen

Reputation: 289

One way of accomplishing this can be found here: http://jsfiddle.net/eA32C/40/.

Upvotes: 0

Steve Ross
Steve Ross

Reputation: 1218

$("#sec,#kb").click(function() {
    $this = $(this);

if ( $this.attr('checked')) {

    $this.after('<input type="text" name="input" id="inputbox"  />');

} else {

    $('#inputbox').remove();

}
});

http://jsfiddle.net/eA32C/39/

Upvotes: 0

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

Couple of issues fixed.. See below,

$(function() {
    $('input:checkbox').change(function() {        
        if ($(this).is(':checked')) {
            $(this).after('<input type="text" name="input" id="inputbox"  />');
        } else {
            $(this).next('input').remove();
        }
    });
});

DEMO

Upvotes: 1

thecodeparadox
thecodeparadox

Reputation: 87073

$(function() {
  $('input:checkbox').on('change', function() {
    if ( this.checked ) {
        $(this).after('<input type="text" name="input" id="inputbox"  />');
    } else {
        $(this).next('input').remove();
    }
  });
});

Upvotes: 0

Related Questions