Reputation: 311
I would like to take a user entered string. Create an array from said string. Then take that array and display it as a 'ul'. The user entered string will be flower names separated by "&". I would also like to see if I could use an alert to notify the user that they basically did not type in a correctly formatted string.
here is what I have so far but Im confused at how to continue as well as how to implement an "alert".
html:
<form>
Enter flowers here: <input type="text" id="flower_string"><br>
<input type="button" value="Just Do It" onclick="FlowerArray()"><br>
</form>
<ul id="flower_results"></ul>
javascript:
//funtion will take user flower names seperated by "&" to create an array and display
function FlowerArray(){
var flower_string = document.getElementById("flower_string").value;
var flower_array = flower_string.split("&");
var i;
//for loop to display results to user
for(i = 0; i < flower_array.length; i++){
}
}
my for loop is not complete because im unsure how i can do this.
Upvotes: 0
Views: 123
Reputation: 193271
You can compose a string and the append it as innerHTML:
function FlowerArray() {
var flower_string = document.getElementById("flower_string").value;
var flower_array = flower_string.split("&");
var i, html = '';
//for loop to display results to user
html = flower_array.map(function(el) {
return '<li>' + el + '</li>';
}).join('');
document.getElementById('flower_results').innerHTML = html;
}
<form>
Enter flowers here:
<input type="text" id="flower_string">
<br>
<input type="button" value="Just Do It" onclick="FlowerArray()">
<br>
</form>
<ul id="flower_results"></ul>
Upvotes: 2
Reputation: 46331
You need to create <li>
elements and append them to the <ul>
.
See this snippet with comments:
//funtion will take user flower names seperated by "&" to create an array and display
function FlowerArray(){
var flower_string = document.getElementById("flower_string").value;
var flower_array = flower_string.split("&");
var i;
var results = document.getElementById('flower_results'); // <- get the UL element
//for loop to display results to user
for(i = 0; i < flower_array.length; i++){
var li = document.createElement('li'); // <- create a LI element
li.innerHTML = flower_array[i]; // <- set it's content
results.appendChild(li); // append it to the UL
}
}
<form>
Enter flowers here: <input type="text" id="flower_string"><br>
<input type="button" value="Just Do It" onclick="FlowerArray()"><br>
</form>
<ul id="flower_results"></ul>
Upvotes: 2