Lahiru karunanayake
Lahiru karunanayake

Reputation: 29

Show/hide text box based on check box

i`m trying to make a textbox. when check box is checked text box should be shown.but when check box is unchecked text box should be remove.This is how i implement this so far.When i clikc on check box it is showing text box. now i want to know how to remove textbox when check box is unchecked

javascript as follow

<script type="text/javascript">
function addbox() {
document.getElementById('area').style.display = 'block';
}
</script>

HTML as follow

<input type="checkbox" id="myCheck"  onclick="addbox();" on>Add new item type

i want to show following form

<div class="row" id="area" style="display: none;" >
Something
</div>

Upvotes: 0

Views: 13520

Answers (5)

user2575725
user2575725

Reputation:

Just handled checked state of checkbox

#myCheck:not(:checked)+#area {
  display: none;
}
<input type="checkbox" id="myCheck" />Add new item type

<div class="row" id="area">
  Something
</div>

Upvotes: 0

breezy
breezy

Reputation: 1918

You could write something like this with jQuery. jsFiddle File // http://jsfiddle.net/breezy/5q2vm06a/

$('#area').hide();

function checkval() {

    if ($('#myCheck').is(':checked')) {
        alert('is checked');
        $('#area').show();
    } else {
        $('#area').hide();
    }

}

$(function () {
    checkval(); // this is launched on load
    $('#myCheck').click(function () {
        checkval(); // this is launched on checkbox click
    });

});

Upvotes: 0

user3024814
user3024814

Reputation: 246

Use jQuery toggle() or this JavaScript function (Source: http://www.dustindiaz.com/seven-togglers/)

document.getElementById("myCheck").addEventListener("click", function() {
    toggle('area');
});

function toggle(obj) {
    var el = document.getElementById(obj);
    el.style.display = (el.style.display != 'none' ? 'none' : '' );
}

@Richard Hamilton: I edited your fiddle: http://jsfiddle.net/5h7ynca0/1/

Upvotes: 1

Carlos Calla
Carlos Calla

Reputation: 6706

You can do it with CSS only, no JS needed at all, just get the right selector, in this case I used +:

#myCheck:checked + #area {
  display: block !important;
}
<input type="checkbox" id="myCheck" />
Add new item type

<div class="row" id="area" style="display: none;" >
Something
</div>

Upvotes: 1

Drummad
Drummad

Reputation: 722

Change your javascript function to this:

function addbox() {
    if (document.getElementById('myCheck').checked) {
        document.getElementById('area').style.display = 'block';
    } else {
        document.getElementById('area').style.display = 'none';
    }
}

Upvotes: 1

Related Questions