Turn HTML Form Input into JavaScript Variable - javascript

I am new to HTML forms and I was wondering how I can easily (or not) change it's input to a JavaScript variable. Here is my code:
<head>
<title>Begin</title>
<link type="text/css" rel="stylesheet" href="begin.css"/>
</head>
<body>
<form action="begin-create-done.html" method="get">
First Name: <input type="text" name="firstname">
<br>
Last Name: <input type="text" name="lastname">
<br>
<br>
New Username: <input type="text" name="user">
<br>
Password: <input type="password" name="pass">
<br>
Repeat Password: <input type="password" name="rpass">
<input type="submit" value="Submit">
</form>
</body>
</html>
I want each part of the form (e.x. First Name, Last Name, New Username, etc.) to be it's own JavaScript variable. Thank you very much!

Accessing HTML input elements from JavaScript
Assuming you don't have other elements with same names, you can access input values from JavaScript by name as follows:
var firstName = document.getElementsByName("firstname")[0].value;
You now have the value from firstname field in JavaScript variable called firstName. Just keep repeating and you got the other input fields too. You can then proceed and wrap these statements to a function and call it when input data changes. For example:
function formChanged() {
var firstName = ...
var lastName = ...
}
Now register this function call to change / keyup events and you have a function that monitors changing form values:
<input type="text" name="firstname" onkeyup="formChanged()" onchange="formChanged()"/>

Should you prefer a more structured approach, or if you have more than one form on the page, you could:
Create an object that will hold all form values and update them. After that you could simply access them with formValues.inputName.
Store your default values in an array (in the same order as your inputs).
Execute a function that will take care of outputting the default values & updating the object when the values are changed. It takes the form (selected by Id, Class, whatever) and an array of default values as parameters.
// create the object that will hold the input values
var formValues = {};
// store code in the function for a more 'modular' approach
function inputObj(formNR, defaultValues) { // where defaultValues is an array
var inputs = formNR.getElementsByTagName('input');
for ( var i = 0; i < inputs.length; i++) {
if(inputs[i].type === 'text' || inputs[i].type === 'password') {
formValues[inputs[i].name] = defaultValues[i]; // store default in object
}
inputs[i].value = defaultValues[i]; // output default in input
inputs[i].addEventListener('keyup', function() { // update object on change
formValues[this.name] = this.value;
}, false);
}
}
// build a little array with the defaultValues for each input
var defValues =['defaultFirstName','defaultLastName','defaultUser',
'defaultPass','defaultPass'];
// this will push all inputs from the given form in the formValues object.
inputObj(document.forms[0], defValues);
// Access the values like this, eg.
console.log(formValues.firstname); // will return 'defaultFirstName'
See it in action here. Or with CodeView. Note: The code in the example has some additions to show the object's values on the page.

Try to first create a function that grabs the value from the input field:
<script>
function XX()
{
var first2 = document.getElementById("firstname").value;
}
</script>
Then you have to fire it up when the input changes with onchange:
FirstName: <input type="text" id="firstname" name="firstname" onchange="XX()">

Related

Can you access a HTML form data from the event property, or a "this" keyword, in javascript?

I know that you can easily get data from a form like:
function getData(event) {
event.preventDefault();
const inpt = document.getElementById("inpt").value;
return inpt;
}
//OR
function getData(event) {
event.preventDefault();
const inpt = document.getElementById('form').elements[0].value;
return inpt;
}
<form id="form" onsubmit="getData(event)">
<input id="inpt" type="text"></input>
</form>
what I'd like to know is if this same value could be reached through the event property or a this keyword, withou using a "getElementBy..." of any sort or any querySelector.
I think I like James' answer better. Much simpler. Haven't tested either too extensively sorry.
If you assign all of your form elements a name attribute, on the form submission event you can use the FormData Api to get their data. I believe this won't work on I.E. or other older browsers (check for browser compatibility).
Form Data: https://developer.mozilla.org/en-US/docs/Web/API/FormData#browser_compatibility
Object.fromEntries(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries#browser_compatibility
<form id="form" onsubmit="getData()">
<input name="input1" id="inpt" type="text"></input>
<input name="input2" id="NotNeededForThis" type="text"></input>
</form>
function getData(event) {
event.preventDefault();
const formData = new FormData(event.target);
const formObject = Object.fromEntries(data.entries());
return formObject;
}
This will return the object:
{
input1: "whatever the value was",
input2: "whatever the value was"
}
Since the event listener is set on the form, the form element is available as
event.target
And so the text field value would be accessible by
event.target.elements[0].value
The form element is also this within the submit handler, so you could also do
this.elements[0].value.
You can access the value of the input through the event directly. For example in the function to access the data of the input field with the name 'input1':
function getData(event){
//format event.target.nameOfInput.value
//for the input field with the name input1
let inp1 = event.target.input1.value;
//for the input field with the name input2
let inp2 = event.target.input2.value;
//
console.log( inp1 , inp2)
}

Not able to know whether values are being inserted or not

Im taking input from user and keeping those values in new array called movie2. If user enters input again it should check the value from movie2 array and if it matches should give a pop up like it already added and if it is a different input it should add those values to movie2 array. I have tried many times but whatever the user inputs it is getting added, it is not comparing.
<!DOCTYPE html>
<html>
<head>
<title>Movie Mania</title>
<link rel="stylesheet" type="text/css" href="Movie.css" >
<script src="Movie.js"></script>
</head>
<body>
<div class="content">
<div class="matter">
<p class="header">Movie Mania</p>
<div class="regis">
<form class="reg">
<input type="text" name="user" id="movie" placeholder="Please enter any
movie name" size="40"><hr>
<div><input type="submit" class="button" value="Search" id="sub"
onclick="validation()" /></div >
</form></div>
</div>
</div></body>
</html>
Javascript:
var movie1 = ["Bahubali", "The Final Destination", "The Cars ","P.K "," Bajarangi Baijaan ","Force "];
var movie2=[];
function validation() {
var movie = document.getElementById("movie").value;
if (!movie.trim()) { //its validate the input empty undefined null
var name2 = "Please enter your favoite movie name";
alert(name2);
}
else if (movie1.includes(movie)) { // includes used for find the value is in array or not
var name2 = "Movie exists in our database";
alert(name2);
}
else {
insert();
}}
function insert(){
var movie = document.getElementById("movie").value;
if(movie2.indexOf(movie)==true){
var name2="Movie already added to Array 2";
alert(name2);
}
else{
movie2.push(movie);
var name2 = "Movie added into Array2";
alert(name2);
}
}
.includes() is part of ES2016, which isn't fully implemented in all browsers yet. Use .indexOf() instead. Now, indexOf() returns -1 when the value doesn't exist or the index position of the item when it does. You have:
if(movie2.indexOf(movie)==true){
Which is not the correct way to test against indexOf(). If indexOf() were to return 0, it would mean that the item was found at the first position in the array (indices start with 0). But, because you are attempting to compare it against true, true will be converted to a number (to perform a number to number comparison) and it will convert to 1. Since 0 doesn't equal 1, the test will fail, and insert the movie even though it already exists.
Also, JavaScript does not have block level scope when using the var keyword for declaration. If you declare a variable with var anywhere in a function, its scope is the entire function. So, you can't declare the variable in one branch of the if and then again in the other. In reality, you don't even need to set up your name variable because all you are doing with it is immediately displaying it in an alert(). Instead, you can just put your string in the alert().
Additionally, don't use inline HTML event attributes (onclick, etc.). Here's why.
Lastly, it appears that you are not actually trying to submit data anywhere. In that case, don't use a submit button, just use a regular button.
// Get refrence to button and textbox
var btn = document.querySelector("form.reg input[type=button]");
// Don't create references to DOM properties because if you decide you want
// to get the value of a different property later, you'll have to scan the DOM
// for the element all over again. Just get a reference to the element once and
// then you can access whatever property you need when you need it.
var movie = document.getElementById("movie");
// Set up click event handler
btn.addEventListener("click", validate);
var movie2 = [];
// Your two functions are redundant. They can be combined into this one:
function validate(evt){
// Access the property of the DOM object you want (user input should always be trimmed)
var mv = movie.value.trim();
// Quick test for input:
if(mv === "") {
alert("You didn't enter anything!");
return;
}
// If we've gotten this far, there is input, so test to see if it is already in the array
var message = "";
if(movie2.indexOf(mv) > -1){
message = "Movie already added to Array 2!!!!";
} else {
movie2.push(mv);
message = "Movie added to Array 2";
}
alert(message);
// Just for testing:
console.clear();
console.log(movie2);
}
<div class="content">
<div class="matter">
<p class="header">Movie Mania</p>
<div class="regis">
<form class="reg" action="#">
<input type="text" name="user" id="movie" placeholder="Please enter any movie name" size="40">
<hr>
<div>
<input type="button" class="button" value="Search" id="sub">
</div>
</form>
</div>
</div>
</div>
The includes() method determines whether a string contains the
characters of a specified string. This method returns true if the
string contains the characters, and false if not.
Hence we shall not use includes() method to compare/search strings.
There are multiple ways you can search for a string in an array of string.
I check for string given to me in given array of string using
indexOf()
The indexOf() method returns the position of the first occurrence of a specified value in a string.
This method returns -1 if the value to search for never occurs.
And where you are adding the movie to the array, you do not need to read data from input box again. The better idea is to clean up the input, validate it and provide it as input to insert(movie).
Here is the sample code, which is working for me.
var movie1 = ["Bahubali", "The Final Destination", "The Cars ","P.K "," Bajarangi Baijaan ","Force "];
var movie2=[];
function validation()
{
var movie = document.getElementById("movie").value;
movie = movie.trim();
if (!movie) //its validate the input empty undefined null
{
var name2 = "Please enter your favoite movie name";
alert(name2);
}
else if (movie1.indexOf(movie) > -1) // check if movie already exists
{
var name2 = "Movie exists in our database";
alert(name2);
}
else
{
insert(movie);
}
}
function insert(movie)
{
if(movie2.indexOf(movie) > -1)
{
var name2="Movie already added to Array 2";
alert(name2);
}
else
{
movie2.push(movie);
var name2 = "Movie added into Array2";
//alert(name2);
for (var i=0; i < movie2.length ; i++)
{
console.log(movie2[i]);
}
}
}
<!DOCTYPE html>
<html>
<head>
<title>Movie Mania</title>
<script type="text/javascript" src="testjs.js"></script>
</head>
<body>
<p class="header">Movie Mania</p>
<form>
<input type="text" name="user" id="movie" placeholder="Please enter any movie name" size="40">
<hr>
<div>
<input type="submit" class="button" value="Search" id="sub"
onclick="validation()" />
</div >
</form>
</body>
</html>

Jquery not returning the values in form INPUTs

I have a login form on a modal jquery dialog with the usual 2 text INPUTs. When I enter a login name and password then click the submit, the call back function is called.
The first thing the callback does is try to extract the values of the two INPUTs, but the values returned are empty strings (I have a breakpont here, and have even stepped through the jquery processing of the objects - they objects are correctly identified as the fields on the form, but value="" for both).
At this point I can still see the values in the form, and when the callback exits and the focus goes back to the form, the values are still in the INPUTS. I also tried .prop("value") rather than .val(), but the result was the same.
I just can't figure why I can't read the values - any help appreciated.
<form id="cp-loginform" action="/cypo/index.php" method="POST" >
<input type="hidden" name="Login" value="Login">
<input type="hidden" name="pp" value="0" />
<input type="text" id="cp-loginname" name = "loginname" placeholder = "Login ID" class="loginforminput cp-width-50" autofocus >
<input type="password" id="cp-password" name = "password" placeholder = "password" class="loginforminput cp-width-50"></p>
<input type="submit" id="cp-submit" name = "submit" onclick="ProcessLogin()" ></p>
</form>
function ProcessLogin() {
var loginval = $("#cp-loginname").val();
var passwordval = $("#cp-password").val();
console.log(loginval.concat(" ",passwordval));
}
PROBLEM RESOLVED:
I felt that this was a scope issue. The form itself was obviously OK (if submitted from the dialog it worked) - it was just the attempt to check the INPUT values using jquery that wasn't working.
I found that my select had to start with the dialog element and include a descendent path to my INPUTs. It's as if the dialog puts a wrapper around the elements inside so they are no longer visible as owned by the document.
If I login with xxx and zzz and step therough the following code I see this:
var loginval = $("#cploginname").val(); << = ""
var passwordval = $("#cppassword").val(); << = ""
var loginval = $("#cp-loginform #cploginname").val(); << = ""
var passwordval = $("#cp-loginform #cppassword").val(); << = ""
var loginval = $("#cpdialog #cp-loginform #cploginname").val(); << = "xxx"
var passwordval = $("#cpdialog #cp-loginform #cppassword").val(); << = "zzz"
console.log(loginval.concat(" ",passwordval));
I can't say I understand what's going on, but I have a solution so I am happy. Thanks to all who answered.
FINAL WORD
Thanks to #CMedina, I now understand. The form was defined in a hidden DIV at the top of my BODY section, and I passed $("#loginform") to a f() that created the dialog. The dialog was added to the DOM just before the . I had missed the fact that my original form was still in the DOM, so I was referencing that, not the dialog copy. When I included the dialog wrapper in the path, I finally 'found' the second copy.
Your button is the type submit (their natural behavior is to send the form). Remove the onclick in your button html.
<input type="submit" id="cp-submit" name = "submit">
You must add preventDefault to prevent submit the form and do what you want. Add the code JS for the button onclick event
$("#cp-submit").on("click", function(e){
e.preventDefault();
var loginval = $("#cp-loginname").val();
var passwordval = $("#cp-password").val();
console.log(loginval.concat(" ",passwordval));
});
Result: https://jsfiddle.net/cmedina/svjqb2a4/
Try it :
<html>
<head>
</head>
<body>
<form id="cp-loginform" action="/cypo/index.php" method="POST">
<input type="hidden" name="Login" value="Login">
<input type="hidden" name="pp" value="0" />
<input type="text" id="cp-loginname" name = "loginname" placeholder = "Login ID" class="loginforminput cp-width-50" autofocus >
<input type="password" id="cp-password" name = "password" placeholder = "password" class="loginforminput cp-width-50">
<input type="submit" id="cp-submit" name ="submit" onclick="ProcessLogin(event)">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
function ProcessLogin(e) {
e.preventDefault();
var loginval = $("#cp-loginname").val();
var passwordval = $("#cp-password").val();
alert(loginval.concat(" ",passwordval));
}
</script>
</body>
</html>

Passing the value of a button into a text field

I'm having some trouble with getting Javascript to pass a value (which is stored in local storage) into a textfield. Ideally, I'd like for someone to be able to click the 'apply here' button on one page, have the job number stored in local storage and then have it auto-populate the job number field on my application page with the job number.
This is what I've got so far, I have a feeling that I haven't assigned things correctly.
html (on submit page)
<p>
<form id="applyjob1" action="enquire.html" method="get">
<input type="submit" id="job1" value="Apply for Job" />
</form>
</p>
html (field I'm trying to put data into)
Job Reference Number <input required="required" id="jobNo" name="jobno" type="text" /> </br />
Javascript
window.onload = function init() {
var jobID = document.getElementById("job"); /*button name */
jobID.onsubmit = passJob; /*executes passJob function */
}
function passJob(){
var jobSubmit = localstorage.jobID("1984"); /*assigns localstorage*/
if (jobSubmit != undefined){
document.getElementById("jobNo").value = localstorage.jobID;
}
I think this code would work for your fuction.
function passJob(){
localStorage.setItem("jobID", "1984");
if (localStorage.jobID != undefined) {
document.getElementById("jobNo").value = localStorage.jobID;
}
}
You are assigning the jobSubmit wrongly. To set item, use localStorage.setItem('key', value). Note the casing as it matters.
So basically you should do
var jobSubmit = localStorage.setItem(,"jobID", "1984"); // assigns jobSubmit
And I don't see any element with id="job"

Restore textfield's default value when user clicks the reset button JavaScript

I'm trying to get the textfields to return to their default value when the user clicks the Reset button.
All it does now when the user clicks the Reset button is replacing the user's text with ''.
How can I do it by using pure JavaScript (no jQuery)?
HTML:
<p>Type the first number</p>
<input id="first" type="text" placeholder="First Number" />
<p>Type the second number</p>
<input id="second" type="text" placeholder="Second Number" />
<button id="aButton">Apply</button>
<button id="rButton">Reset</button>
<div id="add"></div>
JAVASCRIPT:
app.onactivated = function (args) {
var aButton = document.getElementById("aButton");
aButton.addEventListener("click", buttonClickHandler, false);
var rButton = document.getElementById("rButton");
rButton.addEventListener("click", buttonResetHandler, false);
};
...
function buttonResetHandler(evetInfo) {
document.getElementById("first").innerText = '';
document.getElementById("second").innerText = '';
}
innerText is an invalid property that is implemented in IE browsers and is used for setting/getting text content of non-form elements, if the values should be set as default, you can use defaultValue property:
var a = document.getElementById("first"),
b = document.getElementById("second");
a.value = a.defaultValue;
b.value = b.defaultValue;
If you want to reset all the form elements, you can use .reset() method of DOM HTMLFormElement object:
document.forms["myForm"].reset();
location.reload(); // reloads the page
history.go(0); // deletes the history
But if you need to preserve some values inside of the page then reassign the values in the function again. To reassign, write the variable (declare in let to change later) again in the function and change the textContent again.
Replace,
document.getElementById("first").innerText
With,
document.getElementById("first").value
Example:
<input id="txtBox" type="text" value="lama">
<input type="button" value="reset lama" onclick='document.getElementById("txtBox").value="lama2";'>
create an init function that sets the default values for each input, then you can call that:
function initializeInputs() {
document.getElementById("first").value = '';
document.getElementById("second").value= '';
}
function buttonResetHandler(e) {
initializeInputs();
}

Categories