I am trying to set an id in html to a string set that is located inside a property inside an object using jquery. But for some reason, when I do run the program, the jquery script doesn't work. I tried setting the html DOM code inside the document.ready, and also tried to run the code inside a function that runs after other events are activated but nothing changed. Help me fix this problem.
$(document).ready(function() {
var testObj = {
exampleText = "Hello world"
};
$("#test").html(testObj.exampleText);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="test"></p>
You have a syntax error.
use var testObj = {exampleText: "Hello world"}; instead.
Related
I'm a newbie trying to write a JS/HTML report generator based on criteria which I submit in an HTML form. The plan eventually is to use PHP/mySQL to manipulate a database and return results but for now I'm just trying to build the HTML/CSS/JS and I've got stuck. I have attributed a JS function to a button in the <body> like so:
<input type="button" id="reportButton" value="Generate Report" onclick="showCriteria()">
I included a script in the <head> as follows:
<script>var showCriteria = function(){ My JS code...}</script>.
This function simply does some date manipulation and displays the result in a div on the same page like so:
document.getElementById("endDate").innerHTML = "to "+endDay+" "+endMonthName+" "+endYear;
But I get Uncaught TypeError: Cannot set property 'innerHTML' of null. So I searched the forum and discovered that this can sometimes be caused by not waiting for the window to load. So I wrapped the script as follows:
<script>
window.onload = function()
var showCriteria = function(){ My JS code...}
That solved the initial error but I then get Uncaught ReferenceError: showCriteria is not defined
It seems like I'm in a Catch22. I get the first error because the script is running before the window has loaded. I fix that by waiting for the window to load only to find that the HTML is waiting for my script to define my JS function.
Any advice gratefully received.
Report Generator screenshot
Window.load script
You've almost got the solution. At least you've got all the right elements.
window.onload = function() {
document.getElementById('reportButton').addEventListener('click', showCriteria);
};
This will make it so the button does not function until the page is ready.
You also need to remove the onclick from the button.
When you put the showCriteria function inside window.onload, please make sure it is accessible by the DOM, i.e. window.showCriteria.
<script>
window.onload = function()
window.showCriteria = function(){ My JS code...}
...
Beside using onclick on html, you can use add listener to listen the click event on that element.
window.onload = function() {
document.getElementById('reportButton').addEventListener('click', showCriteria);
};
In my <body> I have a component that inserts a script that is supposed to run only after all the page has completely loaded:
<script>
$('<script id="smallPlacarScriptdId">\
$(window).load(function() {\
$(".main.right").hide();\
$("#rightzero").show();\
$(".comp.smallPlacard.firstChild").click(function () {\
var clicked = $(this).parent().attr("id");\
$("main.right").hide();\
$("#right"+clicked+"").show();\
});\
})\
<\script>').appendTo("body")
</script>
That's not happening and this script (1) is correctly inserted into the DOM but (2) is not working (not hiding .main.right nor showing #rightzero).
I though that by using this approach I would guarantee that it would be the same as just put this script at the bottom of the <body> but it isn't. In fact if I put it (not dynamically like this) in my page it produces the desired result.
I tried setTimeout() to validate my theory but I'm getting an error in jQuery and I'm lost.
That might be the problem:
<\script>').appendTo("body")
Browser might think you are actually closing your script tag. Change it to
</' + 'script>').appendTo("body")
Check this plunker out: http://plnkr.co/edit/Oc6yrFMdPoW2WV257CBQ?p=preview
Just use this code
<script id="smallPlacarScriptdId">
$(window).load(function() {
$("main.right").hide();
$("#rightzero").show();
$(".comp.smallPlacard.firstChild").click(function () {
var clicked = $(this).parent().attr("id");
$("main.right").hide();
$("#right"+clicked+"").show();
});
})
</script>
Sorry I didn't read you question well enough.
Javascript will allow you to access undeclared variables, so use that to your advantage. Check if a variable is set, undefined is treated as a false so no need for initialization. As soon as you enter the code just set it to true so nothing else will execute.
Hopefully this solves the problem for you, but you really should look at from the server avoiding the javascript, it will bloat the page.
<script>
if (!myScriptHasLoaded)
{
myScriptHasLoaded = true;
$(window).load(function() {
$("main.right").hide();
$("#rightzero").show();
$(".comp.smallPlacard.firstChild").click(function () {
var clicked = $(this).parent().attr("id");
$("main.right").hide();
$("#right"+clicked+"").show();
});
});
}
</script>
I am just starting out with JavaScript and I have a simple code that sends a value to an element with id p. I am currently declaring this function in a <script> in the <head> element of my document.
function writeP(resultSet) {
document.getElementById('p').innerHTML = resultSet.length;
};
writeP(results);
When I have this listed within the <head> element and run the webpage, firebug throws this error at me: TypeError: document.getElementById(...) is null.
However, if I move the code block into a <script> tag beneath the element and then reload the webpage, no problems and the script works as it should. Is there any reason for this, and a way I could make this work so I wouldn't have to define my functions beneath the element or include a onload on my body element?
Thanks for your help
Reason is that by the time your launch js code, DOM is not yet prepared, and JS can't find such element in DOM.
You can use window.onload (docs on W3schools) trigger to fire your functions after all elements are ready. It's same as having onload property on body element, but is more clear, as you can define it in your js code, not in html.
JS evaluates syncronically. Therefore, it does matter WHEN you declare the function. In this case, you're declaring it before the element actually exists.
Second, when you declare a function with that syntax, it does get eval'd inmediately. If you declared, instead
var writeP=function(resultSet) {
document.getElementById('p').innerHTML = resultSet.length;
};
you could save just the call to the end of the Doc, and leave the declaration at the beggining.
However, I would advise you to read a few jQuery tutorials to learn easier ways to deal with dom manipulation. Nobody runs raw JS for that task anymore.
jQuery includes an useful call to document ready event, which will save you a lot of headaches and is -IMHO- more efficient than the onload event. In this case, you would include the jQuery library somewhere in your code
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
and then add
<script>
jQuery(document).ready(function() {
var writeP=function(resultSet) {
jQuery('#p').html(resultSet.length);
};
writeP(resultSet);
});
</script>
just about anywhere in your document or an external js file, as it suits you.
I am trying to a function to trigger once the body loads. I know that you can do this from the body tag, but I would prefer to do this from JS if this is possible.
For example: document.getElementsByTagName('body').onload = someFunc();
This does not work for me, but I think it shows what I essentially want to do.
EDIT:
I have tried the answers, what seems to be the issue is that it is calling the function before the elements it uses in the body tag are loaded, even if I put the script tags inside the body.
This is what it needs to do:
var buttonElements = document.getElementsByClassName('button');
And if I do:
alert(buttonElements)
It will pop up 0, but when I create a variable in the console, it will successfully populate it with the elements.
What you've got will almost work, but you have to import your JavaScript at the end of the <body> tag, and you have to index the first result:
document.getElementsByTagName('body')[0].onload = someFunc;
Like so:
window.onload = someFunc;
If however, your function accepts arguemnts, you would need anonymous function like this:
window.onload = function(){
someFunc(arg1, arg2);
}
BTW, other than fix that #Pointy mentioned for your code, you can also do:
document.body.onload = someFunc;
Dont use quotes... "someFunc"() won't work if you try to run it anyways.
window.onload = someFunc;
If you use jQuery:
$(document).ready(function () {
callMyFunction();
});
I'd like to change the value of the onclick attribute on an anchor. I want to set it to a new string that contains JavaScript. (That string is provided to the client-side JavaScript code by the server, and it can contains whatever you can put in the onclick attribute in HTML.) Here are a few things I tried:
Using jQuery attr("onclick", js) doesn't work with both Firefox and IE6/7.
Using setAttribute("onclick", js) works with Firefox and IE8, but not IE6/7.
Using onclick = function() { return eval(js); } doesn't work because you are not allowed to use return is code passed to eval().
Anyone has a suggestion on to set the onclick attribute to to make this work for Firefox and IE 6/7/8? Also see below the code I used to test this.
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var js = "alert('B'); return false;";
// Set with JQuery: doesn't work
$("a").attr("onclick", js);
// Set with setAttribute(): at least works with Firefox
//document.getElementById("anchor").setAttribute("onclick", js);
});
</script>
</head>
<body>
Click
</body>
</html>
You shouldn't be using onClick any more if you are using jQuery. jQuery provides its own methods of attaching and binding events. See .click()
$(document).ready(function(){
var js = "alert('B:' + this.id); return false;";
// create a function from the "js" string
var newclick = new Function(js);
// clears onclick then sets click using jQuery
$("#anchor").attr('onclick', '').click(newclick);
});
That should cancel the onClick function - and keep your "javascript from a string" as well.
The best thing to do would be to remove the onclick="" from the <a> element in the HTML code and switch to using the Unobtrusive method of binding an event to click.
You also said:
Using onclick = function() { return eval(js); } doesn't work because you are not allowed to use return in code passed to eval().
No - it won't, but onclick = eval("(function(){"+js+"})"); will wrap the 'js' variable in a function enclosure. onclick = new Function(js); works as well and is a little cleaner to read. (note the capital F) -- see documentation on Function() constructors
BTW, without JQuery this could also be done, but obviously it's pretty ugly as it only considers IE/non-IE:
if(isie)
tmpobject.setAttribute('onclick',(new Function(tmp.nextSibling.getAttributeNode('onclick').value)));
else
$(tmpobject).attr('onclick',tmp.nextSibling.attributes[0].value); //this even supposes index
Anyway, just so that people have an overall idea of what can be done, as I'm sure many have stumbled upon this annoyance.
One gotcha with Jquery is that the click function do not acknowledge the hand coded onclick from the html.
So, you pretty much have to choose. Set up all your handlers in the init function or all of them in html.
The click event in JQuery is the click function $("myelt").click (function ....).
just use jQuery bind method !jquery-selector!.bind('event', !fn!);
See here for more about events in jQuery
If you don't want to actually navigate to a new page you can also have your anchor somewhere on the page like this.
<a id="the_anchor" href="">
And then to assign your string of JavaScript to the the onclick of the anchor, put this somewhere else (i.e. the header, later in the body, whatever):
<script>
var js = "alert('I am your string of JavaScript');"; // js is your string of script
document.getElementById('the_anchor').href = 'javascript:' + js;
</script>
If you have all of this info on the server before sending out the page, then you could also simply place the JavaScript directly in the href attribute of the anchor like so:
Click me
Note that following gnarf's idea you can also do:
var js = "alert('B:' + this.id); return false;";<br/>
var newclick = eval("(function(){"+js+"});");<br/>
$("a").get(0).onclick = newclick;
That will set the onclick without triggering the event (had the same problem here and it took me some time to find out).
Came up with a quick and dirty fix to this. Just used <select onchange='this.options[this.selectedIndex].onclick();> <option onclick='alert("hello world")' ></option> </select>
Hope this helps