简体   繁体   中英

Hi i'm having problem in removing input tag after adding. Problem is When I click on remove button Input tag

 $(function() { var scntDiv = $('#p_scents'); var i = $('#p_scents p').length + 1; $('#addScnt').on('click', function() { alert(i); $('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt_' + i +'" value="" placeholder="Input Value" /></label><span> <button id="remScnt">Remove</button><span></p>').appendTo(scntDiv); i++; return false; }); $('#remScnt').on('click', function() { alert(i); if( i > 2 ) { $(this).parent('p').remove(); i--; } return false; }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script> <div class="fragment_1223"> <button id="addScnt">Add Another Input Box</button> <div id="p_scents"> <p> <label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt" value="" placeholder="Input Value" /></label> </p> </div> </div>

Hi i'm having problem in removing input tag after adding. Problem is When I click on remove button Input tag

check the code in editor

use Event delegation model for dynamic element,

replace $('#remScnt').on('click', function() { with jQuery(document).on('click', '#remScnt', function() { and use parents instead of parent

 $(function() { var scntDiv = $('#p_scents'); var i = $('#p_scents p').length + 1; $('#addScnt').on('click', function() { alert(i); $('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt_' + i +'" value="" placeholder="Input Value" /></label><span> <button id="remScnt">Remove</button><span></p>').appendTo(scntDiv); i++; return false; }); jQuery(document).on('click', '#remScnt', function() { alert(i); if( i > 2 ) { $(this).parents('p').remove(); i--; } return false; }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script> <div class="fragment_1223"> <button id="addScnt">Add Another Input Box</button> <div id="p_scents"> <p> <label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt" value="" placeholder="Input Value" /></label> </p> </div> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM