简体   繁体   中英

Dynamically add value in textbox on focus of the last created dynamic textbox using jquery

This code creates dynamic textboxes on focus to the last textbox with value 0 in all the textbox, I want to add dynamic values on the textbox that have been created dynamically

<html>
<head>
<script> src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"> </script>
<script>
$(document).ready(function(){

$( "input" ).on('focus' , addNew);

function addNew (){
    if($(this).is(':last')){
    $( this ).after( '<input type="text" value="0"/>' );
    $( "input" ).on('focus' , addNew);
    }
}
});
</script>
</head>
<body>
<script>

    var divBox1 = document.createElement("div");
    divBox1.style.height = "100%";
    divBox1.style.width = "200px";

    document.body.appendChild(divBox1)
    var input = document.createElement('input');
    divBox1.appendChild(input);

</script>
</body>
</html>

Few problems here:

<script>src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"> </script>

should have been

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"> </script>

The way you were identifying whether the targeted input is last , was not proper. Check the below updated snippet.

 var divBox1 = document.createElement("div"); divBox1.className = "ipHolder"; //adding a class to identify the container of input elements divBox1.style.height = "100%"; divBox1.style.width = "200px"; document.body.appendChild(divBox1) var input = document.createElement('input'); divBox1.appendChild(input); $(document).ready(function() { $("input").on('focus', addNew); function addNew() { var isLast = $(this).closest('.ipHolder').find('input').length - ($(this).index() + 1) == 0; //subtract the number of inputs present already with the index of clicked input //within in the container for inputs and see if it is 0 which means its the last element if (isLast) { $(this).after('<input type="text" value="0"/>'); $("input").on('focus', addNew); } } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"> </script> 

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