Getting value from a Input Box , Javascript, getElementById - javascript

SO i am trying to get the value or the contents of an HTML text box. I have tried various types of methods but none of them work. According to the debugger , the code stops at getelementbyid method. The commented lines are the methods that I have already tried. Some of them return null while some of them return NaN and most of them just return a blank page.
help is much appreciated.
<html>
<head>
<script type="text/javascript" >
function calculateit(){
document.open();
var number = document.getElementsByName('xyz')[0].value
//var number = document.getElementsByName("xyz").value;
//var number = document.getElementsByName('xyz').value;
//var number = document.getElementsByName("xyz");
//var number = document.getElementsByName('xyz');
//var number = document.getElementsById("xyz").value;
//var number = document.getElementsById('xyz').value;
//var number = document.getElementsById("xyz");
//var number = document.getElementsById('xyz');
//var number = document.form1.xyz.value; //form 1 was my form name and/or id
document.writeln(number);
var newtemp = 0;
var newtemp = tempera *9/5+32;
document.write(newtemp);
}
</script>
</head>
<body>
<input type="text" id="xyz" name="xyz">
<button title="calculate" onclick="calculateit()">calculate </button>
</body>
</html>

You're using the wrong method. The two widely supported methods for javascript are "getElementsByTagName" and "getElementById". Note exactly how "getElementById" is spelled. It is meant to get one element with the exact id that you specify. "getElementsByTagName" gets all elements of a certain tag...such as "div". When using "getElementById", you don't to index it or anything - it either returns null (can't find) or the exact element reference. From there, since it is a textarea, you can use ".value" to get the current value, like you already are.
ALSO:
You probably shouldn't use "document.write" or any of its related write methods AFTER the page has been rendered. In your example, that's exactly what you're doing, so once you get the ".value" stuff working, I would change that. The point is that "document.write" is more for during page rendering...so if you had javascript inline with the HTML body or something. Something like:
<html>
<head>
</head>
<body>
<script type="text/javascript">
document.write("testing");
</script>
</body>
</html>
would be fine, but still not preferred. The fact that you have it in a function, that is called on a button click, means it is not during page render, and shouldn't be used. A more practical approach is to have a <div> on the page and add text to it when necessary, using something like ".innerHTML". That way, things are dynamic and not overwritten in the actual document.

It's getElementById, not getElementsById.

Related

Document.querySelector returns a NULL value - script is at bottom of page

I am trying to get the patientNumber (ClinicA100-PF-TR1-P1) using querySelector. I keep getting a NULL value. The patientNumber is at the top of the page and the script is at the bottom. Even after the page is loaded, I click a button that runs the function and it still returns a NULL value.
Here is a screenshot of the selectors (https://recordit.co/IypXuuXib0)
<script type="text/javascript">
function getPatientNumber(){
var patientNumber = document.querySelector("patientNumber");
console.log(patientNumber);
console.log("hello");
return patientNumber;
}
var patientNumber = getPatientNumber();
console.log(patientNumber);
_kmq.push(['identify', patientNumber]);
</script>
Thank you for any help you can provide.
ADDITIONAL HTML INFORMATION:
I am using Caspio (database management software) to create this HTML code. I don't know if that may be the cause of the issue. Here is the HTML CODE.
<p class="sponsorName" id="sponsorNameID">[#authfield:User_List_Sponsor_Name]</p>
<p class="clinicNumber" id="clinicNumberID">[#authfield:User_List_Site_Number]</p>
<p class="protocolNumber" id="protocolNumberID">[#authfield:User_List_Protocol_Number]</p>
<p class="patientNumber" id="patientNumberID">[#authfield:User_List_Patient_Number]</p>
You are missing a dot.
var patientNumberNode = document.querySelector(".patientNumber");
var patientNumber = patientNumberNode.innerText;
if you select the item with class".", if you select with id, you should use"#".
var patientNumber = document.querySelector(".patientNumber"); // class select
var patientNumber = document.querySelector("#patientNumber"); // id select
Your selector is incorrect. It should be
var patientNumber = document.querySelector(".patientNumber");
Why is it failing:
When you use patientNumber as the selector, JavaScript looks for an element with a name of patientNumber. Since that's not the case, and you are looking for an element with a class of patientNumber, you need to use the . notation.
Addon Suggestion (can be ignored):
Since you are also using IDs, consider using document.getElementById() as it is faster than using document.querySelector().
Note that if you use document.getElementById(), your .patientNumber selector won't work. You need to write it as
document.getElementById('patientNumberID');
//ID based on the screenshot of the DOM you've shared
While the code is at the bottom of the page, and the element is at the top, it is not loaded asynchronously as it comes from a third party database. i put a delay in the getPatientNumber() and it works now.

How to add response body to Html [duplicate]

This should be a pretty easy thing to do, but it's not returning anything.
The function love() should kick off, getting a simple number prompt, and spitting out a list of a few items that uses that starting number.
the alert box correctly displays what I expect, but I want it to display on the screen.
(this is but a small section of what I'm after, but it's the kernel of it). No text is displaying in the IE, FF, or Chrome...
<script type="text/javascript">
function love()
{
var ncxElement="";
var idNumber = prompt("Enter beginning number","");
var myText=document.getElementById("here");
for (var i=1;i<5;i++)
{
ncxElement+=("<navPoint class=\"other\" id=\"page_"+idNumber+"\">\n");
idNumber++;
}
alert(ncxElement);
myText.innerHTML=ncxElement;
}
</script>
</head>
<body onload="love()">
<p id="here">Begin!</p>
</body>
If you want to display HTML on your page (without it being parsed), use .textContent instead of .innerHTML and wrap it in a <pre> (to preserve the line breaks).
Demo:
Change:
myText.innerHTML=ncxElement;
To:
myText.textContent=ncxElement;
Change:
<p id="here">Begin!</p>
To:
<pre id="here">Begin!</pre>
navPoints are not valid html elements, so the browser doesn't know what to do with them. They are being added to the DOM, just not displayed unless you add styling to do so.
If you replace them with paragraph tags, it works fine. See the example here.
<script type="text/javascript">
function love()
{
var ncxElement="";
var idNumber = prompt("Enter beginning number","");
var myText=document.getElementById("here");
for (var i=1;i<5;i++)
{
ncxElement+=("<p class=\"other\" id=\"page_"+idNumber+"\">"+idNumber+ "</p>");
idNumber++;
}
alert(ncxElement);
myText.innerHTML=ncxElement;
}
</script>
</head>
<body onload="love()">
<p id="here">Begin!</p>
</body>
Your function just wraps elements inside another. There is no text inside or outside these elements to dipslay.
Try inserting some random text before closing tags to see the result.
Btw, the elements are successfully placed in the p tag.

Creating a div within an existing div in javascript issues

I have a problem, I wanted to create a div in html as a container and in javascript create new divs within the container based on a number input from a user prompt.
My html and javascript look like this.
HTML:
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="stylesheet.css">
<title>Sketchpad</title>
</head>
<body>
<button type="button">Reset</button>
<div class= "container">
</div>
<script src="javascript.js"></script>
<script src="jQuery.js"></script>
</body>
JS
var row = prompt("Enter number of rows:");
var column = prompt("Enter number of columns:");
function createGrid(){
var cont = document.getElementsByClassName('container');
for(i=1; i<column; i++){
var sketchSquare = document.createElement('div');
cont.appendChild(sketchSquare);
}
}
createGrid(column);
I end up with this error: Uncaught TypeError: cont.appendChild is not a function.
I imagine this is something to do with the getElementsByClassName?
I do have a solution which involves creating the container div in javascript and appending the smaller squares inside the container div. I was just curious as to why my first soltuion didn't work?
cont[0].appendChild(myDiv) is a function.
When you document.getElements By Class Name as the name implies you are getting many elements (an array of sorts) of elements and this array don't have the same functions as each of its elements.
Like this:
var thinkers = [
{think: function(){console.log('thinking');}
];
thinkers don't have the method .think
but thinkers[0].think() will work.
try this: open your javascript console by right clicking and doing inspect element:
then type:
var blah = document.getElementsByClassName('show-votes');
blah[0].appendChild(document.createElement('div'));
It works!
also if you want to use jQuery which I do see you added...
you can do:
var cont = $('container');
cont.append('<div class="sketchSquare"></div>');
Try that out by doing this:
First get an environment that has jQuery.
Hmm maybe the jQuery docs have jQuery loaded!
They do: http://api.jquery.com/append/.
Open the console there and at the bottom where the console cursor is type:
$('.signature').append('<div style="background: pink; width: 300px; height: 300px"></div>');
You'll notice that you add pink boxes of about 300px^2 to 2 boxes each of which have the "signature" class.
By the way, prompt gives you a string so you'll have to do row = Number(row); or row = parseInt(row, 10); and another thing don't use that global i do for(var i = 0; ...
var cont = document.getElementsByClassName('container');
Because that^ doesn't return a node, it'll return an HTMLCollection.
https://www.w3.org/TR/2011/WD-html5-author-20110705/common-dom-interfaces.html#htmlcollection-0
You need to pick an individual node from that collection before appending.
There could be a couple of issues that could cause this. Without fully giving the answer here's what it could be at a high level.
Your script is ran before the DOM is fully loaded. Make sure that your script is ran after the DOM is present in the page. This can be accomplished using either the DOMReady event ($(document).ready equivalent without jQuery) or simply making sure your script tag is the last element before the closing body tag. (I usually prefer the former)
When you utilize document.getElementsByClassName('container') (https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName) this method returns an array therefore you would either need to apply the operation to all elements of the result or just select the zero-th as document.getElementsByClassName('container')[0]. As an alternative, if you would like to be more explicit you could also place an id on the container element instead to more explicitly state which element you would like to retrieve. Then, you would simply use document.getElementById([id]) (https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById) and this would get back a single element not a collection.
The result of prompt is a string. Therefore you would have to first parse it as an integer with parseInt(result, 10) where 10 is simply the radix or more simply you want a number that is from 0-10.
You should include jquery library before your script, it`s important
<script src="jQuery.js"></script>
<script src="javascript.js"></script>

Javascript, viewing [object HTMLInputElement]

I'm just started to learn HTML. Doing an alert() on one of my variables gives me this result [object HTMLInputElement].
How to get the data, that were added in text field, where my input type is text?
Say your variable is myNode, you can do myNode.value to retrieve the value of input elements.
Chrome Developer Tools has a Properties tab which shows useful DOM attributes.
Also see MDN for a reference.
If the element is an <input type="text">, you should query the value attribute:
alert(element.value);
See an example in this jsFiddle.
Also, and seeing you're starting to learn HTML, you might consider using console.log() instead of alert() for debugging purposes. It doesn't interrupt the execution flow of the script, and you can have a general view of all logs in almost every browser with developer tools (except that one, obviously).
And of course, you could consider using a web development tool like Firebug, for instance, which is a powerful addon for Firefox that provides a lot of functionalities (debugging javascript code, DOM inspector, real-time DOM/CSS changes, request monitoring ...)
It's not because you are using alert, it will happen when use document.write() too. This problem generally arises when you name your id or class of any tag as same as any variable which you are using in you javascript code. Try by changing either the javascript variable name or by changing your tag's id/class name.
My code example:
bank.html
<!doctype html>
<html>
<head>
<title>Transaction Tracker</title>
<script src="bank.js"></script>
</head>
<body>
<div><button onclick="bitch()">Press me!</button></div>
</body>
</html>
Javascript code:
bank.js
function bitch(){ amt = 0;
var a = Math.random(); ran = Math.floor(a * 100);
return ran; }
function all(){
amt = amt + bitch(); document.write(amt + "
"); } setInterval(all,2000);
you can have a look and understand the concept from my code. Here i have used a variable named 'amt' in JS. You just try to run my code. It will work fine but as you put an [id="amt"](without square brackets) (which is a variable name in JS code )for div tag in body of html you will see the same error that you are talking about.
So simple solution is to change either the variable name or the id or class name.
change:
$("input:text").change(function() {
var value=$("input:text").val();
alert(value);
});
to
$("input:text").change(function() {
var value=$("input[type=text].selector").val();
alert(value);
});
note: selector:id,class..
<input type="text" id="name">
and in javascript
var nameVar = document.getElementById("name").value;
alert(nameVar);
<input type="text" />
<script>
$("input:text").change(function() {
var value=$("input:text").val();
alert(value);
});
</script>
use .val() to get value of the element (jquery method), $("input:text") this selector to select your input, .change() to bind an event handler to the "change" JavaScript event.
When you get a value from client make and that a value for example.
var current_text = document.getElementById('user_text').value;
var http = new XMLHttpRequest();
http.onreadystatechange = function () {
if (http.readyState == 4 && http.status == 200 ){
var response = http.responseText;
document.getElementById('server_response').value = response;
console.log(response.value);
}

innerHTML side effects?

I'm having some issues with a DOM element reference and I think I've tracked it down to having something to do with updating innerHTML.
In this example, at the first alert, the two variables refer to the same element, as expected. What's strange though is that after updating the innerHTML of the parent element (body), the two variables are supposedly different, despite not touching either.
<html>
<head>
<script type="text/javascript">
var load = function () {
var div1 = document.createElement('div');
div1.innerHTML = 'div1';
div1.id = 'div1';
document.body.appendChild(div1);
alert(div1 === document.getElementById('div1')); // true
document.body.innerHTML += '<div>div2</div>';
alert(div1 === document.getElementById('div1')); // false
};
</script>
</head>
<body onload="load();">
</body>
</html>
Using == instead of === produces the same results. I get the same results in Firefox 3.5 and IE6. Any idea what's causing the second alert to evaluate to false?
WHen you get the innerHTML value of the body, add a string to it and put it back in the body, all elements in the body is recreated from the HTML string. What you have in the variable is a reference to an element that no longer exists in the page.
This is because ...
document.body.innerHTML += '<div>div2</div>';
... is not a true "append" .. it's a full replacement. Granted, the replacement is equal to the old content + the new content, the fact is that it is a new string which new DOM elements are built around.

Categories