Javascript array dynamic population - javascript

I am brand new in WebDevelopment and I came across the following issue.
I have an html file where a textbox is defined as well as a "View all Contents" button
The user can enter a value in the textbox and submit the data
Then repeat this action multiple times
Every time a new value is entered this value should be stored to a
Javascript array
The user will be able to view the contents of the Javascript array
when clicking on the button "View all Contents".
So my problem is how these values are stored dynamically in Javascript and printed when the user is finished.
Your answer is very much appreciated.
Best Regards
Olga

A very trivial example: http://jsfiddle.net/pimvdb/unEMp/.
<input type="text" id="textbox">
<br>
<input type="button" id="add" value="Add">
<br>
<input type="button" id="view" value="View all Contents">
with:
var arr = []; // the array
document.getElementById('add').onclick = function() {
arr.push(document.getElementById('textbox').value); // add textbox value to array
document.getElementById('textbox').value = ''; // clear textbox value
};
document.getElementById('view').onclick = function() {
alert(arr.join(', ')); // alert array contents as a string; elements are delimited by ', '
};

First you'll want to create your array in the global scope - this means outside of a method body, somewhere in the <script></script> body:
var myArray = new Array();
Next, you'll want to append the array with a new value each time the user clicks a button:
function myButtonClick(){
var myTb = document.getElementById("textBox1");
myArray.push(myTb.value);
myTb.value = ""; // reset the textbox
}
Next, you'll want another button handler for the click on "View All":
function myViewAllButtonClick(){
// will create a string of myArray's values, seperated by new line character
var msg = myArray.join("\n");
// will show the user all of the values in a modal alert
alert(msg);
}
Your HTML might look like:
<input type="text" id="textBox1" />
<input type="button" id="button1" value="Add Value" onclick="myButtonClick();"/>
<input type="button" id="button2" value="Show All" onclick="myViewAllButtonClick();"/>
When you get the hang of things, you can get rid of the "Add Value" button all together and use:
<input type="text" id="textBox1" onchange="onTextChanged(this)"/>
With a handler like:
function onTextChanged(e){
if(e.value == "") return;
myArray.push(e.value);
e.value = "";
}
The onTextChanged handler will fire when the user changes text in the textbox (it won't fire though until the textbox loses focus, which may make it bad for this example, but still a good JS skill to learn/understand).
Happy coding - good luck!
B

JavaScript array could be dynamicaly changed:
var array = [];
function foo() {
array.push('foo');
}
function boo() {
array.push('boo');
}

i put together a small example: http://jsbin.com/izumeb/3
<p><input type="text" id="txt"></input><button onclick="addToAll();">add to selection</button></p>
<p><button onclick="showAll();">show all</button></p>
<p id="all"></p>
and JS
<script>
var values = [];
function addToAll() {
var txt = document.getElementById("txt");
values.push(txt.value);
txt.value = "";
}
function showAll() {
var all = document.getElementById("all");
var str = "";
for (var i=0;i<values.length;++i) {
str += values[i] + "<br/>";
}
all.innerHTML = str;
}
</script>

Related

How to read input box line by line in Javascript and return various values depending on input?

I am trying to create a function in Javascript which can read an input box line by line and return different values depending on the input.
For example, if someone enters several protein mutations on separate lines with the format Arg86Lys, I want the function to read the first three and last three letters to get Arg Lys. Then, if I have a value stored for Arg Lys (let's say 100), I want the output to be a textbox which prints out the value 100 (and prints out the rest of the values on separate lines).
I am stuck on how to read the input box value line by line, and only extract the first three and last three letters from each line. I also do not understand how I can store values (like Arg Lys = 100) and return said values when a certain input is found.
So far I have created a multiline textbox (in HTML) and tried to make a function that reads line by line:
<body>
<form action = "/cgi-bin/hello_get.cgi" method = "get">
Enter mutations on separate lines with format Arg86Lys
<br>
<textarea rows = "5" cols = "60" name = "description">
</textarea><br>
<input type = "submit" value = "submit" />
</form>
<script>
var lines = document.getElementById('textareaId').innerHTML.split('\n');
for(var i = 0;i < lines.length;i++){
\\
}
</script>
</body>
textarea is an input, so its value is going to be stored in its value property, and passed along with the form submission. Here is an answer I found that goes over how to intercept the submit event for the form:
Intercept a form submit in JavaScript and prevent normal submission
Once you've intercepted the form submission event, pull the value from the description input, and do with it what you want from there
let form = document.getElementById("form");
let data = {"Arg Lys":100}; // store data like this
form.addEventListener("submit",function(e){
e.preventDefault();
var lines = document.getElementById('textareaId').value.split('\n');
document.getElementById('textareaId').value = '';
for(var i = 0;i < lines.length;i++){
let val = lines[i].substring(0,3);
let lastval = lines[i].substring(lines[i].length - 3)
document.getElementById('textareaId').value += val+' '+lastval + ' - ' +data[val+' '+lastval]+'\n';
}
})
<body>
<form id="form" action = "/cgi-bin/hello_get.cgi" method = "get">
Enter mutations on separate lines with format Arg86Lys
<br>
<textarea id="textareaId" rows = "5" cols = "60" name = "description"></textarea><br>
<input type = "submit" value = "submit" />
</form>
</body>
Are you looking for something like that?

How to print random string from a selection of user form inputs javascript/jquery

var textEntered = function() {
var input = document.userNameForm.userInput.value;
if(input) {
document.getElementById("resultText").innerHTML += input + "<br>";
}
}
This is what I have so far and this obviously just prints out the user inputs onto the screen in a list. But I want to somehow store all these user inputs from the form I have in my HTML, (maybe in an array?) and maybe assign each to a number and use Math.floor(Math.random()) to print out a random result. (I'm just making a little/random site where you put in the names of your friends and it returns and prints a random name from the names that you give it, if that makes sense).
I'm a beginner just so you know
function textEntered() {
var inputs = [];
$('form input').each((i,e)=>inputs.push(e.value));
if (inputs) {
document.getElementById("resultText").innerHTML += inputs[Math.floor(Math.random()*inputs.length)] + "<br>";
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input value="Hello">
<input value="World">
<input value="from Stardust">
<button onclick="textEntered()">Submit Now!</button>
</form>
<div id="resultText">Submit it!
<br><br>
</div>
Is this essentially what you are looking for?

Delete button next to each array's value

I have a HTML-JavaScript script in which the user can insert data to a new array [] by using a form's text field and an insert button.
By pressing insert button, the user inserts the data typed into the array.
I have a function which prints all the values of the array into <p id="demo"></p> and runs itself every 100 milliseconds in order to be updated with the arrays values.
I also have a reset button to delete every array's value when clicked.
What I want to do is add a delete button next to each array's value in order to be easier for the user to delete the wrong value he inserted.
I am using this code to insert values and print them:
HTML:
<div align="center">
<form id="form1">
<input type="text" name="fname" id="fname" placeholder="Type here!">
</form>
<br>
<input type="button" id="Button Insert" onclick="myFunction()" value="Insert">
<input type="button" onclick="myFunction3()" value="Reset">
</div>
<p id="demo" align="center"></p>
JavaScript/JQuery:
var all_values =[];
function myFunction() {
var temp_val = $("#fname").val();
all_values.push(temp_val);
document.getElementById("form1").reset();
}
setInterval(function () {
$("#demo").html(all_values.join("<br>"));
}, 100);
function myFunction3() {
all_values.length = 0;
}
To be more specific I want something like these things: iOS example JSFiddle Example 1 JSFiddle Example 2.
Could you please help me? Thanks in advance.
I'd do it the other way around.
Remove setInterval as it's really bad way to do such things.
Remove white spaces from the id attribute (id="Button-Insert", not id="Button Insert")
Don't use onclick attributes. Instead, register click event handlers with jQuery
// caching is a good practice when you reffer to the same elements multiple times:
var all_values =[], demo = $("#demo"), form = $("#form1")[0], fname = $("#fname");
$('#Button-insert').click(function(){
var temp_val = fname.val();
all_values.push(temp_val);
// create delete button along with the value
demo.append('<p>'+temp_val+' <button value="'+temp_val+'" type="button" class="del-btn">Delete</button></p>');
form.reset();
});
$('#Button-reset').click(function(){
all_values = [];
demo.html('');
});
// event delegation for dynamic elements:
demo.on('click', '.del-btn', function(){
all_values.splice(all_values.indexOf($(this).val()), 1);
$(this).parent().remove();
});
JSFiddle
Simply create the delete buttons at the same time you create the table.
function loadvalues(){
var i, button;
$('#demo').empty();
for(i in all_values){
$('#demo').append(all_values[i]);
button = $('<button>',{'text':'Delete'}).click(function(){
all_values.splice(this,1);
loadvalues();
}.bind(i)).appendTo('#demo');
$('#demo').append('<br>');
}
}
Also you don't need to poll, you could simply add each one on demand with a function like this:
function addVal(){
var val = $("#fname").val(), i = all_values.length;
all_values.push(val);
$('#demo').append(val);
button = $('<button>',{'text':'Delete'}).click(function(){
all_values.splice(this,1);
loadvalues();
}.bind(i)).appendTo('#demo');
$('#demo').append('<br>');
}
I had some typos, the code works,
Check here:
http://codepen.io/anon/pen/QbvgpW

pass a variable name and evaluate it to that variable's value

I have a form with many buttons all of which print a value in the relevant textbox. the problem is the value is a fairly long text string and I would like to create a shorter variable eg. 'text' and make that variable equal to eg. 'some long sentence that I only want to type once'. any idea how I can edit this code to make this possible
function setInput(button, setValue) {
var buttonVal = button.value,
textbox = document.getElementById('input_' + buttonVal);
textbox.value = setValue;
<html>
<input type='submit' name='submit_a' value="a"
onclick="setInput(this,'make_me_a_variable'); return false;">
</html>
var textLookup = {
btnName1: "Long text",
btnName2: "Longer text"
};
// inside your function
var buttonText = ...,
inputText = textLookup[buttonText];
// do stuff with inputText;
Instead of defining the event handler in the HTML code, you could also create the event handler with javascript. You need to do that in another event handler for document.onload. When you do it earlier, the input HTML element might not have been parsed and created yet, so no event handler for it can be added.
<script>
// store your text in a variable
var inputText = 'make_me_a_variable';
// define some code which is executed when the page is loaded:
document.addEventListener("load",function(event){
// get the input by the id property I added to the HTML below.
var input = document.getElementById('submit_a');
// add an event handler for the click event (replaces the onclick HTML property)
input.addEventListener("click",function(event) {
setInput(this, inputText);
return false;
});
});
</script>
[...]
<input id="submit_a" type='submit' name='submit_a' value="a" >
You can create a variable and assign your long text to the variable and use it where ever you want.
Modified code
var longText = 'long text here'.
function setInput(button) {
var buttonVal = button.value,
textbox = document.getElementById('input_' + buttonVal);
textbox.value = longText ;
}
Html:
<input type='submit' name='submit_a' value="a"
onclick="setInput(this); return false;">

Add form input to array with javascript using unshift()

I am trying to add elements to an array via a form. I am using the unshift() method. The code below doesn't work and I would like to know why.
<form>
<input id="input"> </input>
<input type = "button" id="button"> Click me </input>
</form>
<script>
var input = document.getElementById("input").value;
var button = document.getElementById("button");
var myArray = [];
myArray.unshift(input);
button.onclick = function alerted (){
alert(myArray);
};
</script>
Your quoted code runs immediately when the page is loaded. The form field won't have anything in it then, so its value will be ''. When you alert that, the default toString operation on the array will result in '' and the alert will be blank.
You want to run your unshift code in response to a user event, such as the button being clicked, rather than right away. You can do that by setting input to be the element (remove .value from that line) and then moving your line with unshift into the function you're assigning to onclick, adding the .value there:
button.onclick = function alerted (){
myArray.unshift(input.value);
alert(myArray);
};
Other notes:
You never write </input>. Normally you don't close input tags at all. If you're writing XHTML (you probably aren't), you'd put the / within the main input tag like this: <input id="input" />. But again, you're probably not writing XHTML, just HTML.
The value (caption) of an input button goes in its value attribute, not content within opening and closing tags. (You would use opening and closing tags with the button element, not input.)
Taking all of that together, here's a minimalist update: Live copy | source
<form>
<input id="input"><!-- No ending tag -->
<input type = "button" id="button" value="Click me"><!-- No ending tag, move value where it should be -->
</form>
<script>
var input = document.getElementById("input"); // No .value here
var button = document.getElementById("button");
var myArray = [];
button.onclick = function alerted (){
myArray.unshift(input.value); // Moved this line, added the .value
alert(myArray);
};
</script>
DEMO
You need to a) get the value in the click and b) return false if you want the button to not submit. I changed to button. Alternative is <input type="button" value="click me" id="button" />
You may even want to empty and focus the field on click...
<form>
<input id="input" type="text"/>
<button id="button"> Click me </button>
</form>
<script>
var input = document.getElementById("input"); // save the object
var button = document.getElementById("button");
var myArray = [];
button.onclick = function alerted (){
myArray.unshift(input.value); // get the value
alert(myArray);
return false;
};
</script>​
You're not getting the new value in the onclick function.
Try this: http://jsfiddle.net/SeqWN/4/
var button = document.getElementById("button");
var i = document.getElementById("input");
var myArray = [];
button.onclick = function alerted (){
myArray.unshift(i.value);
alert(myArray);
};​

Categories