Loading user input into an array then display - javascript

Trying to get user input from HTML form and then get it into an array in javascript. Afterwards output it back into the div tag in HTML as a list.
The code works but it outputs the text twice instead of just once.
Example: user inputs orange in HTML form, then inputs apple, then banana
My code makes it output: orange, orange, apple, orange, apple, banana
It should just output: orange, apple, banana
// global variable
var enteredStringsArray = [];
function listArray() {
"use strict";
var form;
var enteredText;
var enteredString;
var index;
form = document.getElementById("lab06");
enteredText = form.text.value;
enteredStringsArray.push(enteredText);
enteredString = document.getElementById("theOrderedList");
for (index = 0; index < enteredStringsArray.length; index++) {
enteredString.innerHTML += "<li>" + enteredStringsArray[index] + " </li>";
}
return false;
}
<form id="list" action="#" onsubmit="return listArray();">
<label>Text:</label>
<input type="text" id="textId" name="text" />
<br/>
<input type="submit" name="runForm" value="submit" />
</form>
<div id="outputDiv" class="Output">
<ol id="theOrderedList"></ol>
</div>

replace
for (index = 0; index < enteredStringsArray.length; index++) {
enteredString.innerHTML += "<li>" + enteredStringsArray[index] + "
</li>";
}
from
enteredString.innerHTML += "<li>" + enteredText + "</li>";
it will work. Add each input items one by one. no need to loop it.

You can try without forloop, just create new li element and append in your ol
// global variable
var enteredStringsArray = [];
function lab06firstArrays() {
"use strict";
var enteredText;
enteredText = document.getElementById("textId").value;
enteredStringsArray.push(enteredText);
console.log(enteredStringsArray);
var ul = document.getElementById("theOrderedList");
var li = document.createElement("li");
li.appendChild(document.createTextNode(enteredText));
ul.appendChild(li);
document.getElementById("textId").value= "";
return false;
}
<form id="lab06" action="#" onsubmit="return lab06firstArrays();">
<label>Text:</label>
<input type="text" id="textId" name="text" />
<br/>
<input type="submit" name="runForm" value="submit" />
</form>
<br/>
<div id="outputDiv" class="Output">
<ol id="theOrderedList"></ol>
</div>
EDIT:
With forloop:
// global variable
var enteredStringsArray = [];
function lab06firstArrays() {
"use strict";
var enteredText;
enteredText = document.getElementById("textId").value;
enteredStringsArray.push(enteredText);
//console.log(enteredStringsArray);
var ul = document.getElementById("theOrderedList");
for (var i= enteredStringsArray.length - 1; i < enteredStringsArray.length; i++)
{
var li = document.createElement("li");
li.appendChild(document.createTextNode(enteredText));
ul.appendChild(li);
document.getElementById("textId").value= "";
}
return false;
}
<form id="lab06" action="#" onsubmit="return lab06firstArrays();">
<label>Text:</label>
<input type="text" id="textId" name="text" />
<br/>
<input type="submit" name="runForm" value="submit" />
</form>
<br/>
<div id="outputDiv" class="Output">
<ol id="theOrderedList"></ol>
</div>

Related

Writing single JS script for assigning ID's to output in HTML

I am creating a website that has a list of user inputs, however at a certain stage I want users to see a summarized page of all their inputs. If the input was not chosen it should not show as part of the summary (as in the script example below).
Here is my problem: there will be multiple user inputs and to write a JS script to achieve what I had done in an example script below will be lots of work and unfeasible. Is there a way the two JS scripts for the individual ID's can be combined into one as in the script below?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div>
<label>For the first test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test1" required>
</div>
<div>
<label>For the second test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test2" required>
</div>
<button id="myBtn">Test</button>
<div style="color:blue;">
<p id="result1"></p>
</div>
<div style="color:red">
<p id="result2"></p>
</div>
<script>
function getUserName() {
var test1 = document.getElementById('test1').value;
var result1 = document.getElementById('result1');
if (test1.length > 0) {
result1.textContent = 'Test1: ' + test1;
} else {
null;
}
}
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', getUserName, false);
</script>
<script>
function getUserName() {
var test2 = document.getElementById('test2').value;
var result2 = document.getElementById('result2');
if (test2.length > 0) {
result2.textContent = 'Test2: ' + test2;
} else {
null;
}
}
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', getUserName, false);
</script>
</body>
</html>
P.s. I would also like to know if a user were to press the test button with an input, remove the input and press the test button again, that the first input would be removed?
You can get all inputs and loop throw the result and create an dom element which will contain the value of the input
and each created element will be added to lets say a result element
See code snippet
function getUserName() {
var inputList = document.getElementsByTagName("INPUT");
var res = document.getElementById("result");
res.innerHTML = "";
var indx = 1;
for (i = 0; i < inputList.length; i++) {
if (inputList[i].value != "") {
var ele = document.createElement("p");
ele.innerHTML ="test " + indx + " : " + inputList[i].value
res.appendChild(ele);
indx++;
}
}
}
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', getUserName, false);
<div>
<label>For the first test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test1" required>
</div>
<div>
<label>For the second test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test2" required>
</div>
<button id="myBtn">Test</button>
<div id="result">
</div>

Javascript convert text to a link

I'm trying to make it so when a user inputs text in a textbox it prints it as a link that they are able to click on. Here is my code:
HTML:
<form>
<input type="text" id="urlhtml" size ="30" placeholder="http://www.sait.ca">
<br>
<br>
<input type="submit" value="Add Url" id="submit"onclick="getUrlList(); return false">
</form>
<br>
<h2> Your favorite urls are: </h2>
<a href target ="_blank" ><h3><span id="showurls"></span>
</h3></a>
JAVASCRIPT:
var urlList=[];
function getUrlList () {
var url={urlhtml};
var i=0;
var thisList="";
url.urlhtml=document.getElementById("urlhtml").value;
urlList.push(url);
for(i=0; i< urlList.length;i++)
{
var thisurl={urlhtml};
thisurl=urlList[i];
thisList+="http://" + thisurl.urlhtml;
thisList+="<br>";
}
document.getElementById("showurls").innerHTML=thisList;
}
The link gets displayed and you can click on it however it just opens up the same page and doesn't go to what the user inputted.
Any help would be really appreciated.
Just change code to this. You have to form a "a" attribute for each link.
var urlList = [];
function getUrlList() {
var url = {
urlhtml
};
var i = 0;
var thisList = "";
url.urlhtml = document.getElementById("urlhtml").value;
urlList.push(url);
for (i = 0; i < urlList.length; i++) {
thisList += "<a target='blank' href='http://" + urlList[i].urlhtml + "'>" + urlList[i].urlhtml + "</a><br>";
}
document.getElementById("showurls").innerHTML = thisList;
}
<form>
<input type="text" id="urlhtml" size="30" placeholder="http://www.sait.ca" value="www.google.com">
<br>
<br>
<input type="submit" value="Add Url" id="submit" onclick="getUrlList(); return false">
</form>
<br>
<h2> Your favorite urls are: </h2>
<a href target="_blank"><h3><span id="showurls"></span>
</h3></a>
change the for loop to
for(i=0; i< urlList.length;i++)
{
thisList+="<a href='http://" + urlList[i] + "'>" + urlList[i] + "</a><br>";
}
basically you were not forming anchor tags correctly

get required form elements via DOM in javascript

To do checking on required fields and a custom method of alerting users that required fields are missing, I'm trying to get an array of elements in a form, and have been hunting but not finding a good method.
Is there some variation of
document.getElementById(form).elements;
that would return all the required elements of an array, or a way to test if a given element is required... something akin to either
var my_elements = document.getElementById(form).required_elements;
or
var my_elements = document.getElementById(form).elements;
for (var this_element in my_elements){
if (this_element.attributes["required"] == "false"){
my_elements.splice(this_element, 1);
}
}
Try querySelectorAll with an attribute selector:
document.getElementById(form).querySelectorAll("[required]")
var requiredElements = document.getElementById("form").querySelectorAll("[required]"),
c = document.getElementById("check"),
o = document.getElementById("output");
c.addEventListener("click", function() {
var s = "";
for (var i = 0; i < requiredElements.length; i++) {
var e = requiredElements[i];
s += e.id + ": " + (e.value.length ? "Filled" : "Not Filled") + "<br>";
}
o.innerHTML = s;
});
[required] {
outline: 1px solid red;
}
<form id="form">
<input required type="text" id="text1" />
<input required type="text" id="text2" />
<input type="text" id="text3" />
<input type="text" id="text4" />
<input required type="text" id="text5" />
</form>
<br>
<button id="check">Check</button>
<br>
<div id="output">
Required inputs
</div>

Javascript: Labeling array results

Alright so here is my Html code:
<html>
<head>
<title>Planning</title>
<script type="text/javascript" src="Function.js"></script>
</head>
<body>
<form id="form">
<h1><b>Please enter data</b></h1>
<hr size="3"/>
<br>
<label for="Name">Name:</label> <input id="Name" type="text" />
<br>
<label for="Date">Date: </label><input id="Date" type="text" />
<br>
<label for="Plans">Plans: </label><input id="Plans" type="text" />
<br>
<br>
<input type="button" value="Save" onclick="insert();">
<input type="button" value="Show data" onclick="show();"> <br>
<h2><b>Data:</b></h2>
<hr>
</form>
<div id="display">
</div>
</body>
</html>
And my Javscript:
var Name=new Array();
var Date=new Array();
var Plans=new Array();
function insert(){
var NameValue = document.getElementById('Name').value;
var DateValue = document.getElementById('Date').value;
var PlansValue = document.getElementById('Plans').value;
Name[Name.length]=NameValue;
Date[Date.length]=DateValue;
Plans[Plans.length]=PlansValue;
}
function show() {
var content="<b>Your Plans For the Day:</b><br>";
var Namelabel ="<p>Name</p>"
for(var i = 0; i < Name.length; i++) {
+ Namelabel;
content +=Name[i]+"<br>";
}
for(var i = 0; i < Date.length; i++) {
content +=Date[i]+"<br>";
}
for(var i = 0; i < Plans.length; i++) {
content +=Plans[i]+"<br>";
}
document.getElementById('display').innerHTML = content;
}
The code on its own works fine but what I for the life of me can't figure out how to do is add a label identifying what the data showed is.
example being "Name:" for the displayed names and "dates:" appearing before the displayed dates.
I have other parts of the document I need to do in the meantime but this is really bothering me.
Change you show function to this
function show() {
var content="<b>Your Plans For the Day:</b><br>";
for(var i = 0; i < Name.length; i++) {
content += "Name " + Name[i]+"<br>";
}
for(var i = 0; i < Date.length; i++) {
content += "Date" + Date[i]+"<br>";
}
for(var i = 0; i < Plans.length; i++) {
content += "Plans" + Plans[i]+"<br>";
}
document.getElementById('display').innerHTML = content;
}

jQuery add ID increment to .html() appending on input onchange and refresh onchange value

I apologize for the wordy title but I haven't found a solution to my problem yet. I am a newbie with jQuery and web development so any guidance would be appreciated.
I have a <input> that allows user to enter a value (number) of how many rows of a set of input fields they want populated. Here's my example:
<div id="form">
<input id="num" name="num" type="text" />
</div>
<p> </p>
<div id="form2">
<form action="" method="post" class="form_main">
<div class="data">
<div class="item">
<input id="name" name="name[]" type="text" placeholder="name" /><br/>
<input id="age" name="age[]" type="text" placeholder="age" /><br/>
<input id="city" name="city[]" type="text" placeholder="city" /><br/>
<hr />
</div>
</div>
<button type="submit" name="submit">Submit</button>
</form>
My jQuery:
<script>
var itemNum = 1;
$("#num").on("change", function() {
var count = this.value;
var item = $(".item").parent().html();
//item.attr('id', 'item' + itemNum);
for(var i = 2; i <= count; i++) {
itemNum++;
$(".data").append(item);
}
})
</script>
I'm having problems adding an ID item+itemNum increment to <div class="item">... item.attr() didn't work. It doesn't append once I added that line of code.
Also, how can I get it so that once a user enters a number that populates rows of input fields, that if they change that number it will populate that exact number instead of adding to the already populated rows? Sorry if this doesn't make any sense. Please help!
Here is a DEMO
var itemNum = 1;
$("#num").on("change", function() {
$('.data div').slice(1).remove(); //code for removing previously populated elements.
var count = this.value;
console.log(count);
var item;
//item.attr('id', 'item' + itemNum);
var i;
for(i = 1; i <= count; i++) {
console.log(i);
item = $("#item0").clone().attr('id','item'+itemNum);
//prevent duplicated ID's
item.children('input[name="name[]"]').attr('id','name'+itemNum);
item.children('input[name="age[]"]').attr('id','age'+itemNum);
item.children('input[name="city[]"]').attr('id','city'+itemNum);
itemNum++;
$(".data").append(item);
}
})
Use clone() instead of html()
Try
var itemNum = 1,
item = $(".data .item").parent().html();;
$("#num").on("change", function () {
var count = +this.value;
if (itemNum < count) {
while (itemNum < count) {
itemNum++;
$(item).attr('id', 'item' + itemNum).appendTo('.data')
}
} else {
itemNum = count < 1 ? 1 : count;
$('.data .item').slice(itemNum).remove();
}
})
Demo: Fiddle

Categories