I'm new to jQuery and JavaScript.
Managed to get the following code to work, adding a new text input field based on the number selected by the user from the (previous) dropdown selection field.
<script>
$(function() {
var input = $('<input placeholder="输入名称或标题..." type="text" required/>');
var newFields = $('');
$('#qty').bind('blur keyup change', function() {
var n = this.value || 0;
if (n + 1) {
if (n > newFields.length) {
addFields(n);
} else {
removeFields(n);
}
}
});
function addFields(n) {
for (i = newFields.length; i < n; i++) {
var newInput = input.clone();
newFields = newFields.add(newInput);
newInput.appendTo('#newFields');
}
}
function removeFields(n) {
var removeField = newFields.slice(n).remove();
newFields = newFields.not(removeField);
}
});
</script>
However, in <input placeholder="Enter subject or title..." type="text" required/>, I want to add two attributes for each added field/ parameter:
name="subject1", name="subject2"and so on, for each input fieldFor example, the output input label for the first field should be <input placeholder="Input subject or title..." type="text" name="subject1" required/>
<input> tag
For example, the output input label for the first field should be "Subject 1: <input placeholder="Input subject or title..." type="text" name="subject1" required/> ”How to implement this function?
This is a way to add topic title and name attributes.
You can do this using string concatenation, using the variable
i.$(function() { $('#qty').bind('blur keyup change', function() { var n = this.value || 0; createFields(n) }); function createFields(n) { $("#newFields").empty(); //清空字段列表 for (var i = 1; i <= n; i++) { var fieldWrapper = $('<div class="fieldwrapper"/>'); //创建包装器 var name = $("<p>主题 " + i + "</p>"); //创建主题标题 var input = $('<input name="Subject' + i + '" placeholder="输入名称或标题..." type="text" required />'); //创建输入框 fieldWrapper.append(name); //添加标题 fieldWrapper.append(input); //添加输入框 $("#newFields").append(fieldWrapper); //添加到列表中 } } });