HTML Form input into Javascript array - javascript

My goal is to enter a single name into a html Text form. Each time I press submit
it will store that value into a javascript array. Currently, I am able to get
the first value I submit into the array but not the subsequent values. Hope I am
being clear enough, Any help would be great.
Here is my JavaScript
function getListOfNames() {
"use strict";
//Declare variables
var form;
var getNameValue;
var myArray = [];
var output;
//Assign values
output = document.getElementById("myTable");
form = document.getElementById("myForm");
getNameValue = form.getNameValue.value;
//Each time form is submited put the new value into array
myArray.push(getNameValue);
//output the results
output.innerHTML = myArray;
}
function project5Part2() {
"use strict";
// Your code goes in here.
getListOfNames();
return false;
}
Here is my HTML
<form id="myForm" action="#" onsubmit=" return project5Part2();" >
<label for="firstName">Enter Name</label>
<input type="text" id="enteredName" name="getNameValue"/>
<input type="submit" value="Enter Name" />
<input type="reset"  value="Clear form - DO NOT SEND" />
</form>

Remove the onsubmit from the form.
change the input type="submit" into a regular button and use the onclick to execute JavaScript.
<form id="myForm" action="#" >
<label for="firstName">Enter Name</label>
<input type="text" id="enteredName" name="getNameValue"/>
<button type="button" onclick="project5Part2();">Enter Name</button>
<input type="reset" value="Clear form - DO NOT SEND" />
</form>
Create or use a global array (cannot be enclosed in the method if you want to persist)
When the button is clicked, checked the value of the textbox and if not empty, add the value to the array.
var myArray = new Array();
function project5Part2() {
var name = document.getElementById('enteredName').value;
if (!(typeof name === 'undefined') && name!=null && name.trim()!='') {
myArray.push(name);
}
console.log(myArray);
document.getElementById('enteredName').value = '';
}
Will log the contents of the array each time the button is clicked.
For example: ["albert", "manny", "susan"]
The textbox value is being cleared each time the name is added.

Related

How to display rounded values in a form and show on focus the original values?

I have numeric values with many decimal places and the precision is required for other functions. I want to present the values in a form, so the user can change the values if necessary.
To increase the readability, I want to display the values rounded to 2 decimal places, but if the user clicks on an input field, the complete value should be presented. By doing this, the user can see the real value and adjust them better.
Example:
HTML
<button id="myBtn" onclick="fillForm()">Try it</button>
<form id="myForm" >
<fieldset>
<input type="text" id="myInput1" onchange="myFunction()" >
</fieldset>
</form>
JavasSript
<script>
//Example values that should be presented
var x = 3.14159265359;
function fillForm(){
document.getElementbyId("myInput1").value = x;
}
function myFunction(){
x = document.getElementbyId("myInput1");
}
</script>
The form input value should be " 3.14 " and if the user clicks in the field, the displayed value should be 3.14159265359.
Now the user can change the value and the new value has to be saved.
Because this is for a local 1 page website with no guaranty of internet connection, it would be an asset but not a requirement, to do it without an external script (jquery …).
you can use focus and blur event to mask/unmask you float, then simply store the original value in a data param, so you can use the same function to all input in your form ;)
function fillForm(inputId, val)
{
var element = document.querySelector('#'+inputId);
element.value = val;
mask(element);
}
function mask(element) {
element.setAttribute('data-unmasked',element.value);
element.value = parseFloat(element.value).toFixed(2);
}
function unmask(element) {
element.value = element.getAttribute('data-unmasked') || '';
}
<button onclick="fillForm('myInput1',3.156788)">Fill!</button>
<form id="myForm" >
<fieldset>
<input type="text" id="myInput1" onblur="mask(this)" onfocus="unmask(this)" >
</fieldset>
</form>
Edit: added "fillForm()" :)
Just use .toFixed(). It accepts one argument, an integer, and will display that many decimal points. Since Javascript primitives are immutable, your x variable will remain the same value. (also when getting/setting the value of an input use the .value property
function fillForm(){
document.getElementbyId("myInput1").value = x.toFixed(2);
}
If you need to save it you can store it in a new value
var displayX = x.toFixed(2)
Here is my solution. I hope you have other suggestions.
HTML
<form id="myForm" >
<fieldset>
<input type="text" id="myInput1" >
</fieldset>
</form>
<button id="myBtn" onclick="fill_form()">fill form</button>
JavasSript
<script>
var apple_pi = 10.574148541;
var id_form = document.getElementById("myForm");
//Event listener for form
id _form.addEventListener("focus", copy_input_placeh_to_val, true);
id _form.addEventListener("blur", round_input_2decimal, true);
id _form.addEventListener("change", copy_input_val_to_placeh, true);
// Replace input value with input placeholder value
function copy_input_placeh_to_val(event) {
event.target.value = event.target.placeholder;
}
// Rounds calling elemet value to 2 decimal places
function round_input_2decimal(event) {
var val = event.target.value
event.target.value = Number(val).toFixed(2);
}
// Replace input placeholder value with input value
function copy_input_val_to_placeh(event) {
event.target.placeholder = event.target.value;
}
// Fills input elements with value and placeholder value.
// While call of function input_id_str has to be a string ->
//fill_input_val_placeh("id", value) ;
function fill_input_val_placeh (input_id_str, val) {
var element_id = document.getElementById(input_id_str);
element_id.placeholder = val;
element_id.value = val.toFixed(2);
}
// Writes a value to a form input
function fill_form(){
fill_input_val_placeh("myInput1", apple_pi);
}
</script>
Here is an running example
https://www.w3schools.com/code/tryit.asp?filename=FLDAGSRT113G
Here is solution, I used focus and blur listeners without using jQuery.
I added an attribute to input named realData
document.getElementById("myInput1").addEventListener("focus", function() {
var realData = document.getElementById("myInput1").getAttribute("realData");
document.getElementById("myInput1").value = realData;
});
document.getElementById("myInput1").addEventListener("blur", function() {
var realData = Number(document.getElementById("myInput1").getAttribute("realData"));
document.getElementById("myInput1").value = realData.toFixed(2);
});
function fillForm(value) {
document.getElementById("myInput1").value = value.toFixed(2);
document.getElementById("myInput1").setAttribute("realData", value);
}
var x = 3.14159265359;
fillForm(x);
<button id="myBtn" onclick="fillForm()">Try it</button>
<form id="myForm" >
<fieldset>
<input type="text" id="myInput1" realData="" onchange="myFunction()" >
</fieldset>
</form>
jsfiddle : https://jsfiddle.net/mns0gp6L/1/
Actually there are some problems that needs to be fixed in your code:
You are redeclaring the x variable inside your myFunction function with var x =..., you just need to refer the already declared x without the var keyword.
Instead of using document.getElementById() in myFunction, pass this as a param in onchange="myFunction(this)" and get its value in the function.
Use parseFloat() to parse the value of your input to a float, and use .toFixed(2) to display it as 3.14.
This is the working code:
var x = 3.14159265359;
function fillForm() {
document.getElementById("myInput1").value = x.toFixed(2);
}
function myFunction(input) {
x = parseFloat(input.value);
}
To display the original number when you click on the input you need to use the onfocus event, take a look at the Demo.
Demo:
var x = 3.14159265359;
function fillForm() {
document.getElementById("myInput1").value = x.toFixed(2);
}
function focusIt(input){
input.value = x;
}
function myFunction(input) {
x = parseFloat(input.value);
}
<button id="myBtn" onclick="fillForm()">Try it</button>
<form id="myForm">
<fieldset>
<input type="text" id="myInput1" onchange="myFunction(this)" onfocus="focusIt(this)">
</fieldset>
</form>

Javascript function to show text if i input value

To the point, if i input value "20" in input field then show message "Thank you".
Here's my HTML Code:
<form method="post" action="">
<input type="text" id="nominal" value="">
<input type="submit" value="submit">
</form>
Here's my JS Code:
$(document).ready(function(){
var money = 20;
/* not sure if this is written correctly, but this is supposed to
check whether the hidden input element value is equal to var money */
if ($("input[id='nominal']").val() == money ) {
var h = document.createElement("H1") // Create a <h1> element
var t = document.createTextNode("Thank You"); // Create a text node
h.appendChild(t); // Append the text to <h1>
};
});
i've created one script to fulfill what I need, but not working! what's wrong?
My JDFIDDLE LINK
You have to create an event to listening for changes, in this case changed. And you can make your code a bit smaller too. ;)
$(function() {
$("#nominal").change(function() {
if( $(this).val() == 20 )
$(this).after("<h1>Thank You</h1>");
});
});
Full working exaple with removing the message when value changes again and strict check can be seen here.
$(document).ready(function(){
var money = 20;
$("#nominal").change(function() { // take change event of input box
if ($(this).val() == money ) { // use $(this) to take value
var h = document.createElement("H1"); // Create a <h1> element
var t = document.createTextNode("Thank You"); // Create a text node
h.appendChild(t);
$('form').append(h); // append created h1 element in form/html
} else {
$('form').find("h1").remove();
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form method="post" action="">
<input type="text" id="nominal" value="">
<input type="button" value="submit" name="submit" id="submit">
</form>

Convert Form data to JSON

<html>
<head></head>
<body>
<form name="abc" action="#" method="post">
Name: <input type="text" name="name"><br>
Age : <input type="text" age="name"><br>
<input type="submit"><br>
</form>
</body>
</html>
Can any one write this HTML code in such a way that when I will submit this form the the form data will be submitted in JSON format .
A pure JavaScript solution would be:
var form = document.getElementsByTagName('form')[0];
form.addEventListener('submit',function(event){
event.preventDefault();
var data = {
"name":this.name.value,
"age":this.age.value
};
console.log(data);
});
Try substituting name="age" for age="name" at second input type="text" , utilizing .serializeArray() , $.post()
$("form").submit(function(e) {
e.preventDefault();
var data = $(this).serializeArray();
console.log(data);
// $.post("/path/to/server", data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<form name="abc" action="#" method="post">
Name:
<input type="text" name="name">
<br>Age :
<input type="text" name="age">
<br>
<input type="submit">
<br>
</form>
check this function
var formDataToObject = function (formElm) {
var formObj = new FormData(formElm),
result = {},
values = formObj.values(),
keys = formObj.keys(),
key;
while (!(key = keys.next()).done) {
result[key.value] = values.next().value;
}
return result;
};
Two notes here:
1) No support for multiple select options, it will return the last selected option!!
2) The loop breaks when the next() return object with done equals to true,
but this object also contains the key for the last element in the form
which is in most cases the Submit Button, so if you don't have one in the form the last element will be excluded, easy to fix.

How can to show more than one form value in a alert?

I'm submitting a form which its deleting record.
It's a simple checkbox, if the user check the box then
that record will be deleted from the table , which works.
What I would like to do its have a alert box which shows
the name of the person(s) they are deleting before and then they confirm it which then it will be deleted.
Right now im using ajax to show the alert but its only showing the first record I check ,
It still deleting all the records but I would like it to show all all the names before the user confirm it.
How would I be able to accomplish this?
function sub_keys()
{
alert_string='Are you sure you want to delete ';
var con=confirm( alert_string + document.getElementById("name_id").value + '?');
if(con)
{
var formData = $("#confrm_key").serializeArray();
var URL = 'quality_time_delete_table2.cfc?method=getkeyDetail';
more code.....
}
form:
<input type="hidden" name="name_Id" id="name_id" value="#emp_namefirst# #emp_namelast# ">
You can add a class in your checkboxes and use js querySelectorAll and Array.prototype.map():
var text = document.querySelectorAll('.name');
var values = [].map.call(text, function(obj) {
return obj.innerHTML;
});
confirm(values);
<div class="name">test1</div>
<div class="name">test2</div>
<div class="name">test3</div>
<div class="name">test4</div>
And one example close to your needs:
function deletePeople() {
var text = document.querySelectorAll('input[type=checkbox]:checked');
var values = [].map.call(text, function (obj) {
return obj.value;
});
var res = confirm(values);
res ? alert("records deleted") : alert("no action");
}
<input type="checkbox" value="test1" />
<input type="checkbox" value="test2" />
<input type="checkbox" value="test3" />
<input type="checkbox" value="test4" />
<input type="button" onclick="deletePeople();return false;" value="Delete" />
Also keep in mind that id must be unique.
References:
Array.prototype.map()
document.querySelectorAll

Fill data in input boxes automatically

I have four input boxes. If the user fills the first box and clicks a button then it should autofill the remaining input boxes with the value user input in the first box. Can it be done using javascript? Or I should say prefill the textboxes with the last data entered by the user?
On button click, call this function
function fillValuesInTextBoxes()
{
var text = document.getElementById("firsttextbox").value;
document.getElementById("secondtextbox").value = text;
document.getElementById("thirdtextbox").value = text;
document.getElementById("fourthtextbox").value = text;
}
Yes, it's possible. For example:
<form id="sampleForm">
<input type="text" id="fromInput" />
<input type="text" class="autofiller"/>
<input type="text" class="autofiller"/>
<input type="text" class="autofiller"/>
<input type="button"value="Fill" id="filler" >
<input type="button"value="Fill without jQuery" id="filler2" onClick="fillValuesNoJQuery()">
</form>
with the javascript
function fillValues() {
var value = $("#fromInput").val();
var fields= $(".autofiller");
fields.each(function (i) {
$(this).val(value);
});
}
$("#filler").click(fillValues);
assuming you have jQuery aviable.
You can see it working here: http://jsfiddle.net/ramsesoriginal/yYRkM/
Although I would like to note that you shouldn't include jQuery just for this functionality... if you already have it, it's great, but else just go with a:
fillValuesNoJQuery = function () {
var value = document.getElementById("fromInput").value;
var oForm = document.getElementById("sampleForm");
var i = 0;
while (el = oForm.elements[i++]) if (el.className == 'autofiller') el.value= value ;
}
You can see that in action too: http://jsfiddle.net/ramsesoriginal/yYRkM/
or if input:checkbox
document.getElementById("checkbox-identifier").checked=true; //or ="checked"

Categories

Resources