javascript variable undefined or null - javascript

couldn't find a specfic answer elsewhere. I'm totally new to JS and trying to pull a value out of a form and write it to the page. The result when I try to write ProductName is undefined, and when I try to write ProductNameElement is null. I'm sure it's to do with the form values being empty when the page loads but not sure after that...
<script>
var ProductNameElement = document.getElementById("ProductName");
var ProductName = ProductNameElement.value;
function showname(){
document.write(ProductName);
}
</script>
<h2>Revenues</h2>
<div class="number">Product Name: <input type="text" id="ProductName" value=""></input></div>
<input type="button" value"showname" onclick="showname();"></input>

You are running the first two lines of your script too early BEFORE the elements in your page have been parsed and placed into the DOM. Because of that, the ProductName element doesn't exist yet when you're trying to find it with document.getElementById("ProductName");.
Place your script right before the </body> tag and then all your page elements will be available when you run your script. Or, just put all your code in the showname function that isn't called until the click event.
function showname(){
var ProductNameElement = document.getElementById("ProductName");
var ProductName = ProductNameElement.value;
document.write(ProductName);
}
And, as others have said, using document.write() after the documented has been loaded will cause the existing document to be cleared and a new empty document will be created. This is pretty much never what you want. If you're just doing this for debugging, use console.log(ProductName) and look at the debug console.

You'll have to get the element and the value inside the function, otherwise they aren't available, and the change of the value isn't caught
<script>
function showname(){
var ProductNameElement = document.getElementById("ProductName");
var ProductName = ProductNameElement.value;
document.write(ProductName);
}
</script>
<h2>Revenues</h2>
<div class="number">
Product Name: <input type="text" id="ProductName" value="" />
</div>
<input type="button" value"showname" onclick="showname();" />
FIDDLE
And inputs are self closing, and you should stop using document.write, it will overwrite the entire document and remove everything that is currently there !

Related

Converting text to lowercase/uppercase with a pending a radio button

I am writing a Javascript program that takes a users input text, then (pending a radio button check – lowerCase/UpperCase) converts the input text to either lowercase/upperCase and outputs the value back to the form.
Purely trying to learn on my own Javascript. I am moderately new (but savvy) to JS. Pretty solid on HTML, CSS, Java, but BRAND new with interacting with page elements.
I have dug around for two days to try and solve this. I have even checked out a few books at my local library. (Currently reading the text, Microsoft guide to CSS/HTML, and JS). What other books would you recommend in order to under JS more?
Here is the code below. Although I know one can use CSS in order to convert this and I have done this. I'm purely just wanting to figure out Javascript.
<!DOCTYPE html>
<html>
<head>
<title> Case Changer By: Elliot Granet</title>
<style>
function convert(){
var convertedText = document.test.input.value;
if(document.getElementById("lowerCase").checked = true){
var output = convertedText.toLowerCase();
}else {
output = convertedText.toUpperCase();
}
document.getElementById('outputText').value = output;
}
convert();
</head>
The rest -
<body>
<h3>Choose your Conversion method below:</h3>
<form action="getElementById">
<fieldset>
<input id="lowerCase" type="radio" name="case" value="lowerCase">Lower Case<br>
<input id ="upperCase" type="radio" name="case" value="upperCase">Upper Case<br><br>
</fieldset>
<fieldset>
<textarea id="inputText" name="input" form="inputText">Enter text here to be Converted...</textarea>
</fieldset><br>
<fieldset>
<textarea id ="outputText" name="output" form="outputText">Converted text will appear here...</textarea>
</fieldset>
<input type="button" value="Convert">
</form>
</body>
</html>
You need to make few changes to make this function work.
style is an invalid tag to put js code. You need to put it inside <script> tag
If you are writing this function inside header yo may come across error since before DOM is ready it will try to get value of textarea with id inputText.
document.getElementById(idName').value but not is right syntax to get the value of element using id
Attaching convert() with the button. So when you will click on button the function will execute.
5.document.getElementById("lowerCase").checked = true this is wrong.It mean that checkbox will get checked as = will assign the value . Instead you need to compare the value. So use == or ===
if you declare var output inside if loop it wont be available inside else. So you need to declare it outside the if-else loop
Hope this snippet will be useful
HTML
<input type="button" value="Convert" onclick="convert()">
JS
window.load =convert; // convert function will be called after window is ready
function convert(){
var output; //variable declaration outside if-else loop
var convertedText = document.getElementById('inputText').value; //document.getElementById
if(document.getElementById("lowerCase").checked == true){ // == comparision
output = convertedText.toLowerCase();
}
else {
output = convertedText.toUpperCase();
}
document.getElementById('outputText').value = output;
}
EXAMPLE

Can not copy data of HTML tags to JavaScript

For some reasons I am trying to change functionality of submit button. I am facing problem in copying data from HTML tags to JS. The alert generated by following code prints "Undefined" not the data inside tag.
<html>
<body>
<input class="inputtext" id="email" name="email" type="text"></div>
<input value="Submit" name="v4l" id="login" class="inputsubmit" type="button" onclick="myFunction();return false">
<script>
function myFunction() {
var TestVar =document.getElementsByClassName('login').value;
alert(TestVar);
}
</script>
</body>
</html>
I know it can be done by form but I need it this way.
try
var TestVar = document.getElementById('email').value
alert(TestVar);
this will get value of text field
getElementsByClassName
^
See that s? Elements is plural. getElementsByClassName returns a NodeList (which is like an Array).
You have to either pick an index from it (foo[0]) or loop over it to get the values.
That said, you don't actually have any elements that are a member of the login class, so it is going to return a Node List of zero length.
You do have an element with id="login", so maybe you should use getElementById instead.
There doesn't seem much point in reading the value from an element that you've hard coded the value for. You might actually want to be using document.getElementById('email')

Unable to set val of hidden input field

I have this following code, I am trying to set value of hidden field with java script.
<script type="text/javascript" language="javascript">
var currentTime = new Date();
var tday=currentTime.getDate();
var tmonth=currentTime.getMonth();
var tyear=currentTime.getFullYear();
$("input[name='tday'").val(tday);
$('#tmonth').val(tmonth);
$('#tyear').val(tyear);
document.getElementById('tday').value='213';
</script>
<div id="edit_bs" class="edit_bs_st">
<form id='edir_pers' class='edit_pers_css' name='edit_pers' action='edit_pers.php' method='post'>
<input id='tyear' name='tyear'/>
<input id='tmonth' type='hidden' name='tmonth' />
<input id='tday' type='hidden' name='tday' />
<button type="submit">Submit</button></from>
The problem is that the value are not being passed to the 'edit_pers.php' they are blank. I have even tried document.getlementid.value to set the value but nothing works. I dont know what is wrong with my code.
hidden doesn't have anything to do with it. It's your call to the element that is bad.
THIS IS YOURS: BROKEN
$("input[name='tday'").val(tday);
THIS IS FIXED
$('input[name=tday]').val(tday);
Here's the result.
$(document).ready(function () {
var currentTime = new Date();
var tday=currentTime.getDate();
$('input[name=tday]').val(tday);
}):
As a side note, you don't need the redundant identifiers in your code. I'd personally go with this since you are probably required to have the name attribute.
HTML
<input type='hidden' name='tday' />
Javascript
$('input[name=tday]').val(tday);
http://jsfiddle.net/Uh7yn/
A part of your problem is that your code runs before the elements exists in the DOM.
Since you are using jQuery, the best way to circumvent this issue would be to use the document.ready handler. However, you will have to make sure that jQuery is loaded on the page.
$(function () {
//since your inputs have ids, you do not have to use any attribute selectors
$('#tday').val(213);
});
Also, you have a typo in the closing form tag.

Uncaught TypeError: Cannot set property 'value' of null

I'm trying to pass the entered text to the controller using an ajax request. But i'm getting athe error "Uncaught TypeError: Cannot set property 'value' of null " when I tried to execute JS file..
Here is the HTMLcode:
<form action="">
<input type="text" class="searchbox1" name="search" placeholder="Search for Brand, Store or an Item..." value="text" />
<input type="button" class="searchbox_submit1" name="submit" value="text" onClick="javascript:getSearchText();">
</form>
Here is the JS code:
function getSearchText() {
var searchText = document.getElementByName("search").value;
h_url=document.getElementById("u").value;
var theURL = h_url+'search_all/' + deptid + '/' + searchText + '/1';
$.ajax({
url : theURL,
fail: function(){
},
success : function() {
},
error:function(){
}
});
}
Please help me to fix this.
You don't have an element with the id u.That's why the error occurs.
Note that you are trying to get the value of the input element with the name 'u' and it's not defined in your code.
The problem may where the code is being executed. If you are in the head of a document executing JavaScript, even when you have an element with id="u" in your web page, the code gets executed before the DOM is finished loading, and so none of the HTML really exists yet... You can fix this by moving your code to the end of the page just above the closing html tag. This is one good reason to use jQuery.
In case anyone landed on this page for a similar issue, I found that this error can happen if your JavaScript is running in the HEAD before your form is ready. Moving your JavaScript to the bottom of the page fixed it for my situation.
The problem is that you haven't got any element with the id u so that you are calling something that doesn't exist.
To fix that you have to add an id to the element.
<input id="u" type="text" class="searchbox1" name="search" placeholder="Search for Brand, Store or an Item..." value="text" />
And I've seen too you have added a value for the input, so it means the input is not empty and it will contain text. As result placeholder won't be displayed.
Finally there is a warning that W3Validator will say because of the "/" in the end. :
For the current document, the validator interprets strings like according to legacy rules that break the expectations of most authors and thus cause confusing warnings and error messages from the validator. This interpretation is triggered by HTML 4 documents or other SGML-based HTML documents. To avoid the messages, simply remove the "/" character in such contexts. NB: If you expect <FOO /> to be interpreted as an XML-compatible "self-closing" tag, then you need to use XHTML or HTML5.
In conclusion it says you have to remove the slash. Simply write this:
<input id="u" type="text" class="searchbox1" name="search" placeholder="Search for Brand, Store or an Item...">
I knew that i am too late for this answer, but i hope this will help to other who are facing and who will face.
As you have written h_url is global var like var = h_url; so you can use that variable anywhere in your file.
h_url=document.getElementById("u").value;
Here h_url contain value of your search box text value whatever user has typed.
document.getElementById("u");
This is the identifier of your form field with some specific ID.
Your Search Field without id
<input type="text" class="searchbox1" name="search" placeholder="Search for Brand, Store or an Item..." value="text" />
Alter Search Field with id
<input id="u" type="text" class="searchbox1" name="search" placeholder="Search for Brand, Store or an Item..." value="text" />
When you click on submit that will try to fetch value from document.getElementById("u").value; which is syntactically right but you haven't define id so that will return null.
So, Just make sure while you use form fields first define that ID and do other task letter.
I hope this helps you and never get Cannot set property 'value' of null Error.
guys This error because of Element Id not Visible from js Try to inspect element from UI and paste it on javascript file:
before :
document.getElementById('form:salesoverviewform:ticketstatusid').value =topping;
After :
document.getElementById('form:salesoverviewform:j_idt190:ticketstatusid').value =topping;
Credits to Divya Akka .... :)
It seems to be this function
h_url=document.getElementById("u").value;
You can help yourself using some 'console.log' to see what object is Null.
h_url=document.getElementById("u") is null here
There is no element exist with id as u
Add defer to your script tag, if it's in header. It will allow your script to execute after the DOM is loaded.
<script src="script.js type="text/javascript"></script>
It should look like this:
<script src="script.js type="text/javascript" defer></script>

How to refer to a javascript variable in a value field?

I'd like to refer to a variable ("special") in field later in the same script. I've gotten the variable to display with alert boxes and document.write, but don't now how to make to apply its value to the value field in
var special=(10000-health);
var health=(100);
<input style="background:#FF7777;" readonly="readonly" type="text" value="special" id="special" />
this just writes "special" to the box, when I would like the value instead.
You have to set the value explicitly:
document.getElementById('special').value = special;
Note: You can only access the element after it was parsed in the DOM. To be sure, you can insert this part of the script after the element in the HTML. Often JavaScript code is added just before the closing body tag or is only executed when the load event fires. For more information, see Where to place JavaScript in a HTML file.
Update: Here is an example:
<body>
<input style="background:#FF7777;" readonly="readonly" type="text" value="special" id="special" />
<script type="text/javascript">
var health = 100;
var special = 10000 - health;
document.getElementById('special').value = special;
</script>
</body>
References: getElementById, DOM
MDC's JavaScript Guide is also worth reading.
document.getElementById('special').value = special;
you have to use some kind of DOM manipulation. One of the more popular libraries is JQuery.
using jQuery you'd write something like
$('#special').val(special);
var input = document.getElementById('special');
input.value = special;

Categories

Resources