I have 2 fields prefix and value. Suppose when I put prefix as A and value as 10, it should give me result A1 to A10. In my code it gives me result A1 to A10 but at start it appends value too. That means it gives 10A1 instead of only A1. Thank you. Sorry for grammar.
function saveForm(){
var val = document.getElementById("val").value;
var prefix = document.getElementById("prefix").value;
for(i=1; i<=parseInt(val); i++){
val += prefix + i + "<br>";
}
document.getElementById("demo").innerHTML = val;
}
<label>Prefix</label>
<input id="prefix" name="prefix" type="text" /><label>Value</label><input id="val" type="text" />
<button type="button" onClick="saveForm()" />Save</button>
<p id="demo"></p>
3 Answers 3
You are using the existing variable val which already has value hence value will be concatenated with previous value.
Use different variable which has be initialized as ''
function saveForm() {
var val = document.getElementById("val").value;
var prefix = document.getElementById("prefix").value;
var value = '';
for (var i = 1; i <= parseInt(val); i++) { //declare i using keyword "var" or else it will be global
value += prefix + i + "<br>";
}
document.getElementById("demo").innerHTML = value;
}
<label>Prefix</label><input id="prefix" name="prefix" type="text" /><label>Value</label><input id="val" type="text" />
<button type="button" onClick="saveForm()">Save</button>
<p id="demo"></p>
Comments
Try now. you just need to change the variable names.
function saveForm() {
resval = '';
var myval = document.getElementById("val").value;
var prefix = document.getElementById("prefix").value;
for (i = 1; i <= parseInt(myval); i++) {
resval += prefix + i + "<br>";
}
document.getElementById("demo").innerHTML = resval;
}
<body>
<label>Prefix</label><input id="prefix" name="prefix" type="text" /><label>Value</label><input id="val" type="text" />
<button type="button" onClick="saveForm()" />Save</button>
<p id="demo"></p>
</body>
Comments
Declare a new variable temp, assign inside for loop then show using innerHTML.
function saveForm(){
var val = document.getElementById("val").value;
var prefix = document.getElementById("prefix").value;
var temp = "";
for(i=1; i<=parseInt(val); i++){
temp += prefix + i + "<br>";
}
document.getElementById("demo").innerHTML = temp;
}