This should be a pretty simple question. I'm just looking to input the variable "inputNumber" into the appending html snippet here. The inputNumber should increment every time it appends this html.
So basically I want the input name, id, and the div id to increment from 5 everytime "addMore" is clicked.
var inputNumber = 5;
$("#addMore").click(function() {
$("#input-names").append("<input type='text' id='name' + inputNumber++ name='name' + inputNumber++> <div class='delete-line' id='delete-' + inputNumber++><a href='JavaScript:void(0);'>X</a></div><br>");
});
You simply didn't terminate the string before inserting the variable.
var inputNumber = 5;
$("#addMore").click(function() {
inputNumber++;
$("#input-names").append("<input type='text' id='name"+ inputNumber +"' name='name"+ inputNumber +"' > <div class='delete-line' id='delete-"+ inputNumber +"'><a href='JavaScript:void(0);'>X</a></div><br>");
});
You can see by the syntax highlighting the difference in the code. You're IDE should have this feature too.
You were trying to use the increment operator (++) several times. This is also a problem as each time you call inputNumber++
the value is incremented. That means that in your code (with the quotes fixed), you were still incrementing the value by 3 because you called inputNumber++
3 times. I changed this behavior by calling inputNumber++
only once at the beginning of the click callback.
You might also want to think about improving your code's readability by using this syntax to create elements with attributes -
var inputElem = $('<input />', {
type: 'text',
id: 'name'+inputNumber,
name: 'name'+inputNumber
});
Call inputNumber++
once outside of the append otherwise you will be incrementing everytime it is stated inside the long string you are appending. Increment operators are self-assigning, which means they increment by 1 and assign to the value incremented all at once. The code equivalent of inputNumber = inputNumber + 1
$("#addMore").click(function() {
inputNumber++;
$("#input-names").append("<input type='text' id='name" + inputNumber + "' name='name" + inputNumber + "'> <div class='delete-line' id='delete-" + inputNumber + "'><a href='JavaScript:void(0);'>X</a></div><br>");
});
With the other way you had it, the resultant HTML for the first click would have been:
<input type='text' id='name6' name='name7' />
<div class='delete-line' id='delete8'>
<a href='javascript:void(0);'>X</a>
</div>
Also, ensure you string of text is concatenated correctly.
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.