How to store inputs from a textbox in array in Javascript - javascript

<!DOCTYPE html>
<html>
<head>
<form id="form1">
Beets:<input id="number1" type="integer" size = "5">
Artichokes: <input id="number2" type="integer" size = "5">
Carrots: <input id="number3" type="integer" size = "5">
</form>
<button id = "submitButton" onclick="RunApp()" > Submit</button>
<button id = "displayButton" onclick="getAllValues()" > Display</button>
<script>
var str = "";
function getAllValues() {
var input1, inputs;
input1 = document.getElementById("form1");
inputs = input1.elements["number1"].value;
for (i = 0; i < inputs.length; i++) {
str += inputs[i].value + " ";
}
alert(str);
}
function RunApp()
{
var beets, artichokes, carrots, input1, input2, input3;
// getting inputs into variables
input1 = document.getElementById("form1");
beets = input1.elements["number1"].value;
input2 = document.getElementById("form1");
artichokes = input1.elements["number2"].value;
input3 = document.getElementById("form1");
carrots = input1.elements["number3"].value;
if (beets == "" || carrots == "" || artichokes == "" || isNaN(beets) || isNaN(carrots) || isNaN(artichokes))
{
document.getElementById("demo").innerHTML+= "not valid" + "<br>";
document.getElementById("demo").innerHTML+= "--------------------------" + "<br>";
}
else
{
document.getElementById("demo").innerHTML+= "Beets = " + beets + "<br>"; document.getElementById("demo").innerHTML+= "Artichokes = " + artichokes + "<br>";
document.getElementById("demo").innerHTML+= "Carrots = " + carrots + "<br>";
}
}
</script>
<p id="demo"></p>
</head>
<body>
</body>
</html>
First, this is my first time learning JS.
So, I have a text-box, a submit button, and a display button. When I enter a number in the text-box, and click submit, it shows the number. I enter my second number and clicking the submit button shows me the second number. Then I click on the display button, it will shows the number 1 and number 2 in order. If I have more inputs in the text-box, the display button will show the entire list of all the inputs from the array.
Thank you!

Well, since it's your first time and you're learning I won't just give you the answer, but I'll point you in the right direction.
You want to attach a click event on the submit button to add the value to an array, and then print the array on click of the display button.

i think first you must google for this. I write something and you can improve this. I only want to give an example.
HTML:
<input type="text" id="inputbox">
<br/>
<button type="button" id="submit">Submit</button>
<button type="button" id="display">Display</button>
<br/>
<div id="screen"></div>
JS:
var inputArray = [];
var input = document.getElementById('inputbox');
var screen = document.getElementById('screen');
document.getElementById('submit').onclick = function () {
inputArray.push(input.value);
screen.innerHTML = input.value;
};
document.getElementById('display').onclick = function () {
screen.innerHTML = inputArray
};
http://jsfiddle.net/y9wL27y0/

Related

How to accept the input from a text box and display in array format in jQuery?

I have written the code of taking input value from a text box and adding it to an array using the add button and also displaying the values of the array when the display button is clicked.
The thing is I did all this using JavaScript and now I want to do it using jQuery. I tried a code snippet from this website but it's not working. Please help.
<body>
<script src="jquery-3.3.1.js"></script>
<input type="text" id="text1"></input>
<input type="button" id="button1" value="Add" onclick="add_element_to_array();"></input>
<input type="button" id="button2" value="Display" onclick="display_array();"></input>
<div id="Result"></div>
<script>
var x = 0;
var sample = []; // <-- Define sample variable here
function add_element_to_array(){
$(document).on('click', '#btnSubmit', function () {
var test = $("input[name*='i_name']");
$(test).each(function (i, item) {
sample.push($(item).val());
});
console.log(sample.join(", "));
});
}
function display_array() {
var e = "<hr/>";
for (var y = 0; y < sample.length; y++) {
e += "Element " + y + " = " + sample[y] + "<br/>";
}
document.getElementById("Result").innerHTML = e;
}
</script>
</body>
You can use this code to get idea of how it should work. You can also check for non-empty value before pushing the value into the array as an empty value in array will not make any sense.
$(document).ready(function(){
var valueArray = [];
//add value in array
$('#button1').click(function(){
var textValue = $('#text1').val();
//push non empty value only
if(textValue.trim() !== ''){
valueArray.push(textValue);
//reset the text value
$('#text1').val('');
}
});
//display value
$('#button2').click(function(){
$('#Result').html(valueArray.toString());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text1"></input>
<input type="button" id="button1" value="Add"></input>
<input type="button" id="button2" value="Display"></input>
<div id="Result"></div>
I have added the jquery script considering the following as your suggested html.
<input type="text" id="text1"></input>
<input type="button" id="button1" value="Add"></input>
<input type="button" id="button2" value="Display"></input>
<div id="Result"></div>
The inptArr must be a global array.
<script>
var inptArr = [];
$('#button1').on('click',function(){
if($('#text1').val() != '')
inptArr.push($('#text1').val());
});
$('#button2').on('click',function(){
var string = '';
var lastIndex = parseInt(inptArr.length - 1);
for(var i = 0; i <= lastIndex ; i++)
{
if(i == lastIndex)
string += inptArr[i];
else
string += inptArr[i] + ',';
}
$('#Result').append(string);
});
</script>
This is another way to achieve what you want with minor changes.
You have only one text input element so don't need any each loop.
document.ready() is needed if you define script from starting of the code because at starting there is no defined element that have an id as btnSubmit so this block must wait to dom elements to be ready.
Also you don't need pure javascript code getElementById on display_array() function when you use jquery. You can change it as $("#Result").html(e);
var x = 0;
var array = [];
$(document).ready(function(){
$('#btnSubmit').on('click', function () {
array.push($("#text1").val());
});
});
function display_array() {
var e = "<hr/>";
for (var y = 0; y < array.length; y++) {
e += "Element " + y + " = " + array[y] + "<br/>";
}
$("#Result").html(e);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text1"/>
<input type="button" id="btnSubmit" value="Add"/>
<input type="button" id="button2" value="Display" onclick="display_array();"/>
<div id="Result"></div>
In your code functions passed to onclick attributes are binding the click event to a DOM - don't do that.
var array = Array();
var input = $("#text1");
var result = $("#result");
function add_element_to_array(){
var value = input.val();
array.push(value);
console.log("Add:", value);
// input.val(""); // bonus: clears input after adding text to an array
}
function display_array() {
result.text(array.toString());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text1">
<input type="button" id="button1" value="Add" onclick="add_element_to_array();">
<input type="button" id="button2" value="Display" onclick="display_array();">
<div id="result"></div>

how to create an object with user input javascript

window.onload = Soldier;
function Soldier(allegiance,armor,weapon){
this.allegiance = allegiance;
this.armor = armor;
this.weapon = weapon;
}
document.getElementById("soldier").innerHTML =
var soldier1 = new Soldier("Theosis", true, "Sword");
alert(soldier1.allegiance);
<DOCTYPE HTML>
<html>
<head>
<script src = "objscript.js"> </script>
</head>
<body>
Allegiance: <input type ="text" id = "allegiance"><br/><br/>
Armor: <input type ="text" id = "armor"><br/><br/>
Weapon(s): <input type ="text" id = "weapon"><br/><br/>
<input type = "button" id="button" value = "Submit"><br/>
<p id = "soldier"> </p>
</body>
</html>
i know how to make objects but i dont know how to make the user input the data of the object and print onto the screen.
window.onload = submit;
function Soldier(allegiance,armor,weapon){
this.allegiance = "allegiance";
this.armor = armor;
this.weapon = weapon;
var soldier1 = document.getElementById("atext").value;
document.getElementById("soldier").innerHTML = " allegiance: " + soldier.allegiance + " <br/> " + " armor: " + soldier.armor + "</br>" + "Weapon(s): "+ soldier.weapon;
}
function submit(){
var submitButton = document.getElementById("button");
submitButton.onclick = Soldier;
}
<DOCTYPE HTML>
<html>
<head>
<script src = "objscript.js"> </script>
</head>
<body>
Allegiance: <input type ="text" id = "atext"><br/><br/>
Armor: <input type ="text" id = "armor"><br/><br/>
Weapon(s): <input type ="text" id = "weapon"><br/><br/>
<input type = "button" id="button" value = "Submit"><br/>
<p id = "soldier"> </p>
</body>
</html>
I dont think im allowed to use push. im just suppose to make new soldiers by the user typing it in. i made the code a little better. now just need it to actually print
The solution:
HTML
Allegiance: <input type ="text" id = "allegiance"><br/><br/>
Armor: <input type ="text" id = "armor"><br/><br/>
Weapon(s): <input type ="text" id = "weapon"><br/><br/>
<input type = "button" id="button" onclick="hire()" value = "Submit"><br/>
<p id="output"></p>
JS
var soldiers = [];
function Soldier(allegiance, armor, weapon){
this.allegiance = allegiance;
this.armor = armor;
this.weapon = weapon;
this.doReport = function () {
return this.armor + ' and ' + this.weapon;
}
}
function doReport() {
output = "";
for(var i = 0; i < soldiers.length; i++) {
output += (i + 1) + ") " + soldiers[i].doReport() + "; ";
}
document.getElementById("output").innerHTML = output;
}
function hire() {
var soldier = new Soldier(
document.getElementById("allegiance").value,
document.getElementById("armor").value,
document.getElementById("weapon").value
);
soldiers.push(soldier);
doReport();
}
I added function hire() and bound it with submit button. A new soldier object is being pushed into the list of soldiers. Also I added doReport() method to Soldier and common doReport() function which makes a general report of all soldiers in the list. Right now, I call doReport() in the end of each hire(), but you can do it by clicking on some another button for example.

How correctly check if input is not equal zero

I have simple code, in input user inputs number and it must print the numbers until the input is not equal to zero.
And the problem is when i submit value, page stops responding
Here is how my code looks like:
window.onload = function() {
var btn = document.getElementsByClassName('btn')[0];
function printInput() {
var output = document.getElementsByClassName('output')[0];
var input = document.getElementsByClassName('input')[0].value;
while(input !== 0) {
var input = document.getElementsByClassName('input')[0].value;
output.innerHTML += input+'<br>';
}
}
btn.addEventListener('click', printInput);
}
<input type="text" class="input" maxlength="1">
<button class="btn">Submit</button>
<div class="output"></div>
The value property of input is a string.
You must compare with the correct type:
while (input !== '0')
or
while (input != 0)
----- edit -----
Consider changing the while to an if, otherwise it will print any number different of 0 indefinitely.
window.onload = function() {
var btn = document.getElementsByClassName('btn')[0];
function printInput() {
var output = document.getElementsByClassName('output')[0];
var input = document.getElementsByClassName('input')[0].value;
if(input !== '0') {
var input = document.getElementsByClassName('input')[0].value;
output.innerHTML += input+'<br>';
}
}
btn.addEventListener('click', printInput);
}
<input type="text" class="input" maxlength="1">
<button class="btn">Submit</button>
<div class="output"></div>
You need to make two changes
Change type attribute from text to number
Change from while to if
Demo
window.onload = function()
{
var btn = document.getElementsByClassName('btn')[0];
function printInput()
{
var output = document.getElementsByClassName('output')[0];
var input = document.getElementsByClassName('input')[0].value;
if (input !== 0)
{
var input = document.getElementsByClassName('input')[0].value;
output.innerHTML += input + '<br>';
}
}
btn.addEventListener('click', printInput);
}
<input type="number" class="input" maxlength="1">
<button class="btn">Submit</button>
<div class="output"></div>

how to validate URL in dynamically added textbox

how to check URL is correct or not when i will enter into dynamically added textbox .
here t3 is given as id of input tag but that is works only for first dynamically added textbox not for others.
how to validate another URL present into next dynamically added textbox ?
<script type="text/javascript">
function GetDynamicTextBox(value){
return '<Label> Enter the URL : </label>' +
'<input name = "habits" type="text" id = "t3" value = "' + value + '" />' +
' <input type="button" value="Remove" onclick = "RemoveTextBox(this)" /><br><br>'
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var values = eval('<%=Values%>');
if (values != null) {
var html = "";
for (var i = 0; i < values.length; i++) {
html += "<div>" + GetDynamicTextBox(values[i]) + "</div>";
}
document.getElementById("TextBoxContainer").innerHTML = html;
}
}
window.onload = RecreateDynamicTextboxes;
</script>
<html>
<head>
<title>T-SUMM</title>
<script type="text/javascript">
function check()
{
if (document.getElementById('t1').value==""
|| document.getElementById('t1').value==undefined)
{
alert ("Please Enter a Query");
return false;
}
var regex = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/;
if(!regex .test(document.getElementById('t2').value)||!regex .test(document.getElementById('t3').value))
{
alert("Please enter valid URL.");
return false;
}
return true;
}
</script>
</head>
<body>
<center>
<form method="Post" action="./result.jsp">
<table>
<br><br><Label> Enter a Query : </label>
<input name='habits' id='t1'> <br><br>
<Label> Enter the URL : </label>
<input name='habits' id='t2'>
<input id="btnAdd" type="button" value="add another URL" onclick="AddTextBox()" /><br><br>
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<input type="submit" name="submit" onclick="return check();">
</table>
</form>
</body>
</html>
HTML - index.html
<html>
<head>
<title>T-SUMM</title>
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript">
function check()
{
if (document.getElementById('t1').value==""
|| document.getElementById('t1').value==undefined)
{
alert ("Please Enter a Query");
return false;
}
var regex = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/;
var boxes = document.getElementsByTagName('input');
for(i = 0; i < boxes.length; i++) {
if(boxes[i].type == "text" && boxes[i].className==="urls" && !regex.test(boxes[i].value)) {
alert("Please enter valid URL. Error in Text Box "+boxes[i].value);
return false;
}
}
return true;
}
</script>
</head>
<body>
<center>
<form method="Post" action="./result.jsp">
<table>
<br><br><Label> Enter a Query : </label>
<input name='habits' id='t1'> <br><br>
<Label> Enter the URL : </label>
<input name='habits' class="urls" id='t2'>
<input id="btnAdd" type="button" value="add another URL" onclick="AddTextBox()" /><br><br>
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<input type="submit" name="submit" onclick="return check();">
</table>
</form>
</body>
</html>
JS - script.js
function GetDynamicTextBox(value){
return '<Label> Enter the URL : </label>' +
'<input name = "habits" type="text" class="urls" value = "' + value + '" />' +
' <input type="button" value="Remove" onclick = "RemoveTextBox(this)" /><br><br>'
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var values = eval('<%=Values%>');
if (values != null) {
var html = "";
for (var i = 0; i < values.length; i++) {
html += "<div>" + GetDynamicTextBox(values[i]) + "</div>";
}
document.getElementById("TextBoxContainer").innerHTML = html;
}
}
window.onload = RecreateDynamicTextboxes;
I think you can first try to add an "onchange" handler to the "TextBoxContainer" div and user event.target or event.srcElement to identify whether it is a textbox that triggered the "onchange" event. If the trigger dom is exactly the ones you want, then you can try to validate its value and if it is not, you don't need to do anything. If this is done, then the rest things will be simply add/remove textboxes to the container element. Below are some sample codes that may help:
<script type="text/javascript">
var _container = document.getElementById('TextBoxContainer');
function add(){
var _txt = document.createElement("INPUT");
_txt.type = "text";
_container.appendChild(_txt);
}
_container.onchange = function(event){
var _dom = event.target || event.srcElement;
if(_dom && _dom.tagName === "INPUT" && _dom.type === "text"){
//alert(_dom.value);
//You can validate the dom value here
}
};
document.getElementById('add').onclick=function(){
add();
};
</script>

Assistance with using loops

Basically I'm trying to create a function in which it takes parameters, the times table required, and the values at which it should start and end. The function is to return a formatted string that can be displayed in the output area.
The rest of the code will get the three values from the textboxes and call the multiplication table function.
The return value will be displayed in a text area.
An example of what it should look like:
My JS currently looks like this:
function btnDisplay_onclick()
{
// get textboxes and assign to variables
var tableTextbox = document.getElementById("txtTable");
var startTextbox = document.getElementById("txtStart");
var finishTextbox = document.getElementById("txtFinish");
var outputTextbox = document.getElementById("txtOutput");
var table = tableTextbox.value;
var start = startTextbox.value;
var finish = finishTextbox.value;
var output = multiply(table, start, finish);
outputTextbox.value = output;
}
function multiply(table, start, finish)
{
for
}
the HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<!-- saved from url=(0014)about:internet -->
<title>Multiplication Table</title>
<script src="Lab6-MultTable.js"></script>
</head>
<body>
<form action=#>
<p><h1>Multiplication Table</h1></p>
<p>
Table Number:<input type="text" id="txtTable"><br>
Start Number:<input type="text" id="txtStart"><br>
Finish Number:<input type="text" id="txtFinish"><br>
</p>
<p>
<textarea id="txtOutput" rows="8" cols="20" readonly="readonly"></textarea>
</p>
<p>
<input type="button" value="Display Numbers" id="btnDisplay" onclick="btnDisplay_onclick()">
<input type="reset">
</p>
</form>
<noscript>This website requires JavaScript to be enabled.</noscript>
</body>
</html>
So basically I'm having trouble learning how to use Loops properly if someone would be willing to explain it to me as reading up on it I'm not able to fully understand it for whatever reason.
You could change the processing of the value a bit, like
var table = +tableTextbox.value || 0;
That converts the value to number and checks for a truthy value. If falsy, take zero as value.
For multiplication take the start and end value for the for loop and a variable for the result.
Calculate the value and add the line to the result, return the result.
function multiply(table, start, finish) {
var i, result = '';
for (i = start; i <= finish; i++) {
result += table + ' * ' + i + ' = ' + table * i + '\n';
}
return result;
}
function btnDisplay_onclick() {
// get textboxes and assign to variables
var tableTextbox = document.getElementById("txtTable");
var startTextbox = document.getElementById("txtStart");
var finishTextbox = document.getElementById("txtFinish");
var outputTextbox = document.getElementById("txtOutput");
var table = +tableTextbox.value || 0; // convert to number and
var start = +startTextbox.value || 0; // testfor truthynes or take
var finish = +finishTextbox.value || 0; // the default value of 0
var output = multiply(table, start, finish);
outputTextbox.value = output;
}
function multiply(table, start, finish) {
var i, result = '';
for (i = start; i <= finish; i++) {
result += table + ' * ' + i + ' = ' + table * i + '\n';
}
return result;
}
<form action="">
<p><h1>Multiplication Table</h1></p>
<p>
Table Number:<input type="text" id="txtTable"><br>
Start Number:<input type="text" id="txtStart"><br>
Finish Number:<input type="text" id="txtFinish"><br>
</p>
<p>
<textarea id="txtOutput" rows="8" cols="20" readonly="readonly"></textarea>
</p>
<p>
<input type="button" value="Display Numbers" id="btnDisplay" onclick="btnDisplay_onclick()">
<input type="reset">
</p>
</form>
Another way is write the result inside the loop at textarea.
$("#display").on("click", function(){
multiply();
});
function multiply(){
var table = document.getElementById("table").value
, start = document.getElementById("start").value
, finish = document.getElementById("finish").value
, text = document.getElementById("result");
text.value = '';
for ( var i = start ; i <= finish ; i++ ){
text.value += table + " * " + i + " = " + (table * i) + "\n";
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<div id="parameters">
Table number: <input id="table" type="number" />
<br/>
Start number: <input id="start" type"number" />
<br/>
Finish number: <input id="finish" type"number" />
<div>
<textarea id="result" rows="8" cols="20" readonly="readonly"></textarea>
</text>
<br/><br/>
<button id="display" /> Display numbers
<button type="reset" /> Reset
</form>

Categories

Resources