why this Javascript code not working - javascript

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.

Related

Could someone help me with this javascript code

Hello i was learning Javascript from 10 day of javascript videos and in last day it still runs error: Uncaught TypeError: Cannot read property 'insertAdjacentHTML' of null
could someone help me
let ourForm = document.getElementById('ourForm')
let ourField = document.getElementById('ourField')
let ourList = document.getElementById('ourList')
ourForm.addEventListener('submit', (e) => {
e.preventDefault()
createItem(ourField.value)
})
function createItem(x) {
ourList.insertAdjacentHTML('beforeend', x)
}
This will be because the element with an id of ourList does not exist. Double check you have an element in your HTML with this id.
Please recheck your HTML code. It looks like you missed the id ourList somewhere. The error means that your javascript was unable to find the element with the given id.
If you check your HTML code, there must be an element with an id of "ourList" for your code to work. Since the error says that an object with that id currently returns a null, something is incorrect. You most likely either misspelled it, or forgot to add the id to the corresponding HTML element.
You do this by writing:
<ul id="ourList"> ... </ul>
where ul is your element type. (ul, ol, div...)

JQuery retrieving id from Checkbox at run time

My problem is, I want to retrieve checkbox id at runtime and use them later for other purpose.
But retrieved id is read as object.
My Code is:
// Following code gives id of checkbox which contains myCheckbox as its id.
var myCheckbox= $('input[id$=myCheckbox]')[0].id;
// and Now I want to check if that checkbox is checked with following code:
if ($(myCheckbox).is(':checked'))
return 1;
else
return 0;
But here myCheckbox id is read as Object instead of id and thus always enter in else condition and returns 0. This code works when I enter id of checkbox directly.
if ($('#ctl001_myCheckbox').is(':checked'))
return 1;
else
return 0;
It shouldnot be so complicated, I have been working with Javascript but new to JQuery.
You are getting the ID correctly, but the jQuery selector requires the # symbol, much in the same way as a CSS selector does. You need to add the # character to your selector:
if ($('#'+myCheckbox).is(':checked'))
return 1;
else
return 0;
BenM is correct, but why are you getting the ID of the element, and then look it up again? You already found the element, there is no need to search for it a second time.
Just keep a reference to the element:
var myCheckbox = $('input[id$=myCheckbox]').first();
// or var myCheckbox = $('input[id$=myCheckbox]')[0];
// and later
if (myCheckbox.is(':checked')) {
// or if (myCheckbox.checked) {
Simply:
return (($('#' + myCheckbox).is(':checked')) ^ false);
Have you tried using:
var myCheckbox= $('input[id$=myCheckbox]').attr('id');

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>

'div_element' is null or not an object in IE7

Here I have get one error in JavaScript div_element is null or not an object.
I have given my code below:
function showLoading(id) {
div_element = $("div#" + id)[0];
div_element.innerHTML = loading_anim; // Error in this line
}
When I am debugging my script but it's working fine in other browsers including IE 8, but it's not working in IE 7. I don't understand what exact issue occur in this script.
First of all, you dont need to put a tag name infront of the jQuery, unless you have other elements with exact same id on other elements, in other pages.
Next, your statement div_element.innerHTML = loading_anim; is correct. So, the only explanation is that, there is no element with that ID, in the DOM.
Finally, since you are usign jQuery already, no need to mix up native JS and jQuery to create a dirty looking code.
function showLoading(id) {
div_element = $("#" + id);
console.log(div_element); //check the console to see if it return any element or not
div_element.html(loading_anim);
}
I think you don't select anything with your jquery selector (line 2)
try to display
id
"div#" + id
$("div#" + id)
$("div#" + id)[0]
You can use firebug javascript console or a simple alert like this:
alert($("div#" + id)[0]);
And see if you must id or class on your div ( use # or . selector)
I suppose, that nic wants to display some loader GIF animation, I confirm, that nic must use jQuery .html() method for DOM objects, and tusar solution works fine on IE6+ browsers. Also (it is obvious but anyway) nic must assign a value to loading_anim variable in script, lets say: var loading_anim = $('#loader').html(); before assigning its value to div_element.
Use .html() for jQuery objects. innerHTML work for dom objects, they wont work for jQuery objects.
function showLoading(id) {
div_element = $("div#" + id);
$(div_element).html(loading_anim); // Provided `loading_anim` is valid html element
}

How do I concatenate a string with a variable?

So I am trying to make a string out of a string and a passed variable(which is a number).
How do I do that?
I have something like this:
function AddBorder(id){
document.getElementById('horseThumb_'+id).className='hand positionLeft'
}
So how do I get that 'horseThumb' and an id into one string?
I tried all the various options, I also googled and besides learning that I can insert a variable in string like this getElementById("horseThumb_{$id}") <-- (didn't work for me, I don't know why) I found nothing useful. So any help would be very appreciated.
Your code is correct. Perhaps your problem is that you are not passing an ID to the AddBorder function, or that an element with that ID does not exist. Or you might be running your function before the element in question is accessible through the browser's DOM.
Since ECMAScript 2015, you can also use template literals (aka template strings):
document.getElementById(`horseThumb_${id}`).className = "hand positionLeft";
To identify the first case or determine the cause of the second case, add these as the first lines inside the function:
alert('ID number: ' + id);
alert('Return value of gEBI: ' + document.getElementById('horseThumb_' + id));
That will open pop-up windows each time the function is called, with the value of id and the return value of document.getElementById. If you get undefined for the ID number pop-up, you are not passing an argument to the function. If the ID does not exist, you would get your (incorrect?) ID number in the first pop-up but get null in the second.
The third case would happen if your web page looks like this, trying to run AddBorder while the page is still loading:
<head>
<title>My Web Page</title>
<script>
function AddBorder(id) {
...
}
AddBorder(42); // Won't work; the page hasn't completely loaded yet!
</script>
</head>
To fix this, put all the code that uses AddBorder inside an onload event handler:
// Can only have one of these per page
window.onload = function() {
...
AddBorder(42);
...
}
// Or can have any number of these on a page
function doWhatever() {
...
AddBorder(42);
...
}
if(window.addEventListener) window.addEventListener('load', doWhatever, false);
else window.attachEvent('onload', doWhatever);
In javascript the "+" operator is used to add numbers or to concatenate strings.
if one of the operands is a string "+" concatenates, and if it is only numbers it adds them.
example:
1+2+3 == 6
"1"+2+3 == "123"
This can happen because java script allows white spaces sometimes if a string is concatenated with a number. try removing the spaces and create a string and then pass it into getElementById.
example:
var str = 'horseThumb_'+id;
str = str.replace(/^\s+|\s+$/g,"");
function AddBorder(id){
document.getElementById(str).className='hand positionLeft'
}
It's just like you did. And I'll give you a small tip for these kind of silly things: just use the browser url box to try js syntax. for example, write this: javascript:alert("test"+5) and you have your answer.
The problem in your code is probably that this element does not exist in your document... maybe it's inside a form or something. You can test this too by writing in the url: javascript:alert(document.horseThumb_5) to check where your mistake is.
Another way to do it simpler using jquery.
sample:
function add(product_id){
// the code to add the product
//updating the div, here I just change the text inside the div.
//You can do anything with jquery, like change style, border etc.
$("#added_"+product_id).html('the product was added to list');
}
Where product_id is the javascript var and$("#added_"+product_id) is a div id concatenated with product_id, the var from function add.
Best Regards!

Categories