IE11 Unable to get property 'value' of undefined or null reference - javascript

it's seems that I'm having a frustrating problem and can't seem to find an answer.
I'm trying to get the value of the element in <td> tag. The id reaches the function but for some reason I can't get the value of it.
JS
function f(id)
{
console.log(id);
expr=/ /gi;
value = document.getElementById(id).value;
value = value.replace(expr, "");
//remaining code
}
PHP
print "<td style=\"height:20px;\"><input $disbled type=\"text\" name=\"".$values[$i][0]."\" onChange=\"return f('".$values[$i][0]."')\" value=\"".$values[$i][1]."\" class=\"".$values[$i][2]."\"></td>\n";
Any help would be appreciated!

A couple of problems there:
Your element doesn't have an id at all
Your code is falling prey to The Horror of Implicit Globals (that's a post on my anemic little blog).
Here's a fixed version:
function f(name)
{
console.log(name);
var expr=/ /gi;
var value = document.querySelector('[name="' + name + '"]').value;
value = value.replace(expr, "");
//remaining code
}
#1 is fixed by using querySelector and an attribute selector selecting by name
#2 is fixed by declaring the local variables in f
You could also fix #1 by giving your element an id and sticking with getElementById.

The input you are trying to access has not ID property defined. You shall add it in order to access the input object via getElementById().
<input $disbled id=\"".$id."\" type=\"text\" name=\"".$values[$i][0]."\" onChange=\"return f('".$values[$i][0]."')\" value=\"".$values[$i][1]."\" class=\"".$values[$i][2]."\">

Related

Javascript:How to getElementById from element created dynamically by script

I am playing around some code where I want to access the element which is created dynamicaaly by script. When I am trying to access this by using getElementById it is responding with
TypeError: ...getElementById is not a function.
code
const testConnectText = "Hello";
const daParent=document.getElementById("test");
const tagDiv = "<p style='text-align: center;'><span class='status' id='connectTest'></span></span></p>";
const statusConnecting = tagDiv.getElementById("connectTest");
statusConnecting = testConnectText;
daParent.innerHTML=tagDiv;
document.body.appendChild(daParent);
any suggestion how to get this and pass the updated text here ?
The getElementById method only exists on the document, rather than on HTMLElements. You can only use document.getElementById, so if you need to find something by id inside a particular element you can use a query selector and a #. However, what you have is not an element but a string. It would be preferable to construct your new HTML by doing something like this:
const p = document.createElement('p');
p.style.textAlign = 'center';
const span = document.createElement('span');
span.classList.add('status');
span.setAttribute('id', 'connectTest');
p.append(span);
Once you've done this, it's possible for you to use p.querySelector('#connectTest') but there wouldn't really be any reason to do that since you already have the span stored in a variable called span.
Using your code as a starting point (not change the way you've chosen to do this), this is your solution.
By moving the accessor to below the call to .innerHTML, the element will be in the DOM. As pointed out. .getElementById() is only available on the document object.
So this shows the simple changes necessary:
const testConnectText = "Hello";
const daParent=document.getElementById("test");
const tagDiv = "<p style='text-align: center;'><span class='status' id='connectTest'></span></span></p>";
daParent.innerHTML=tagDiv;
const statusConnecting = document.getElementById("connectTest");
console.log(statusConnecting.id);
<div id="test"></div>
It should be noted that there can be some security risks using .innerHTML, but that is a topic for a different question.

Javascript - Use document.getelementbyid().value with a variable

I'm trying to capture the value of a text field on an HTML form using document.getElementById(my_field).value where the variable my_field is passed to my function dynamically, but am hitting a wall.
How do you use a variable in this context?
The function just doesn't seem to parse the contents of the variable my_field, instead treating it as a string no matter whether I use quotes, square brackets or curly braces.
function myFunction() {
var my_field = arguments[0];
var current_value = document.getElementById(my_field).value;
alert ("Current Value: " + current_value);
}
I'm doing it this way because I have multiple records on a form and each row has its own unique id for the required field.
Running the above just does nothing. The alert never pops which I assume is because current_value never gets set.
To add further detail - I tried to simplify everything for the purposes of this question as there's lots of other unnecessary complications that will only detract from the main issue - on my HTML form is a text field which calls my function on onChange
onchange="enforce_multiples('quantity[<?php echo $line_id; ?>]',<?php echo $product['minimum'];?>)"
I've checked that arguments[0] and [1] are being captured correctly by outputting their values to an alert. Everything works fine up until I try to set the quantity_entered value.
<script>
function enforce_multiples() {
var line_id = arguments[0];
var quantity_increments = arguments[1];
var quantity_entered = document.getElementById([line_id]).value;
alert("QE" + quantity_entered);
//var quantity_mod = quantity_entered % quantity_increments;
//var revised_quantity = quantity_entered - quantity_mod;
//alert("RQ: " + revised_quantity);
//document.getElementById([line_id]).value = revised_quantity;
}
</script>
Checked the console and I receive the error: Uncaught TypeError: Cannot read property 'value' of null on the geElementById line
You should write document.getElementById(my_field) instead of document.getelementbyid(my_field).
OK so I got to the bottom of this in case anyone is interested.
In order to use a variable in document.getElementById() you simply add the variable name with no quotes.
var my_variable = "field1";
document.getElementById(my_variable);
The reason this wasn't working on my form was because the text fields only had the name parameter and not an id parameter.
So I needed to change:
<input type="text" name="field_name" value="1234" />
To
<input type="text" name="field_name" id="field_name" value="1234" />
And that sorted it. Otherwise I was just getting generic NULL error messages in the console.

Cannot get document.getElementByID to work

The following function doesn't work for some reason. Can someone see what the problem is?
function checkMaxLen(txt, maxLen) {
var actualLen = txt.value.length;
var remain = maxLen - actualLen;
document.getElementById('remainChar').Value = remain;
}
<input type="text" id="remainChar" runat="server" value="500"/>
Whenever I try to run the function, I get this error:
Microsoft JScript runtime error: Unable to set value of the property 'Value': object is null or undefined
Check the ID of the input in your final HTML. Since you have runat="server" ASP.NET is likely adding its typical container prefixes.
Main Problem: There is no Javascript getElementById issue, but rather a problem with feeding the right id into getElementById (caused because ASP.NET feels free to change the ids of runat="server" elements) (covered by the accepted answer). This is what caused the error the OP reported:
Microsoft JScript runtime error: Unable to set value of the property 'Value': object is null or undefined
This was because getElementById was given a non-existent id and returned null.
Another Problem: The second problem was indeed a Javascript problem, but not related to getElementById either. Javascript is case sensitive, so trying to set the value property of a input element's DOM object cannot be done by trying to set But even if the (non-existent) Value property.
Solution:
The correct code that solves both problems follows:
function checkMaxLen(txt, maxLen) {
var actualLen = txt.value.length;
var remain = maxLen - actualLen;
document.getElementById('<%= remainChar.ClientId%>').value = remain
}
Note: Thanks go to Ian for pointing out an important oversight in my original answer.
case sensitive:
document.getElementById('remainChar').value
.Value should be .value, script should be executed after appears in the source or after the DOMReady event has been fired.
also since this is asp.net the id attribute of the box will not be "remainChar" but transformed into something else.
so you either need to find out what the final id will be or remove the runat="server" attribute
<html>
<body>
<input type="text" id="remainChar" value="500"/>
<script>
function checkMaxLen(txt, maxLen) {
var actualLen = txt.value.length;
var remain = maxLen - actualLen;
document.getElementById('remainChar').value = remain;
}
checkMaxLen({value:""},20);
</script>
</body>
</html>

Why does this javascript throw this particular error?

In my HTML code I have a button that when pressed runs a javascript function. This is the HTML code for the button:
<button type="button" onclick="repeatName()">Click me!</button>
I want the user to enter something into a text field (which is inside of a form). This is the code for the text field:
<input type="text" name="txtName" />
I want this div's innerHTML to be changed according to the information put in the name textbox once the button is pressed. This is the code for the div:
<div name="editThis" width="50px" height="50px" border="1px">
</div>
When the button is clicked, I want it to run the function below. It is supposed to change the innerHTML of the div.
function repeatName() {
var editField = document.getElementsByName("editThis").innerHTML;
var repeatedName = document.theForm.txtName.value;
editField = (repeatedName + " is the value.")
}
THE PROBLEM IS that whenever the button is clicked, I see this error in the Firefox error console:
Error: uncaught exception: [Exception... "Cannot modify properties of a WrappedNative" nsresult: "0x80570034 (NS_ERROR_XPC_CANT_MODIFY_PROP_ON_WN)" location: "JS frame :: chrome://global/content/bindings/autocomplete.xml :: onxblpopuphiding :: line 825" data: no]
What is this error and how can I correct it?
According to the documentation, document.getElementsByName(str) returns "a list of elements".
It's clear that "a list of elements" doesn't have a singular .innerHTML property. I'd guess that the specific error relates to your browser's internal mechanism for representing that list in its own WrappedNative type.
Iterate the results instead; in your case, you only need the first result, so get it with the array accessor syntax [0].
But, since name properties relate to form components, you should use id instead. Retrieving an element by ID is easier, since IDs are [supposed to be] unique.
Also, since Javascript has no references, you cannot store innerHTML in a variable and change it expecting the original property to change; you must make the assignment in the same statement in which you notate innerHTML:
function repeatName() {
var editField = document.getElementsById("editField");
var repeatedName = document.theForm.txtName.value;
editField.innerHTML = repeatedName + " is the value."
}
I think Tomalak has it right. Alternately, you can give your div an id, and then use getElementById, which will return a single object and not a collection.
i.e.
<div id="editThis" .... > .... </div>
...
...
document.getElementById("editThis").innerHTML = repeatedName + " is the value";
Div elements don't have a name attribute, so use an id instead.
<div id="editThis" ...>
Then use:
function repeatName() {
var editField = document.getElementById("editThis");
if (editField) {
editField.innerHTML = document.theForm.txtName.value + ' is the value';
}
}

why this Javascript code not working

Below is simple code I am using. But why it's not working. giving javascript error.
function postcommnet(wallid) {
var txtboxid='commentdata_'+wallid;
var commentdata=document.getElementById(txtboxid).value
}
error is : document.getElementById(txtboxid) is null.
Please help.
This is one of the few cases where the error is telling you what's wrong:
"document.getElementById(txtboxid) is null."
This means, essentially, that the value of the above is null. This means that getElementById did not find an element with the ID you provided.
Check that the value of txtboxid is correctly an id on one of the DOM's elements. Your error message means that the element is not retrieved and thus the value is null.
It cannot find the element with the id. I have checked the code is working if there is an element with the given id.
This actually works:
<html>
<body>
<input value="lol" id="commentdata_1"/>
<script type="text/javascript">
function postcomment(wallid) { var txtboxid='commentdata_'+wallid;
var commentdata=document.getElementById(txtboxid).value
}
postcomment(1);
</script>
</body>
</html>
The id may not exist on your page, its worth checking.
The following checks to see if the id exists. If it does not exist it will tell you the id its trying to use.
function postcommnet(wallid) {
var txtboxid='commentdata_'+wallid;
if(document.getElementById(txtboxid)){
var commentdata=document.getElementById(txtboxid).value
}
else{
alert('the id - ' + txtboxid +' does not exist');
}
}
I'd suggest using Firefox/Firebug and setting a breakpoint inside your function, then check that the value for wallid is what you expect and, if necessary, examine the live HTML to ensure that the element does, in fact, exist.

Categories