Unable to read input DOM element's value - javascript

i have following html/JS code :
function controller()
{
document.write(document.getElementById("name").value) ;
document.write(document.getElementById("id").value) ;
}
<input type="text" id="name"/>
<input type="text" id="id"/>
<input type="button" id="push" onclick="controller()"/>
Problem : when i click on push button onclick is fired and controller function is executed and i am able to retrieve value of element having id name but the second element having id idis not read and as a result i get the following error for second input element :
Uncaught TypeError: Cannot read property 'value' of null
I have been struggling for hours but i am unable to understand where i am making mistake can somebody help ?

Your script read the inputs values correctly, but when the first document.write statement execute it will override the body so when the script try to execute the second one it will find no input and return the error line :
Uncaught TypeError: Cannot read property 'value' of null
Hope this helps.
function controller()
{
console.log(document.getElementById("name").value);
console.log(document.getElementById("id").value);
}
<input type="text" id="name"/>
<input type="text" id="id"/>
<input type="button" id="push" onclick="controller()"/>

the problem is that document.write erases the body you can instead use 'alert()' or add another element to dom and set its innerHTML to the values:
function controller(){
alert(document.getElementById("name").value) ;
alert(document.getElementById("id").value) ;
}
OR
<input type="text" id="name"/>
<input type="text" id="id"/>
<input type="button" id="push" onclick="controller()"/>
<div id="result"></div>
javascript
var ele=document.querySelector("#result");
function controller(){
ele.innerHTML="Name :"+document.getElementById("name").value+"<br>Id: "+document.getElementById("id").value;
}

document.write(document.getElementById("name").value); is replacing your entire dom, so the subsequent getElementById can't retrieve the input value. Store all of the values before you write them back to the document.
function controller(){
var store = [];
store.push(document.getElementById("name").value);
store.push(document.getElementById("name2").value);
document.open();
document.write(store);
document.close();
}

The problem is that document.write is "clearing" the page.
The input's aren't anymore on the page, after the first document.write
Detailed Information can be found on the MDN under this link https://developer.mozilla.org/en-US/docs/Web/API/Document/write
Which states:
Note: as document.write writes to the document stream, calling
document.write on a closed (loaded) document automatically calls
document.open, which will clear the document
try instead alert() or console.info() or other functions that don't clear the document.
function controller()
{
alert(document.getElementById("name").value) ;
alert(document.getElementById("id").value) ;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<input type="text" id="name"/>
<input type="text" id="id"/>
<input type="button" id="push" onclick="controller()"/>
</body>
</html>
tested on Win7 with chrome 51+
Optional:
If you want/have to use document.write, read first all values and that write them to the document.
function controller()
{
var firstField = document.getElementById("name").value;
var secondField = document.getElementById("id").value;
document.write(firstField);
document.write(secondField);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<input type="text" id="name"/>
<input type="text" id="id"/>
<input type="button" id="push" onclick="controller()"/>
</body>
</html>
tested on Win7 with chrome 51+
Info: The better way to attach Events is to attach them over an
Eventlistener here is an link to the addEventListener Reference
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

Related

Why the button object can not use the onclick() function?

I am trying to use javascript to create a web calculator. I hope that users can calculate the result when they click the different buttons. However, there is an error in line16(Uncaught TypeError: Cannot read property 'onclick' of null). I hope someone could help me. These are my codes:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
</style>
<script type="text/javascript">
var btnadd,btnsub,btnmul,btndiv;
btnadd = document.getElementById('btnadd');
btnsub = document.getElementById('btnsub');
btnmul = document.getElementById('btnmul');
btndiv = document.getElementById('btndiv');
btnadd.onclick() = function(){
cal(add());
}
function cal(func){
var num1 = document.getElementById('num1').value;
var num2 = document.getElementById('num2').value;
parseFloat(num1);
parseFloat(num2);
var result;
result = func(num1,num2);
document.getElementById('result').value = result;
}
function add(num1,num2){
return (num1+num2);
}
function sub(num1,num2){
return (num1-num2);
}
function mul(num1,num2){
return (num1*num2);
}
function div(num1,num2){
return (num1/num2);
}
</script>
</head>
<body>
<form>
num1:<input type="text" id="num1" /><br>
num2:<input type="text" id="num2" /><br>
<input type="button" id="btnadd" value="add" />
<input type="button" id="btnsub" value="sub" />
<input type="button" id="btnmul" value="mul" />
<input type="button" id="btndiv" value="div" /><br>
result:<input type="text" id="result"/>
</form>
</body>
</html>
You need to either add the defer attribute to your script or put it at the end of the body.
Putting JS code in the head means that it will be run before the page is fully parsed. That means that there is no element with the id of btnadd just yet. If you add the defer attribute, then it will wait for the page to be parsed before running the script. Putting at the end of the body has the same effect.
In terms of your code itself, you need to set the onclick property. You cannot assign a function like that. Also, do val2 = parseFloat(val2) rather than parseFloat(val2). (similarly for val1) because here you need to reassign the value
Because you didn't define the onclick correctly
Instead of
btnadd.onclick() = function(){
cal(add());
}
try
btnadd.onclick = function(){
cal(add);
}
Check this codepen : https://codepen.io/zecka/pen/NWrejxO
Note that there are other errors in your code that will prevent you from making it work as you want.

Javascript passing data between text boxes

I'm working on getting data to go from one textbox to another using javascript. Im new to Javascript and im getting a document undefined or null error.
<!DOCTYPE html>
<html>
<head>
<script>
function doit() {
window.document.form1.txtbox1.value= window.document.form2.txtbox2.value;
}
</script>
</head>
<body>
<form name="form1">
Enter your name:
<input type="text" name="txtbox1" value="">
<input type="button" name="btn1" value="Click" onclick="doit()">
</form>
<br><br><br>
<form name="form2">
Results:
<input type="text" name="txtbox2" value="">
</form>
</body>
</html>
It seems that you are trying access the element as a property of the DOM.
Instead, you should use document.getElementsByName method.
Revised function:
function doit(){
// The [0] is for accessing the first item.
// If you are unfamiliar with arrays, visit
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
document.getElementsByName("txtbox1")[0].value = document.getElementsByName("txtbox2")[0].value;
}
You need to switch (swap) them :
window.document.form1.txtbox1.value= window.document.form2.txtbox2.value;
When you click a button - you set the value of the second input to the first one and probably the second input called 'Result' is empty.
Try:
function doit() {
window.document.form2.txtbox2.value = window.document.form1.txtbox1.value;
}
There should not be any error, it's just pass data in another direction as you probably expect.
Give a unique ID to both the input element.
<input type="text" id="txtbox1" value="">
<input type="text" id="txtbox2" value="">
and in function doit()
document.getElementById("txtbox2").value = document.getElementById("txtbox1").value

Getting HTML DOM element and setting it to a value of a input tag

There is an element on my page with the id last_name. I would like to get its value and pass it along to my input tag.
I am essentially trying to do something like this (doesn't work).
<input type="hidden" name="lastName" value=document.getElementById("last_name").value>
Is there anyway to do this?
This is not only on load.
Essentially, I have a bunch of textboxes grouped together in a form.
Then I have another form with a button. When the user hits the button, I want my input tags' values be the current values entered in the textboxes.
EDIT: Thanks all! Got it work. I essentially had to remove the "value" attribute of the input tags and then add an "onclick" attribute to my button and then call those javascript codes you guys provided me.
for only loading page:
<!DOCTYPE html>
<html>
<head>
<!-- link here your JQuery library -->
<script>
$(function(){
$('#lastName').val($('#last_name').val());
});
</script>
</head>
<body>
<input type="text" id="last_name" value="123">
<input type="hidden" name="lastName" value="">
</body>
</html>
for button click:
<!DOCTYPE html>
<html>
<head>
<!-- link here your JQuery library -->
<script>
$(function(){
$('#btn-save').on('click', function() {
$('#lastName').val($('#last_name').val());
// other work
return false;
}
});
</script>
</head>
<body>
<input type="text" id="last_name" value="123">
<input type="hidden" name="lastName" value="">
<button id="btn-save">Save</button>
</body>
</html>
without jQuery use:
<script>
window.onload = function(){
var src = getElementById('last_name');
var dst = getElementById('lastName');
dst.value = stc.value;
}
</script>
Try this:
var lastName = document.getElementById("last_name");
var input = document.getElementById("yourInputId");
input.value = lastName.value;
Try the following code
HTML
<input type="hidden" name="lastName" id='hidLastName' />
and javascript code:
var input = document.getElementById("hidLastName")
input.value = document.getElementById("last_name").value
You should move the logic to a .js file or inside a <script></script> element. Preferrably the former. Try something like this:
Put an id to the receiving input:
<input type="hidden" id="lastName" name="lastName">
And this to your .js file
window.onload = function(){
var lastNameInput = document.getElementById('lastName');
var sourceInput = document.getElementById('last_name');
lastNameInput.value = sourceInput.value;
}
Try This:
Java Script
<script>
function setInput() {
document.getElementById("lastname").value = document.getElementById("last_name").value;
}
</script>
HTML
<input type="text" id="last_name" onblur="setInput()"/>
<input type="hidden" id="lastname" />

HTML-form submit button not running the OnSubmit script associated with it

I'm making a chrome extension, and so far I'm just testing some things. The HTML for the extension is this:
<!doctype html>
<html>
<head>
<title>Title</title>
<script src="processform.js"></script>
</head>
<body>
<form name="myform" onSubmit="ExampleJS()">
First name: <input type="text" id="fname" name="firstname" /><br />
Last name: <input type="text" id="lname" name="lastname" /><br />
<input name="Submit" type="submit" value="Update" />
</form>
</body>
</html>
The processform.js file is this:
function ExampleJS(){
var jFirst = document.getElementById("fname").value;
var jLast = document.getElementById("lname").value;
alert("Your name is: " + jFirst + " " + jLast);
}
When I press the submit button the alert doesn't appear.
You cannot use inline code in a Chrome extension due to its Content Security Policy, and setting onsubmit in the element counts as inline.
A jQuery-based solution (you will need to include jQuery with the extension and add it to the page, but there's no harm in that):
// processform.js
$(document).ready(function(){
// Bind from JS, not inline
$("form").submit(ExampleJS);
});
A pure JavaScript solution would be:
// processform.js
document.addEventListener('DOMContentLoaded', function(){
// Bind from JS, not inline
document.forms["myform"].addEventListener('submit', ExampleJS);
});
Please put the following code -
$(document).ready(function(){
$("form").submit(ExampleIS);});
This should work.

html form.input.value is not getting printed why?

...
<script type="text/javascript">
function printvalues() {
document.write("This is my first JavaScript!");
document.write(form.inputobj1.value);
document.write(form.inputobj2.value);
}
</script>
<form name="form">
<input name="inputobj1" value="123" />
<input name="inputobj2" value="abc"/>
<input type="button" onclick =" printvalues();">
</form>
why this line is not printing the value document.write(form.inputobj1.value);
The document.write overwrites the current document. Once done that, the whole <form> element disappears from the DOM and hence it and its input elements cannot be found.
Replace document.write(...) by for example alert(...) and it should work.
Alternatively you can write it as innerHTML of another element. E.g.
<script type="text/javascript">
function printvalues() {
var div = document.getElementById("divId");
div.innerHTML += "This is my first JavaScript!";
div.innerHTML += form.inputobj1.value;
div.innerHTML += form.inputobj2.value;
}
</script>
<form name="form">
<input name="inputobj1" value="123" />
<input name="inputobj2" value="abc"/>
<input type="button" onclick =" printvalues();">
</form>
<div id="divId"></div>
Note that this is not the "best practice", but since you're learning... When done with core Javascript, I recommend you to get yourself through jQuery. It's a Javascript library which greatly eases DOM manipulation like that and more ;)
document.write()
is probably not what you want. It will overwrite the entire contents of the page. The reason you're getting that error is because when you call document.write, it removes all the previous content, and thus the page will no longer have a form element.
Normally you would use a function such as document.getElementById to get a DOM element. For example:
alert( document.getElementById('inputobj1_id').value );
For DOM element:
<input id="inputobj1_id" name="inputobj1" value="123" />
<script type="text/javascript">
function printvalues() {
var x = document.form.inputobj1.value;
var y = document.form.inputobj2.value
document.write("<Html><head></head><body><h1>");
document.write("This is my first JavaScript!</h1></br><h3>");
document.write(x);document.write("</h3></br><h3>");
document.write(y);document.write("</h3></body></html>");
}
</script>
<form name="form">
<input name="inputobj1" value="123" />
<input name="inputobj2" value="abc"/>
<input type="button" value="click" onclick =" printvalues();">
</form>

Categories

Resources