Javascript: document.getElementById() returns NULL - javascript

I am quite new with Javascript and I got a problem with document.getElementById() that always returns NULL, and that's driving me nuts.
I have a element in my code and I want to get its coordinates so I can move it.
Here is the code:
<html>
<head>
<script type="text/javascript" >
function MoveIt(obj) {
alert(obj); // returns "Object HTMLDivElement"
var xx = document.getElementById("arect");
if(document.getElementById("arect").value == null) {
alert('NULL >> ' + xx.value);
}
else {
alert('NOT NULL >>' + xx.value);
}
posX = xx.style.scrollTop;
posY = xx.style.left;
}
</script>
</head>
<body bgcolor="white" >
<DIV class="background" id="MyDiv2">
<div id="arect" name="arect" class="transbox" onmousedown="MoveIt(this);" >
</div>
</div>
</body>
</html>
The above function MoveIt() always returns NULL

The page contents need to be loaded before trying to read them. Try
window.onload = function() {
// run your script in here
}
Or if you're using jQuery, prefer
$(document).ready(function() {
...
}

You never checked getElementById(...) for NULL.
You checked getElementById(...).value for NULL, and divs don't have a "value".
Also note that you forgot to close that <div /> tag, which is illegal in your XHTML... and used an SVG doctype for some reason. SVG is not HTML.
It's not really clear what you're trying to do here.

The "arect" element is a <div>, and <div> elements don't have a "value".
Get rid of that bogus SVG doctype too.

if(document.getElementById("arect").value == null){
alert('NULL >> '+ xx.value);
}
This code always returns null or error. If you want to see if the object exists, do the following....
if(xx == null)
alert('Object does not exist');
else
alert('Object exists. Inner HTML: ' + xx.innerHTML);
Also, div does not have value. If you want to get the html inside div, use xx.innerHTML

if the button is set to visisble= false then you cannot get the id of that button on client side. To hide the button use
button1.Style.Add("display","none")-- for visible false
and
button1.Style.Add("display","block")-- for visible true
and even if button is enabled false we cannot get the Id of the button on client side
You can get the id of the button by document.getElementById('<%= button1.ClientID %>');
Or
if you set the ClientIDMode="Static" for the control in aspx page you can get it directly by document.getElementById('button1');
Or
document.getElementById('MainContent_button1');--- MainContent here is the Id of the contentplaceholder if you have the id of the contenet placeholder different use that id_button1.

in my case it was because of having this line at the beginning of the jsp/html(whatever) file:
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
removing it solved my problem.

Related

Adding and removing a tag on function call

I need to change the color of a specific word inside a text of an element. I tried adding and removing span tags to change the style of the word, but I can't remove it after. Here's the code I tried
function changeColor(unit){
document.getElementsByClassName("label")[0].innerHTML=document.getElementsByClassName("label")[0].innerHTML.replace('/<span id="highlighted">(.*)<\/span>/g','$1');
document.getElementsByClassName("label")[0].innerHTML=document.getElementsByClassName("label")[0].innerHTML.replace(unit,'<span id="highlighted">' + unit + '</span>');
}
The text looks like this "°C,kW/h,cm".
What is happening right now is everytime the function is called, span tags are added but never removed. How can I achieve this with Javascript/JQuery?
Desired behavior :
When the function is called with say "cm" as parameter. I want the string to become "°C,kW/h,<span id=highlighted>cm</span>". Now if the function is called again with "kW/h", I want the string to become "°C,<span id=highlighted>kW/h</span>,cm"
With jQuery you can use .unwrap():
Try:
$(document).ready(function(){
$("label span").contents().unwrap()
});
label {color:green}
#highlighted{color:red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<label>°C,<span id=highlighted>kW/h</span>,cm</label>
Change
.replace('/<span id="highlighted">(.*)<\/span>/g','$1')
to
.replace(/<span id="highlighted">(.*)<\/span>/g,'$1')
The first one is a string, the second one a RegEx and you need the latter.
See how replace works. The first argument is either a string or a RegEx.
Adding my no-jQuery solution:
Make 3 spans (s1, s2, s3)
Change the color style depending on the unit input
And so:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script>
function changeColor(unit) {
var allUnits = [ '°C', 'kW/h', 'cm' ];
for (var i = 0; i < allUnits.length; i++) {
if (unit == allUnits[i])
document.getElementById('s'+(i+1)).style = 'color:#00FFFF';
else
document.getElementById('s'+(i+1)).style = 'color:#000000';
}
}
document.addEventListener("DOMContentLoaded", function(event) {
changeColor('kW/h');
});
</script>
</head>
<body>
<span id="s1">°C</span>,<span id="s2">kW/h</span>,<span id="s3">cm</span>
</body>
</html>

Div element hide and show

I have a hidden div element.
<div class= "CTL" id="CTL" runat="server" style="display:none">
<p class ="divider">
CTL
</p>
<asp:Button ID="CTL_button" runat="server" Text="View CTL"
onclick="CTL_button_Click" />
</div>
I am trying to make the div element appear or stay hidden based on an SQL value returned on page Load:-
window.onload= function show_CTL() {
if("<%=_CurrentUser.IsCTL%>" == "True"){
document.getElementById('CTL').style.display ="block";
}
else{
// document.getElementById('CTL').style.display ="none";
}
But the div element remains shown regardless of value returned...
It seems like only the true part of the loop gets executed...
Use display:none to hide the div in first place
<div class= "CTL" id="CTL" style="display:none" runat="server">
<p class ="divider">
CTL
</p>
<asp:Button ID="CTL_button" runat="server" Text="View CTL"
onclick="CTL_button_Click" />
</div>
then you can show it with
document.getElementById('CTL').style.display ="block";
Cast the condition to a Boolean in JavaScript you can do it like this:
window.onload = function show_CTL() {
var el = document.getElementById('CTL');
if(Boolean("<%=_CurrentUser.IsCTL%>") && el){
el.style.display = "block";
}
else{
el.style.display = "none";
}
}
If the Boolean object has no initial value, or if the passed value is one of the following:
0
-0
null
""
false
undefined
NaN
the object is set to false. For any other value it is set to true (even with the string "false")!
Now I wonder, why not simply add the condition inside the visible attribute?
<div class="CTL" id="CTL" runat="server" visible=<%=_CurrentUser.IsCTL%>></div>
No JavaScript needed this way.
ASP.NET is changing the IDs, thats why you have to take the clientID of your element.
document.getElementById("<%= CTL.ClientID %>").style.display = "block";
visible and display are 2 different css property,
you set visible first, but later you change display,
you should change visible, not display,
of cause you can use display instead of visible in the first place.

Why the href attribute is not getting set in followinng scenario?

I'm using jQuery Colorbox library. I'm not able to a set the href attribute value of anchor tag. Can you help me in setting the value? If I print the value in alert it's printing correct href attribute value. My code is as follows:
<a class="edit_user_transaction_status c-btn" updatehref="{$control_url}{$query_path}?op=edit_user_transaction&page={$page}&txn_no={$user_transaction_details.transaction_no}&transaction_data_assign={$user_transaction_details.transaction_data_assign}&user_id={$user_id}{if $user_name!=''}&user_name={$user_name}{/if}{if $user_email_id!=''}&user_email_id={$user_email_id}{/if}{if $user_group!=''}&user_group={$user_group}&{/if}{if $user_sub_group!=''}&user_sub_group={$user_sub_group}{/if}{if $from_date!=''}&from_date={$from_date}{/if}{if $to_date!=''}&to_date={$to_date}{/if}{if $transaction_status!=''}&transaction_status={$transaction_status}{/if}{if $transaction_no!=''}&transaction_no={$transaction_no}{/if}" href="#updatePopContent">Update</a>
<div class="hidden">
<div id="updatePopContent" class="c-popup">
<h2 class="c-popup-header">Transaction</h2>
<div class="c-content">
<h3>Are you sure to change status?</h3>
NoYes
</div>
</div>
</div>
<script language="javascript" type="text/javascript">
$(document).ready(function(){
$(".edit_user_transaction_status").click(function(e) {
//$.colorbox.close();
var update_url = $(this).attr('updatehref');
$('#update_url').attr('href', update_url);
$(".edit_user_transaction_status").colorbox({inline:true, width:666});
$(".c-btn").bind('click', function(){
$.colorbox.close();
});
});
});
</script>
I'm not able to set the value of href attribute (i.e. update_url) to the anchor tag having id update_url. Can you help me in this? Thanks in advance.
Try setting a data attribute instead of a made-up one (should work, but better to use data. Also, know that firebug, etc. doesn't always change when something is dynamically updated ive found. You can always console.log($('.edit_user_transaction_status').attr('href')) to check the final value:
<a class="edit_user_transaction_status c-btn" data-updateHref="{$control_url}... href="#updatePopContent">Update</a>
$(".edit_user_transaction_status").click(function(e) {
//$.colorbox.close();
var update_url = $(this).data('updateHref');
$('#update_url').attr('href', update_url);
$(".edit_user_transaction_status").colorbox({inline:true, width:666});
$(".c-btn").bind('click', function(){
$.colorbox.close();
});
});

JS Change class of element

All I'm trying to do is toggle the class of an elements by ID when they are clicked on.
<script>
function selectLoad(id)
{
if(document.getElementById(id).className == "load") {
document.getElementById(id).className = "loadSelected";
} else {
document.getElementById(id).className = "load";
}
}
</script>
<div class="load" id=" ... set by PHP per element ... " onclick="selectLoad(this)">
This returns an error...
Uncaught TypeError: Cannot read property 'className' of null
So I guess it doesn't like the conditional.
I'm new to JS and need help, thanks in advance.
You are passing the dom element itself (using this), not the id.
You should change the code to
function selectLoad(element)
{
if (element.className == "load") {
element.className = "loadSelected";
} else {
element.className = "load";
}
}
I think you are passing an id that does not exist in the dom. Has the dom loaded before your javascript is executed? Move the script to the bottom of the page just before the closing html tag
EDIT: Following discussion in comments below the error is this line:
<div class="load" id=" ... set by PHP per element ... " onclick="selectLoad(this)">
it should read
<div class="load" id=" ... set by PHP per element ... " onclick="selectLoad(this.id)">
Your code is not safe because you don't check if you have the DOM element with the given id
That is why you get the error: Cannot read property 'className' of null
if(document.getElementById(id)) {
// ... do something and do not go further.
return;
}
And the problem is passing this when you call selectLoad. At this point, this is the DOM element, not the string that yo expect: ... set by PHP per element .... So you have to change the code accordingly.

How to show and hide DIV based on URL. in Javascript

I have two URL's
url 1 = www.xyz.co.uk/asd.qmd
url 2 = www.xyz.co.uk/asd.qmd?getstep=4#
I want to show a div(left) when PAGE URL is www.xyz.co.uk/asd.qmd?getstep=4#
In the page form.php I wrote the following code:
<script>
$(function(){
var locate = window.location;
if (locate=="http://localhost/school/form.php") {
$('#left').hide();
} else {
$('#left').show();
}
});
</script>
<body onload="function()">
<div id="left">
aasdsasdfdsgfg
</div>
</body>
Why is this not working?
Just make php condition
<?php
if($_GET['getstep']){
}
?>
$('#left').toggle(window.location.href !== "http://localhost/school/form.php");
You need to make a show/hide function the proper javascript way. What you are doing at first with the (I assume) jQuery is beyond me - just declare a simple function containing the code you already have to show/hide and attach it to the onload-event.
If you just want to hide the div when the query string is empty, you could use the search property of the window.location object:
$(function(){
if (window.location.search === "") {
$('#left').hide();
} else {
$('#left').show();
}
});
Anything more complicated (i.e. a different div for each page value) and I recommend you look at regex
You need to use the href property of the window.location object.
var locate = window.location.href,
myElement = $('#left');
locate == "http://localhost/school/form.php"
? myElement.show()
: myElement.hide();

Categories

Resources