Reputation: 47
I want to create a dynamic array with data from the input. Later I want to write the collected data to the in div. How can I do that?
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<body>
<p>Click the button to add a new element to the array.</p>
<input type="text" id="data">
<button onclick="myFunction()">Try it</button>
<button onclick="myFunction2()">Add</button>
<p id="demo"></p>
<script>
var fruits = [];
function myFunction() {
var x=$("#data").val();
fruits.push(x);
$("#data").val("");
for(var i=0;i<fruits.length;i++) {
$("#demo").html(fruits[i]);
}
}
</script>
</body>
</html>
Upvotes: 1
Views: 372
Reputation: 494
I am not sure what are exactly trying to achieve but you need to set a criteria for the input e.g comma separated values.
Or split them on basis of a space character.
then do it the following way,
<script>
var fruits = [];
function myFunction() {
var x=$("#data").val().split(' '); // Use .split(',') if you want to split them on basic of a comma
$("#data").val("");
for(var i=0;i<x.length;i++) {
fruits.push(x[i]);
}
// Now you have the array containing the fruits, add them to DOM
$("#demo").html(fruits.join('<br/>')); // Single fruit per line
}
</script>
Upvotes: 1
Reputation: 67207
Try to append the htmlString. You are replacing it.
var htmlString = ""
for(var i=0;i<fruits.length;i++) {
htmlString += fruits[i];
}
$("#demo").html(htmlString);
And the full code would be,
<script>
var fruits = [];
function myFunction() {
var x=$("#data").val();
fruits.push(x);
$("#data").val("");
var htmlString = ""
for(var i=0;i<fruits.length;i++) {
htmlString += fruits[i];
}
$("#demo").html(htmlString);
}
</script>
And the perfect approach would be,
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<body>
<p>Click the button to add a new element to the array.</p>
<input type="text" id="data">
<button id="try">Try it</button>
<button>Add</button>
<p id="demo"></p>
<script>
var fruits = [];
var data = $("#data");
var demo = $("#demo");
$("#try").click(function(){
fruits.push(data.val());
data.val("");
demo.html(fruits.join(" "));
});
</script>
</body>
</html>
Upvotes: 1