I have a variable that I want saved so that multiple functions can use it. I followed w3schools's directions but it doesn't work. Am I forgetting something? Thank you in advance.
var name = document.getElementById('name').value;
function complete() {
document.getElementById('demo').innerHTML = name;
}
There are a few things to consider:
If you have code that attempts to find an element, but that element hasn't even been read by the browser yet, the browser won't be able to find it. So, make sure that your code only runs AFTER the full DOM has been loaded
by placing the script just before the closing body tag.
Don't attempt to get the value of a form field as soon as the page
loads because the user hasn't typed anything into it yet, so the
value will be nothing. You need to set up your code so that your function gets called at the right time (after the user has had a chance to type in the form field) so only get the value when that moment has come.
Don't give any element the name name because the Global window
object has a property called name that defaults to an empty string
and when you attempt to access name, it could incorrectly attempt
to get the window.name instead of your element called name.
Only form fields have a value property. All other elements have
.textContent (used when the string does not contain any HTML or you
want the actual HTML code displayed, rather than parsed) and
.innerHTML (used when the string does contain HTML and you want
that code parsed).
Lastly, do yourself a favor and don't use W3Schools. It is well known to have outdated or flat out wrong information on it. Instead use the Mozilla Developer's Network, which is recognized as one of the best resources for client-side web development documentation.
<input type="text" id="userName">
<input type="button" value="Click Me!" id="btn">
<div id="demo"></div>
<script>
// Set up the button's click event handling function
document.getElementById("btn").addEventListener("click", complete);
// Only get a reference to the element, not its value because, at this point,
// the user hasn't had a chance to type anything into it.
// Also, getting a reference to the element is the best approach because, if
// you decide you want some other property of the same element later, you'd have
// to scan the document for the same element again.
var theName = document.getElementById('userName');
function complete() {
// Now, just get the current value of the textbox at this moment in time
document.getElementById('demo').textContent = theName.value;
}
</script>
Related
I've got a script in good working order that checks to see if a visitor has been assigned a coupon code but wanted to add functionality that retrieves the coupon code that they were assigned and displays it. Both rely on the localStorage property. The problem I'm running into is that when I display the stored value, it's returning [object HTMLSpanElement] instead of the value that should be assigned.
Pretty much everything I've found on the issue is due to scope, but I don't see how I have a scope issue...even tried making the variables global in scope and that didn't seem to do anything.
Here is the JS:
if(localStorage.getItem("visited") != "true"){
localStorage.setItem("visited","true");
var codeValue = document.getElementById("code");
localStorage.setItem("code",codeValue);
}
else {
var savedCode = localStorage.getItem("code");
document.getElementById("message").innerHTML = "You've already been assigned coupon code " + savedCode;
}
Here is the relevant HTML:
<span id="message">Your coupon code is: <span id="code">CODE1234</span></span>
When you return to the page after already visiting it, I expect the span text to display You've already been assigned coupon code CODE1234, but instead it is returning You've already been assigned coupon code [object HTMLSpanElement]
Note that part of the script was something I had created before and put in production, and I'm basically piggybacking off of that functionality. Previously, if getItem("visited") != "true" returned false, it popped up an alert box and said you'd already been given a code, then redirected you to another page.
You are storing the element itself (which is an object) in the localStorage. You should store the text of the element.
Change
var codeValue = document.getElementById("code");
To
var codeValue = document.getElementById("code").textContent;
Please Note: According to Window.localStorage
The keys and the values are always strings (note that, as with objects, integer keys will be automatically converted to strings).
you need to access the text inside the element, here you are storing the html element inside the localstorage.
change the code to access the text
document.getElementById('code').innerText
In the following code:
function Transact() {
if(document.getElementById('itctobuy').value!='') {
itctobuy = parseInt(document.getElementById('itctobuy').value);
}
if(document.getElementById('steamtobuy').value!='') {
steamtobuy = parseInt(document.getElementById('steamtobuy').value);
}
if(document.getElementById('reltobuy').value!='') {
reltobuy = parseInt(document.getElementById('reltobuy').value);
}
if(document.getElementById('airtobuy').value!='') {
airtobuy = parseInt(document.getElementById('airtobuy').value);
}
if(document.getElementById('bsnltobuy').value!='') {
bsnltobuy = parseInt(document.getElementById('bsnltobuy').value);
}
updateValues();
}
The function's executed by a simple onclick of a button. There are 5 textarea elements and the user may input a number in any, and upon clicking the button the value should be stored in these vars if the textarea value isn't empty (Although it doesn't work even if the empty condition is not present).
If I remove the entire block, updateValues() executes fine, whereas putting it back causes it not be executed, so the problem's with it. What's the reason for this and how do I fix this?
Edit: The console says the following:
Uncaught TypeError: Cannot read property 'value' of null at TRANSACT at HTMLButtonElement.onclick
So what's the cause of this error? It doesn't work when I input all text fields and their values are not null.
Uncaught TypeError: Cannot read property 'value' of null
That tells you that at least one of those elements doesn't exist as of when that code runs, so getElementById returns null, which you're trying to read the value property from.
getElementById will only return null if no element with the given ID exists in the document as of when you call it. In general, the reasons for the element not existing fall into these categories:
Calling getElementById too early
Misspelling the id (e.g., a typo)
Using a name instead of an id
The element exists, but isn't in the document (rare)
In your case, since this is on button click, it's probably #2 or #3. You can see which ID it's unhappy about by looking at the line the error identifies, or using your browser's debugger to step through the code statement-by-statement.
Let's look at each category:
1. Calling getElementById too early
One common error is to have code calling getElementById in a script block that's before the element in the HTML, like this:
<script>
document.getElementById("foo").innerHTML = "bar";
</script>
<!-- ...and later... -->
<div id="foo"></div>
The element doesn't exist as of when that code runs.
Solutions:
Move the script to the end of the HTML, just before the closing </body. tag
Put your call to getElementById in a callback, such as on the DOMContentLoaded event, or a button click , etc.
Don't use window.onload or <body onload="..."> unless you really want to wait to run the code until all external resources (including all images) have been loaded.
2. Misspelling the id
This is really common, using getElementById("ofo") when the element is defined with id="foo".
Example:
<div id="foo"></div>
<script>
document.getElementById("ofo").innerHTML = "I'm foo"; // Error
</script>
Solution: Use the right ID. :-)
3. Using a name instead of an id
getElementById("foo") looks for an element with id="foo", not with name="foo". name != id.
Example:
<input name="foo" type="text">
<script>
document.getElementById("foo").value = "I'm foo"; // Error
</script>
Solution: Use id, not name. :-) (Or look up the element with document.querySelector('[name="foo"]').)
4. The element exists, but isn't in the document
getElementById looks in the document for the element. So if the element has been created, but has not been added to the document anywhere, it won't find it.
Example:
var div = document.createElement("div");
div.id = "foo";
console.log(document.getElementById("foo")); // null
It doesn't look throughout memory, it just looks in the document (and specifically, the document you call it on; different frames have different documents, for instance).
Solution: Make sure the element is in the document; perhaps you forgot to append it after creating it? (But in the example above, you already have a reference to it, so you don't need getElementById at all.)
I'm not sure how to handle the issue to get a value of the control if its ID was passed to a function from code behind.
I have a function called StateSelect that is added to a control in code behind. It has parameters. The last parameter is txtCity.ClientID.ToString()
In my html, I have this function defined as
function StateSelectedp(city, state, ddlZipName, txtCityID)
{
alert($.trim($('#txtCityID').value)); //not sure how to do it
}
I need to get a value of the txtCityID control. How can I reference it with jQuery?
Thank you
To get the value of an element with a variable ID, you can do something along the lines of the following...
function StateSelectedp(city, state, ddlZipName, txtCityID)
{
alert($('#' + txtCityID).val());
}
txtCityID is a string representing the whole ID of a given element. For jQuery to search by id, the id must be prepended by the '#' character. After the element has been selected, the val() function will return the value of the first (I think it's only first, anyways) element in the selected set of elements. There should only be one anyways, as only one element should have a given id.
Keep in mind, though, that this is all happening on the client side. Your reference to code-behind (a Web Forms term) implies that you might be intending to do something with this on the server-side, so this may or may not be the path you're really looking for.
I am doing ajax. At a certain point, I assign someproperty to a DOM object selected by id (suppose it is 12345), and I confirm that the value has been assigned by using alert():
window.document.getElementById('12345').someproperty = true;
alert(window.document.getElementById('12345').someproperty);
At this point, the alert correctly shows true. Then, at some point later, I invoke a javascript command that looks up the value of someproperty for the object:
alert(window.document.getElementById('12345').someproperty);
and this time, it shows undefined. Why is the value not defined?
I have a feeling that you're doing some nasty .innerHTML somewhere between your to lookups of .someproperty.
Assigning to .innerHTML destroys the current DOM, and replaces it with a new DOM that is obtained by parsing the HTML string you provided. So I'm guessing you're destroying an entire section, and replacing it with a nearly identical new section. This naturally wipes out the stateful information in the original DOM.
You should modify the individual DOM elements that need updating instead of wiping them out entirely using .innerHTML.
My DOM skills are weak and I can't work out why a javascript variable is assigned this object pointer value rather than the string value itself.
Short story is that I am making an AJAX call for some screen data and it returns html and populates a div.innerHTML with the following :
<input id="page_tag_add_input"></input>';
<span class="page_tag_add">Add</span>
The doTagXhr function is a YUI connection manager AJAX call.
When the user clicks add, firebug shows me that the newTag variable is stored as "[object HTMLDivElement]", yet when the alert(newTag) javascript kicks in (above), it shows the value correctly as the input text string?? I've exhausted Google searches :-(
Are there any gurus out there that can point me in the right direction? Thanks.
You're assigning newTag to a DOM Element property. I think you've mistaken what Firebug reports it as, that code indicates it's clearly not an element reference, and unless you're manipulating it in the xhr function ( which you didn't paste the code to ) then it's still a string.
Edit:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script>
function doTagXhr(page, input) {
window.input = input;
$.ajax({
url:page,
type:'POST',
data:input
});
}
</script>
<input id="page_tag_add_input" value="test">
<span class="page_tag_add">Add</span>
This always stays a string. I don't know what else it could be other than your xhr function that's reassigning the variable.