html javascript variable from text input null [duplicate] - javascript

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 6 years ago.
So basically I'm trying to get a name that is entered in a text input box in the body to show in an alert in script but it always displays the name as null or if I put .value on the end of the document.getElementById("name") it doesn't display anything. I'm confused because in all the tutorials I've seen it always says to just do it like I did it...
Here's the code I was using:
<!DOCTYPE html>
<html>
<script>
var name = document.getElementById("name");
function showName()
{
alert ("Your name: " + name)
}
</script>
<body>
<form name = "form">
Please enter your full name <input type = "text" id = "name"><br>
<input type = "button" value = "show name" onclick = "showName()">
</form>
</body>
</html>

You need to do some adjustments to your code:
<!DOCTYPE html>
<html>
<body>
<form name = "form">
Please enter your full name <input type = "text" id = "name"><br>
<input type = "button" value = "show name" onclick = "showName()">
</form>
<script>
function showName()
{
var name = document.getElementById("name");
alert ("Your name: " + name.value);
}
</script>
</body>
</html>
First: Put your function to end of your html code to ensure that you can read the element "name".
Second: You need to get the element just when the user clicks on the button, if you get the element before you can't get the value if this exists.
Third: When you get the element, you are getting an object, in order to get the value, you need to call the property value of this object.
Fourth: Always validate if your variables have content or exist.

Try this
<!DOCTYPE html>
<html>
<body>
<form name = "form">
Please enter your full name <input type="text" id="name" value=""><br>
<input type = "button" value="show name" onclick="showName()">
</form>
<script>
function showName() {
var name = document.getElementById("name").value;
alert ("Your name: " + name);
}
</script>
</body>
</html>

function showName()
{
var name = document.getElementById("name");
alert ("Your name: " + name.value);
}
Something like this.

You need to .value because you want input value and also move your get id name into your function .Because your getting id is outside of function so it will always return undefined coz of initial state value is nothing..
<script>
function showName()
{
var name = document.getElementById("name");
alert ("Your name: " + name.value);
}
</script>

You need to put your variable declaration var name = document.getElementById("name"); inside your function function showName() so when your variable gets the value the real value is assigned.
check this fiddle
hope it helps

Instead of
var name = document.getElementById("name");
use
var name = document.getElementById("name").value;
alert('Your name: ' + name);
Hope this helps !

Related

How to get the value of input field in one page and print it in another page?

How can I get the value of an input field and print it on another HTML page? Here is my first page:
index.html
<form action="page.html" method="get">
<label>Enter your name:</label><br>
<input type="text" id="firstName" name="firstName"><br>
<input type="submit" name="submit" value="Submit">
</form>
<script>
function myFunction() {
var name = document.getElementById('firstName').value;
</script>
I want to print that "name" variable on the "page.html". Please help.
I would suggest you to use localStorage , set this value :
localStorage.setItem('nameOfVariable', value);
and after loading other page you can get the value with
localStorage.getItem('nameOfVariable')
In your case :
function setName() {
var name = document.getElementById('firstName').value;
localStorage.setItem('name', name);
}
in page.html :
function getName() {
var name = localStorage.getItem('name');
// Do something
}
Try to use localStorage.
var name = document.getElementById('firstName').value;
window.localStorage.setItem('name', name);
And then in page.html page,
Try to get name
const name = window.localStorage.getItem('name')
And then print it.
You need to use the localStorage in the variable name like
document.getElementById("firstName").value = localStorage.name
You can acces the localStorage data from an another page like
document.getElementById("name").innerHTML = localStorage.name;

HTML Form to display output by using a button

Please let me know what I am doing wrong, I have tried to debug but it hasn't been working. I want to enter information into a text field and then display that after clicking a button.
<!DOCTYPE html>
<html>
<head>
<script type = 'text/javascript'>
var name; //name
console.log("hi from script");
function getName() { //get name
return document.getElementById("name").value;
}
function display() { //get the name and display
name = getName();
alert(name);
}
document.getElementById("Submit").onclick = display();
</script>
</head>
<body>
<form id='form'method = 'post'>
<p> Name: <input type="text" id="name"/></p>
<p><input id ="Submit" type = "button" value = 'Submit' /></p>
</form>
</body>
</html>
The problem is that you are making use of a <form> POST. The default behaviour is to navigate away from the page (or refresh if you're posting to the same page), and doing so would mean that the script cannot execute any further functionality. To prevent this, you need to use .preventDefault() to prevent the default behaviour of the form submission.
In order to do this, I've changed your .onclick = display() functionality to add an event listener on the click, which prevents the default behaviour, and then calls display():
.addEventListener("click", function(event) {
event.preventDefault();
display();
});
Adding this provides the following working example:
var name; //name
console.log("hi from script");
function getName() { //get name
return document.getElementById("name").value;
}
function display() { //get the name and display
name = getName();
alert(name);
}
document.getElementById("Submit").addEventListener("click", function(event) {
event.preventDefault();
display();
});
<form id='form' method='post'>
<p> Name: <input type="text" id="name" /></p>
<p><input id="Submit" type="button" value='Submit' /></p>
</form>
Hope this helps! :)
Create an empty p tag and give it an id, then call the id and .html to input the text into the field. Like so
so get your html ready
<p><span id="youridhere"><p>
then add this to your function instead of using alert.
$('#youridhere').html(name);
that should do it
here's a jsfiddle of what I think you are looking for
https://jsfiddle.net/uzdt715L/
$('button').click(function(){
var thing = $('#whatever').val();
$('#final').html(thing);
});
You need to update your click handler syntax. The following should work for you,
document.getElementById("Submit").addEventListener("click", display);
See this related question - addEventListener vs onclick
Your code is not really wrong.
But because the JavaScript is placed before htm code, so the onlick event is not registered.
You must replace
document.getElementById("Submit").onclick = display();
With
document.onload = function() {
document.getElementById("Submit").onclick = display();
}
Sorry for the formatting as I'm answering via mobile.

How to use a html form to send data to javascript to be saved as a variable

I want to use html and javascript (strictly no php) to have a html data entry form to pass data to js to be saved as a variable. Any help would be appreciated :)
This is what a have so far:
<form id="myform"> //form name
What is your name: <input type='text' name='name'> //name input
Go // running some kind of function?
</form>
and then the js side
var name = 'test';
function formCatch() { //declare function 'formCatch'
name = document.forms["myform"].submit(); // set the name variable as the contents from the form
alert('hello, ' + name); // alert to test the output
}
I'm pretty sure the second line of the function is incorrect.
What I'm looking for in that function is for the data entered into the form on the html page to be saved as the name variable.
maybe it's what you're looking for:
<script>
var name = 'test';
function formCatch() {
document.forms["myform"].submit();
name = document.getElementById("name").value;
alert('hello, ' + name);
}
</script>
<form id="myform">
What is your name: <input id="name" type='text' name='name'>
Go
</form>
See this demo
(EDITED)
HTML :
What is your name: <input type='text' id='name'/>
<a onclick="formCatch();" href="#">Go</a>
JS :
function formCatch() {
name = getElementById("name").value;
alert('hello, ' + name);
}
You dont need to submit your form, just access the value of your name.
name = document.forms["myForm"]["name"].value;

Dynamic values in object properties

want to make values of the oject's dynamic (from user input) but I get "undefined". The idea is to have 3 input fields and the user should input values in them which will fill up the alert message.
<script type="text/javascript">
function Family (fatherName, motherName, sisterName) {
this.fatherName = fatherName;
this.motherName = motherName;
this.sisterName = sisterName;
this.myFamily = function() {
alert("My father's name is " + this.fatherName +", my mother's name is "+ this.motherName +" and my sister's name is " + this.sisterName +".");
}
}
var Me = new Family(
Family["fatherName"] = father,
Family["motherName"] = mother,
Family["sisterName"] = siter);
var father = document.getElementById("fatherId").value;
var mother = document.getElementById("motherId").value;
var sister = document.getElementById("sisterId").value;
</script>
<input type="text" id="fatherId" />
<input type="text" id="motherId" />
<input type="text" id="fatherId" />
<input type="submit" value="Send" onclick="Me.myFamily();">
Also I'm looking for a way how user can add or remove properties (values in them, too).
There are a few things wrong with your code.
You've used your variables here
Family["fatherName"] = father,
Family["motherName"] = mother,
Family["sisterName"] = siter); // This should be sister by the way
before declaring them here
var father = document.getElementById("fatherId").value;
var mother = document.getElementById("motherId").value;
var sister = document.getElementById("sisterId").value; // Doesn't exist
Try switching the statements so you're declaring the variables first.
Also, there is no sisterId, you've used fatherId twice.
You're also calling javascript before the DOM is ready. If you're using jQuery, wrap your JS in
$(document).ready(function() { }
or if you want to stick with plain JS, try
window.onload = function() { }
You'll have to be more specific on what myFamily is supposed to do, since you haven't even mentioned that method.
Here is the working snippet of your example.
<input type="text" id="fatherId" />
<input type="text" id="motherId" />
<input type="text" id="sisterId" />
<input type="submit" value="Send" id="submit" />
<script>
function Family(fatherName, motherName, sisterName) {
this.fatherName = fatherName;
this.motherName = motherName;
this.sisterName = sisterName;
this.myFamily = function() {
alert("My father's name is " + this.fatherName +
", my mother's name is " + this.motherName +
" and my sister's name is " + this.sisterName + ".");
};
}
document.getElementById("submit").onclick = function() {
var father = document.getElementById("fatherId").value;
var mother = document.getElementById("motherId").value;
var sister = document.getElementById("sisterId").value;
Me = new Family(father, mother, sister);
Me.myFamily();
}
</script>
All the mistakes are summarized very well by Brandon.
*EDIT: (anser to your comment)
Your code has two execution related problems.
<script> tags are executed immediately and therefore if you insert script before the <input> part then there are no input elements available for you to retrieve.
You want to retrieve values of the inputs, but those inputs contain data when user clicks on the submit and therefore must be read using .value() at the onclick time. If you try to read them outside the onclick part then they are accessed immediately during page load when the input fields are empty.

how do i get the info from a form using javascript?

i have a form which user enters some data, could be checkboxes, radio buttons, textfields, etc
when user click submit button, i want to refresh the page with whatever data that was entered
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
</head>
<body id="ref">
<form>
Please enter your name:<input type="text" id="name" />
Please enter your age:<input type="text" id="age" />
</form>
<input type="button" onclick="c()" value="submit">
<script type="text/javascript">
function c()
{
var o = document.getElementById('ref');
o.innerHTML = '';
var n = document.createElement('p');
var nam = document.getElementById('name');
n.innerHTML = "Your name is: " + nam;
o.appendChild(n);
var a = document.createElement('p');
var ag = document.getElementById('age');
a.innerHTML = "Your age is: " + ag;
o.appendChild(a);
//how do i get the info from the form? because both nam and ag are coming up null
}
</script>
</body>
</html>
my guess this is not working is because the page refreshes then tries to fetch the element by id which is not there anymore.. whats the correct way of doing this??
You're confusing objects with their properties. Here, you're getting the HTMLInputElement instance for the "age" field:
var ag = document.getElementById('age');
But here you're using that object as though it were a simple value:
a.innerHTML = "Your age is: " + ag;
The HTMLInputElement object has a value field you can use for that:
a.innerHTML = "Your age is: " + ag.value;
Separately, you're completely destroying the page by doing this:
var o = document.getElementById('ref');
o.innerHTML = '';
...because you've given the body element the ID "ref". Completely replacing the body element completely replaces the body element, so you can't rely on objects that only exist as subordinates of that element.
The usual thing is to have an element to fill in, and (optionally) to remove the elements you no longer need. For instance (live copy):
HTML:
<form id="theForm">
Please enter your name:<input type="text" id="name" />
Please enter your age:<input type="text" id="age" />
<input type="button" onclick="c()" value="submit">
</form>
<div id="result">
</div>
(Note I moved the button into the form for convenience.)
JavaScript:
function c() {
var form = document.getElementById("theForm"),
nameField = document.getElementById("name"),
ageField = document.getElementById("age"),
result = document.getElementById("result");
form.parentNode.removeChild(form);
result.innerHTML =
"Your name is " + nameField.value +
" and your age is " + ageField.value;
}
There, when the button is pressed, I remove the form and fill in the "result" div.
You could add the "result" div dynamically if you wanted (live copy):
HTML:
<form id="theForm">
Please enter your name:<input type="text" id="name" />
Please enter your age:<input type="text" id="age" />
<input type="button" onclick="c()" value="submit">
</form>
JavaScript:
function c() {
var form = document.getElementById("theForm"),
nameField = document.getElementById("name"),
ageField = document.getElementById("age"),
result;
result = document.createElement("div");
result.innerHTML =
"Your name is " + nameField.value +
" and your age is " + ageField.value;
form.parentNode.insertBefore(result, form);
form.parentNode.removeChild(form);
}
You can access the fields using a briefer and somewhat more natural syntax if you change your id values to name values instead (live copy):
HTML:
<form name="theForm">
Please enter your name:<input type="text" name="name" />
Please enter your age:<input type="text" name="age" />
<input type="button" onclick="c()" value="submit">
</form>
JavaScript:
function c() {
var form = document.theForm,
nameField = form.name,
ageField = form.age,
result;
result = document.createElement("div");
result.innerHTML =
"Your name is " + nameField.value +
" and your age is " + ageField.value;
form.parentNode.insertBefore(result, form);
form.parentNode.removeChild(form);
}
Further reading:
DOM2 Core (well-supported by most modern browsers)
DOM2 HTML
DOM3 Core (increasingly supported)
If you want to update your html using java-script only , you may use ".value" attribute of the input;
var a = document.createElement('p').value;
var ag = document.getElementById('age').value;
Usually the Form information is processed using server-side code , this is done by specifying the action attribute of the form:
<form action="processuserinfo.aspx">
...
</form>
I'm pretty sure this isn't doable javascript alone. You'll need to use a server-side language like php. Try to google php forms, and you should get some good results. :)

Categories