0

I have number of checkbox elements are there in my html page

<input type='checkbox' class='txtshow'checked="checked\" id='someid1' name='checkMr[]' value='some value' >
<input type='checkbox' class='txtshow'checked="checked\" id='someid2' name='checkMr[]' value='some value' >
<input type='checkbox' class='txtshow'checked="checked\" id='someid3' name='checkMr[]' value='some value' >
  1. what i want is whenever any of this is checked dynamically one element input type='checkbox' should be added to html page.
  2. if unchecked then remove the element which was added.
  3. same element should no be repeated.
3
  • i am new to javascript and jquery so could not try. please help me out ? Commented Oct 25, 2012 at 10:13
  • javascript is programming laguage and jquery is a framework of javascript ... then search in google to learn about javascript ... there are many tutorials, guides and cookbooks ... and because you asked how to remove and/or add elements you have to learn more about DOM (Document Object Model) ... if you prefer to do this with jquery search in jquery website for the documentation Commented Oct 25, 2012 at 10:18
  • I would suggest at least to learn the basics of javascript before using jQuery. Commented Oct 25, 2012 at 10:21

2 Answers 2

1

On the click event, check if the checkbox is checked. If it is, then add a checkbox, if it is not checked, then remove the checkbox. Use an id related to the parent to link them together:

$(".txtshow").click(function() {
    if ($(this).is(":checked")) {
        newCheck = $("<input type=checkbox id='" + $(this).attr("id") + "-child' />")
        $("body").append(newCheck);
    }
    else {
        $("#" + $(this).attr("id") + "-child").remove();
    }
});​

Fiddle: http://jsfiddle.net/nyZj6/6/

Sign up to request clarification or add additional context in comments.

2 Comments

What to do if i have to append this to form element?
Change the "body" to the selector to the selector to which you would like to append.
0

you can do this:

$( '.txtshow' ).change(function(){
    var id = $(this).attr( 'id' );
    if( $(this).is(':checked') ){
        $( '<p id="element_' + id + '"></p>' ).appendTo( $( 'body' ) ); 
    } else {
        $( '#element_' + id + ' ).remove(); 
    }
});  

Where in this case you create a p element with that custom id. You can change that attribute as you want.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.