Reputation: 3803
I am using new jQuery and playing around with it using HTML.
I am trying for If else
events based on button click.
If a user clicks a button I am creating a checkbox and appending a button below.
And if the user clicks a button again I am removing the checkbox below the button and if he clicks again I append...
How do I implement this?
What I tried on button click:
$(document).on("click", "#button", function () {
CreateCheckBox();
$("#Test").toggle("hidden");
}
But it will not work as it will create a checkbox every time. What is best way to do this in jQuery?
Upvotes: 0
Views: 85
Reputation: 335
$("button").on('click',function(){
$('#checkbox').toggle();
if($('#checkbox').css("display") != "none"){
$('#checkbox').hide();
}
else
{
$('#checkbox').show();
}
});
it's not exactly what you're looking for, but it's a good alternative..
Upvotes: -1
Reputation: 10994
Try this
$(document).on('click', 'button', function () {
if ($(this).hasClass('create')) {
$('<div><input type="checkbox"><button>Delete</button></div>').appendTo('body');
// for jsfiddle test purposes I am creating the checkbox using jQuery and a button to delete
$(this).toggle(); // hides append button
} else {
$(this).parent().remove(); // removes the checkbox and delete button
$('.create').toggle(); //shows append button
}
});
Upvotes: 1
Reputation: 110
Here is an working example in Jsfiddle for you to look at. I hope it helps you out.
$("#my-button").click(function() {
if ( $('#checkbox-toggle').children().length > 0 ) {
$('div#checkbox-toggle').empty();
}else{
$('div#checkbox-toggle').append('<input type="checkbox" name="checkbox-name"> hello')
}
});
Upvotes: 1
Reputation: 4239
Just Change Your Code as below :
$(document).on("click", "#button", function () {
$("#CheckboxID").toggle();
});
You are forget to close " ) " as well as you have passed wrong argument in toggle() function.
Upvotes: 0