1 2 3 4 5 6 7 8 9 | < form id = "frm_numbers" method = "post" action = "anotherpage.php" > < label for = "tb_addinputs" >No. Inputs to Add: </ label > < input id = "tb_addinputs" type = "number" min = "1" max = "6" value = "1" /> < button id = "btn_addinputs" >Add Inputs</ button > < button id = "btn_sync" style = "display:none;" >Sync All To First</ button > < input type = "submit" value = "Upload" name = "submit" id = "submit" /> </ form > |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"> </script> < script > $(function(){ //Extend native from http://bit.ly/11MheU1 String.prototype.repeat = function(num) { return new Array(isNaN(num)? 1 : ++num).join(this); } //Add specific number of controls and show sync button $('#btn_addinputs').click(function(e){ e.preventDefault(); addNewTextInputs(); $('#btn_sync').show(); }); //general function to add text inputs function addNewTextInputs(){ var str = '< label >MyNumber</ label > '; str += '< input class = "tb_numbers" type = "number" value = "0" />'; str += '< button class = "btn_addten" >+10</ button > '; var numToAdd = parseInt($('#tb_addinputs').val()); $('#btn_sync').before(str.repeat(numToAdd)); } //sync button click to make all text inputs equal to the first one $('#btn_sync').click(function(e){ e.preventDefault(); if($('.tb_numbers').length > 1)$('.tb_numbers').val($('.tb_numbers').eq(0).val()); }); }); |
.click
event to the 'Add Ten' buttons, so that they can add 10 to the value in the associated number input. If the button was present on page load, then we could do this:
1 2 3 4 5 | $('.btn_addten').click(function(e){ e.preventDefault(); num = parseInt($(this).prev().val()) + 10; $(this).prev().val(num); }); |
.on()
method, which is no hardship:
1 2 3 4 5 | $("#frm_numbers").on("click", "btn_addten", function(e){ e.preventDefault(); num = parseInt($(this).prev().val()) + 10; $(this).prev().val(num); }); |
OK, you can argue that this isn't the most inspiring of scripts, but at least it shows how you can bind an event to a dynamically-added element.
Pretty helpful material, much thanks for this article!!!
ReplyDeleteGame keys
Your article for this website is a good effort. I like to appreciate you and your team.
ReplyDelete