Reputation: 3
I am not very good at jQuery, so I have a question; is there a quick way to code so when you click on a checkbox (equally to 1), there will appear a text box below.
I am currently learning jQuery, so this would be a great example.
Thanks in advance!
Upvotes: 0
Views: 2811
Reputation: 6115
$("#yourCheckboxId").change(function(){
if ($("#yourCheckboxId").is(":checked")){
$("#yourTextBoxId").show();
}
});
and if you want to hide the textbox when you turn the checkbox off its:
$("#yourCheckboxId").change(function(){
if ($("#yourCheckboxId").is(":checked")){
$("#yourTextBoxId").show();
}
else{
$("#yourTextBoxId").hide();
}
});
this is assuming you have a textbox in ur html that has a unique ID and also is hidden initially ("display:none") and that you have a checkbox with unique Id that is visible initially
Upvotes: 1
Reputation: 8318
Another way (http://jsfiddle.net/3r6nb/):
//html
<div>
<input id="check" type="checkbox"/>
<input id="text" type="text" class="hidden"/>
</div>
//css
.hidden
{
/*hides any element given this class, you may also want to set
display:none; as hidden elements still take up space*/
visibility:hidden;
}
.visible
{
visibility:visible;/*set display:inherit; if using display:none; above*/
}
//javascript
$("#check").change(function() {
//toggleClass() removes the class from the element if it
//exists or adds it if it doesn't
$("#text").toggleClass('hidden');
$("#text").toggleClass('visible');
});
Upvotes: 0
Reputation: 136104
If you wish to do this totally dynamically, you will want to make use of 2 methods.
You can determine if the checkbox has been checked, and if so add the textbox after it, or if it has been unchecked and the textbox already exists and if so remove it. This boils down to the code:
$('input[type=checkbox]').click(function(){
if($(this).is(':checked')){
var tb = $('<input type=text />');
$(this).after(tb) ;
}
else if($(this).siblings('input[type=text]').length>0){
$(this).siblings('input[type=text]').remove();
}
})
Live example: http://jsfiddle.net/KQ56P/
Upvotes: 0
Reputation: 3775
$('input:checkbox').change(function () {
if ( $(this).is(':checked') && !$(this).next().is('textarea') ) {
$(this).after( $('<textarea>') );
// OR $('<textarea>').insertAfter(this);
}
});
evan version shows an pre-existing version, mine creates it, you can combine both ;)
Upvotes: 0