Form input to JavaScript variable - javascript

Trying to teach myself basic JavaScript and stuck for days with this simple concept.
I want to save a form input to a variable and later on execute a function,alert or whatever with that var.
function myFunc() {
var userName = document.getElementById("name").value;
alert("Hello, " + userName + "!");
}
<form onSubmit="myFunc" ;>
<input type="text" id="name">
<input type="submit" value="Submit">
</form>
This is actually an example from a book but it does not work in jsfiddle and nor does it on my own server. I can call up the function from the console but it won't execute from the submit button.
What am I doing wrong here ?

You forgot () into onSubmit attribute.
PS: Also you add ; into <form> tag (invalid) and you forgot both input closure <input> -> <input/>
function myFunc() {
var userName = document.getElementById("name").value;
alert("Hello, " + userName + "!");
}
<form onSubmit="myFunc()">
<input type="text" id="name"/>
<input type="submit" value="Submit"/>
</form>

If you are learing JS, better read a little bit about, you can write code in a better way by following a design pattern (you can learn more here
My solution will be
(function () {
// variables
// cached elements
var form = document.querySelector('#form'),
nameInput = document.querySelector('#name');
// event bindings
form.addEventListener('submit', myFunc);
// methods
function myFunc (e) {
e.preventDefault(); // prevents the page reload
alert(nameInput.value);
}
})();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<form id="form">
<input type="text" id="name">
<input type="submit" value="Submit">
</form>
</body>
</html>

You need to add two brackets in your onsubmit expression. When you want to prevent the page from refreshing you could even return false inside your function.
function myFunc() {
var userName = document.getElementById("name").value;
alert("Hello, " + userName + "!");
return false;
}
<form onsubmit="myFunc()">
<input type="text" id="name">
<input type="submit" value="Submit">
</form>
Another way is to add a listener to your form, so you could get rid of onsubmit in general.
function myFunc( event ) {
var userName = document.getElementById("name").value;
alert("Hello, " + userName + "!");
event.preventDefault();
}
document.getElementsByTagName( 'form' )[ 0 ].addEventListener( 'submit', myFunc );
<form>
<input type="text" id="name">
<input type="submit" value="Submit">
</form>
But with this solution you need to use preventDefault on the event parameter.

Related

Why will my function not return string inputted by user

I'm trying to have a user input a string or number on the page, hit submit and have console.log print the string just entered, however as much as I tried it will not print.
Am I missing something here? ( sorry for indentation)
<html>
<head>
<body>
<form>
<input id="userInput" type="text">
<input type="submit" id = "submit()">
</form>
<script>
function submit() {
var test = document.getElementById("userInput");
return console.log(test);
}
</script>
</body>
</head>
</html>
This code will give the result as you expect.you cannot return console.log in return function to get value and also dont use form so that it will always look for action in these kind of cases
function submit() {
var test = document.getElementById("userInput").value;
console.log(test);
return test;
}
<div>
<input id="userInput" type="text">
<button onclick = "submit()"> Submit</button>
</div>
You're doing a few things wrong. Just read the below code, I left explaining comments for you.
<html>
<head>
<body>
<form>
<input id="userInput" type="text">
<button type="button" id="submitBtn" onclick="submit()">Submit</button> // ID - can't be used for submitting a function
</form>
<script>
function submit() {
var test = document.getElementById("userInput");
alert(test.value); // console.log() - is like a void function and it can't be returned
}
</script>
</body>
</head>
</html>
If you look in the console you'll see it's logging a reference to the element, not the value entered in it.
This is because your variable test stores a reference to the element.
var test = document.getElementById("userInput");
You need
var test = document.getElementById("userInput").value;
use Onclick attribute for Submit button! and Also the type of input should be button to prevent the refreshing.
<form>
<input id="userInput" type="text">
<input type="button" onclick= "submit()">
</form>
in JavaScript Code add the value property.
var test = document.getElementById("userInput").value;
Please check the below code. I think this is what you want. The problem was hooking up the event
<form>
<input id="userInput" type="text">
<input id="myBtn" type="submit">
</form>
<script>
document.getElementById("myBtn").addEventListener("click", function() {
var test = document.getElementById("userInput");
console.log(test);
return false;
});
</script>

How do I manually test JavaScript?

I'm trying to learn javascript by making a simple price checking website using the Best Buy products API.
How do I "run" the javascript? My form takes in a product ID number (the SKU) and sends it to validateSKU() on submit. The function processData(data) searches for the product using the SKU.
Nothing is happening when I test the site, and any help would be great; thanks!
<!DOCTYPE html>
<html>
<head>
<title>Learn JavaScript</title>
</head>
<body>
<form id="bestBuyForm" name="bestBuyForm" onsubmit="validateSKU()">
<input id="SKU" name="SKU" required="" type="text">
<label for="SKU">SKU</label>
<input id="email" name="email" type="email">
<label for="email">Email</label>
<input class="button" id="submit" name="submit" type="submit">
</form>
<script>
function validateSKU() {
var SKU = document.forms["bestBuyForm"]["SKU"].value;
var bby = require('bestbuy')('process.env.BBY_API_KEY');
var search = bby.products('sku=' + SKU);
search.then(processData);
}
function processData(data) {
if (!data.total) {
console.log('No products found');
} else {
var product = data.products[0];
console.log('Name:', product.name);
console.log('Price:', product.salePrice);
}
}
</script>
</body>
</html>
Use web console to see what does happen and read about the console API.
Try to bind validateSKU with HTML element addEventListener method. Also you should prevent default form behaviour which cause page reloading on submit. Call event.preventDefault().
Working example code:
<html>
<form id="someForm">
...
<button type="submit">Submit</submit>
</form>
<script>
function validateSKU(event) {
console.log('IT works');
event.preventDefault();
// ...here your code
}
var form = document.getElementById('someForm');
form.addEventListener('submit', validateSKU, false);
</script>
</html>

JavaScript is not redirecting

My Javascript is not redirecting. Here is what I tried:
<html>
<head>
<title>Hello world</title>
</head>
<body>
<form method="POST">
Search: <input id="searchterm" type="text" name="searchterm">
<input type="submit" value="Submit" onclick="processFormData()">
</form>
<script>
function processFormData()
{
var term = document.getElementById("searchterm").value;
window.location = window.location.href + term;
}
</script>
</body>
</html>
I want user to be redirected to a specified url no matter of the url in browser. This should be universal on different machines. I am new to JS, please advise.
First, move the onclick event handler declaration to the <form> tag. Next, change it into an onsubmit event handler declaration. Finally add a return in front of it (to prevent default event handling, i.e. actually submitting the form):
<form method="POST" onsubmit="return processFormData();">
Search: <input id="searchterm" type="text" name="searchterm" />
<input type="submit" value="Submit" />
</form>
Then also add a return false; at the end of processFormData:
function processFormData()
{
var term = document.getElementById("searchterm").value;
window.location = window.location.href + term;
return false;
}
Fiddle here: http://jsfiddle.net/xwcvq7bf/
Use location.host. Try this:
function processFormData()
{
var term = document.getElementById("searchterm").value;
window.location = "http://"+location.host+"/"+term;
return false;
}
And,
<form method="POST">
Search: <input id="searchterm" type="text" name="searchterm">
<input type="submit" value="Submit" onclick="return processFormData()">
</form>
So, now your url will be like this: http://www.example.com/searchTerm
You can specify the url itself,
window.location = "url"+term;
If you wanna get only the hostname(http://www.example.com),
window.location = location.hostname +"/"+term;
or If you wanna get the href(http://www.example.com/home/about.htm),
window.location = location.href +"/"+term;

How do you put a string variable in the confirm() function in Javascript/HTML?

I am trying to confirm with the user if the following string he or she is about to enter is correct but the confirmation box won't appear. Here is that segment of the code:
<html xmlns="http://www.w3.org/1999/html" xmlns="http://www.w3.org/1999/html">
<head>
<script>
function validateForm(){
var pkey = document.forms["createProductForm"]["pagekeyTF"].value;
var agree = confirm("Is this your product?\n\n ${pkey}");
if(agree) //Do something
else //Do something else
}
</script>
</head>
<body>
<form name="createProductForm" controller="actions" action="ImplementNewProduct" onsubmit="return validateForm()" method="post">
<g:textField id="productTF" name="productTF" value="My Product" />
<button id="createProductID" name="createButton" value="Create Product">Create Product</button>
</form>
</body>
</html>
Am I not allowed to pass in string variables in the confirmation function? Because if I take off the ${pkey} it works fine but it does not include the user's input and that is not what I am not trying to achieve. Any help? Thanks!
Edit it like this :
var pkey = document.forms["createPixelForm"]["pagekeyTF"].value;
var agree = confirm("Is this your product?\n\n " + pkey);

How to write to localStorage and post textarea with one click?

I have a handler /choice with a textarea field and /choicehandler that writes the information returned to database. But before posting the form I want to write a user name to localStorage.
This is the form:
<form name="choice_form" action="/choicehandler" method="post">
<textarea name="choice" rows="7" cols="50"></textarea><br />
<input type="submit" value="submit your choice">
</form>
On click I want to assign a username to the user and write it to localStorage with writeToStorage():
<head>
<script type="text/javascript">
var count = 0;
function writeToStorage()
{
user = "user" + count;
count++;
localStorage.setItem("chooser", user);
};
</script>
</head>
What I am confused about is how to use onclick="writeToStorage()" to call the writeToStorage() and at the same time have action="/choicehandler" in the form.
What is the correct way to achieve something like this. I am working with Google App Engine (Python) and I will add the ajax call to /choicehandler later after I solve this.
As a summary, I want to write the javascript variable user to localStorage and post the textarea to /choicehandler with one click.
UPDATE
I am trying john_doe's answer but writeToStorage() is never fired. What am I doing wrong? The full code for the handler is below:
class Choice(webapp.RequestHandler):
def get(self):
self.response.out.write("""
<html>
<head>
<script type="text/javascript">
var count = 0;
function writeToStorage()
{
alert("count: " + count);
user = "user" + count;
//this line was giving an error; now it is fixed
//alert("user: " + user and "count: " + count);
alert("user: " + user + " and count: " + count);
count++;
localStorage.setItem("chooser", user);
};
</script>
</head>
<body>
<form name="choice_form" id="choice_form" action="/choicehandler" method="post" onsubmit="writeToStorage()">
<textarea name="choice" rows="7" cols="50"></textarea><br />
<input type="submit" value="submit your choice">
</form>""")
self.response.out.write("""
</body>
</html>""")
Let your function get invoked right before the form gets submitted.
<form name="choice_form" action="/choicehandler" method="post" onsubmit="writeToStorage()">
<textarea name="choice" rows="7" cols="50"></textarea><br />
<input type="submit" value="submit your choice">
</form>
you can change your function a bit (lots of ways to do this). Add an Id to your form (id="choice_form"), then add a line that submits your form:
function writeToStorage() {
user = "user" + count;
count++;
localStorage.setItem("chooser", user);
document.getElementById("choice_form").submit();
}

Categories

Resources