'Generate a number of blocks according to an HTML input value using JQuery
I want to generate a number of blocks using JQuery. I try this code :
$(function() {
var input = $('<select name="contracts" id="contracts">\
<option value="default">-- Choose --</option>\
<option value="service">service</option>\
<option value="supply">supply</option>\
<option value="work">work</option>\
</select>\
<div>\
<label>start date</label>\
<input type="date" name="sdate" id="sdate">\
</div>\
<div>\
<label>end date</label>\
<input type="date" name="edate" id="edate">\
</div>');
var newFields = $('');
$('#nbr').bind('blur keyup change', function() {
var n = this.value;
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('#myForm');
}
}
function removeFields(n) {
var removeField = newFields.slice(n).remove();
newFields = newFields.not(removeField);
}
});
But It doesn't work correctly. This is my HTML code :
<label>Number Of Contracts</label>
<input type="number" name="nbr" id="nbr">
<form method="post">
<div id="myForm"></div>
<input type="submit" name="submit" value="Submit">
</form>
First It shows the number of divs I want but when I click anywhere it gives me the image below this is the image
Solution 1:[1]
try the one below, I have added a wrapper div and in the input variable and added a parseInt because n is evaluated as string.
$(function() {
var input = $('<div><select name="contracts" id="contracts">\
<option value="default">-- Choose --</option>\
<option value="service">service</option>\
<option value="supply">supply</option>\
<option value="work">work</option>\
</select>\
<div>\
<label>start date</label>\
<input type="date" name="sdate" id="sdate">\
</div>\
<div>\
<label>end date</label>\
<input type="date" name="edate" id="edate">\
</div></div>');
var newFields = $('');
$('#nbr').bind('blur keyup change', function() {
var n = parseInt(this.value);
if(isNaN(n)) {
n = 0;
}
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('#myForm');
}
}
function removeFields(n) {
var removeField = newFields.slice(n).remove();
newFields = newFields.not(removeField);
}
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kenneth Ong |
