I am trying to update the content of a dynamically generated div with .innerHTML and getElementById, but when I test it, I get an error: "Uncaught TypeError: Cannot set property 'innerHTML' of null" I also tried using alert() and checking the value of quizDiv at breakpoints. Well, here's my JS file called main.js:
function makeDiv() {
document.body.innerHTML = "<div id='quizDiv'></div>"
}
function createInputBox(boxId) {
var quizDiv = document.getElementById("quizDiv");
quizDiv.innerHTML = "<input type='text' id='" + boxId + "'>";
}
makeDiv();
createInputBox(1);
Here's my html:
<!-- doctype, head, etc -->
<body>
<!-- content -->
<script src="/main.js"></script>
</body>
Any help is appreciated. Thanks!
Since you already creating the div in js, why not hold the reference then?
function makeDiv() {
var quizDiv=document.createElement("div");
document.body.appendChild(quizDiv);
return quizDiv;
}
function createInputBox(quizDiv,boxId) {
// var quizDiv = document.getElementById("quizDiv");
quizDiv.innerHTML = "<input type='text' id='" + boxId + "'>";
}
var quizDiv=makeDiv();
createInputBox(quizDiv,1);
There are a few problems with you code.
Firstly the HTML is not valid, meaning ID's can't start with numbers. Read more about how to overcome this issue here: CSS-Tricks
Secondly, you code 'works' could you provide an image of your directory structure and the full markup? Here is a jsfiddle with your code and it displays the input: jsFiddle Maybe there is a problem with the file path or your calling the js file before the document is ready.
I cleaned your code up a bit so maybe try this instead:
window.onload = function () {
var body = document.body;
function createDiv (identifier) {
var el = document.createElement('div');
el.id = identifier;
body.appendChild(el);
}
function createInput(identifier) {
var div = document.getElementById('quizDiv');
div.innerHTML = "<input type='text' id='" + identifier + "'>";
}
createDiv('quizDiv');
createInput('bar');
};
Related
I don't have many knowlege in javascript so I don't know what is the problem here,
I create divs dynamically in js and each div call a function when is clicked but the function is not recongized. This is part of the code
for (......) {
var listatema = document.createElement("div");
listatema.innerHTML += "<a href='javascript: void(0)' onClick='functest(" + pag + ")'>" + temat + "</a>";
document.getElementById('menu').appendChild(listatema);}
}
"tema" is a text, the function "functest" has an argument "pag[aux]", this is a number.
The function is:
function functest(arg){
console.log(arg)
}
other alternative that i tried is change that: onClick='"+ functest(pag) +"':
i change the position of Quotation marks "" and the function work good but it is executed when the page is loaded, it don't wait to do click.
Your code should work if you're doing something like:
function functest(arg) {
console.log(arg);
}
for (var i = 0; i < 10; i++) {
var listatema = document.createElement("div");
listatema.innerHTML += "<a href='javascript: void(0)' onClick='functest(" + i + ")'>" + i + "</a>";
document.getElementById('menu').appendChild(listatema);
}
<div id="menu"></div>
I would, however, recommend using addEventListener or setting the onClick handler on the document element object rather than setting the innerHTML. Note that setting innerHTML is not advised, especially when rendering user input. See https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#Security_considerations. In your case, it probably isn't really an issue, but it's good practice to avoid it if you can :)
for (var i = 0; i < 5; i++) {
var wrapper = document.createElement("div");
var listatema = document.createElement("a");
listatema.textContent = i;
listatema.href = "javascript:void(0)";
listatema.addEventListener('click', function(e) {
console.log(this.i);
}.bind({ i : i }));
wrapper.appendChild(listatema);
document.getElementById('menu').appendChild(wrapper);
}
<div id="menu"></div>
onClick='functest(\""+ pag +"\")'
you forgot to quote the parameter.
<div id="result"></div>
<button id="send">Request</button>
JavaScript:
var button = document.getElementById("send"),
div = document.getElementById('result');
button.addEventListener('click', function() {
var result = createIframe("f", "/lorem.txt");
console.log(result.contentWindow);
div.innerHTML = result.contentWindow.document.body.innerHTML;
});
function createIframe(name, src, debug) {
var tmpElem = document.createElement('div');
tmpElem.innerHTML = '<iframe name="' + name + '" id="' + name + '" src="' + src + '">';
var iframe = tmpElem.firstChild;
iframe.style.display = 'none';
document.body.appendChild(iframe);
return iframe;
}
I have on the local server is a file lorem.txt. With hidden frame I am trying to query the contents of this file and paste it into <div id="result"></div>. But for some reason it does not is inserted. What could be the problem?
I believe elements with the ids of "send" and "result", respectively do not exist at the moment when your javascript code is running, therefore the click event will not be attached to the button. You need to make sure that these elements exist when you try to get them by their ids or attach events to them.
Solution: Either make sure your code is running after the document has been loaded or put your relevant script tag below the html you have described in your question.
I am trying to change the input value of a hidden form to update the score of a game in my database.
I have this form code on a php page that displays and plays the game.
<form id ="recordForm" method="POST" action="updatePHP.php">
<input type='hidden' name="record" id='record' value='' />
</form>
And am trying to change the value of the hidden input field with this javascript. This is in the separate javascript file that is controlling the game.
function postPHP(newRecord){
alert("POST TO PHP"); //test to make sure I am calling this function
alert (newRecord); //alerts the correct value
var elem = document.getElementById('record');
elem.value = 12;
// document.getElementById('record').value = newRecord;
// document.getElementById('recordForm').submit();
};
There are a lot of topics on this subject but I am just not able to figure out what I am doing wrong. Any suggestions?
you should try
elem.value = newRecord;
Your JS function should work like this, i tested, more less what you already have. I remove the alerts since you don't need them anymore and leave what you have commented. This means your JS function isn't the problem.
function postPHP(newRecord)
{
document.getElementById('record').value = newRecord;
document.getElementById('recordForm').submit();
};
Don't forget to sent the parameter when calling the JS function, i did it with a button
<button onClick="postPHP('14')">Change</button>
since your JS function is in a separate file don't forget to include it in the File where you call the function
<head>
<script type="text/javascript" src="PATH/exampleName.js"></script>
</head>
Replace the src of the above tag to your needs
And last but not least check your updatePHP.php with a call to the method print_r
print_r($_POST);
All that should make the trick
Thank you for all your suggestions! This was my first question ever, I will look at all of them and see if I can get it working.
This is where I am calling postPHP:
function checkScore(score, record) {
alert('Score= ' + score);
alert ('Record= '+ record);
if(score < record || record === 0){
alert ("NEW RECORD"); //this alert is displayed when needed
postPHP(score);
}
};
and checkScore was called when the user moved a target crate back to the beginning spot and the following statement was executed
if (this.hasWon()) {
var finalScore = this.getScore();
var record = this.getRecord();
checkScore(finalScore, record);
return ret; //moving not allowed
}
there are some access methods used there.
//access methods
Board.prototype.hasWon = function() {
return state === 1;
};
Board.prototype.getScore = function() {
return score;
};
Board.prototype.getWt = function(r, c) {
return b[r][c];
};
Board.prototype.getData = function() {
return {"bobR": bobR, "bobC": bobC, "bobDir": bobDir,
"tgtR": tgtR, "tgtC": tgtC,
"startC": startC, "n": n};
};
Board.prototype.getRecord = function(){
var s = "" + window.location;
var ampIdx = "" + s.indexOf("&");
ampIdx = parseInt(ampIdx);
ampIdx = ampIdx + 7;
var record = "" + s.substring(ampIdx);
//alert("Puzzle Record= " + record);
record = parseInt(record);
return record;
}
;
I do have the javascript included. I do call it once in the body of the HTML, for some reason it doesn't display the game correctly when included in the head.
Again, thank you for the help! I will let you know what I get to work!
This is what I got to work.
function postPHP(newRecord, seed) {
alert("POST TO PHP");
var inner = "<input type='hidden' name='record' id='record' value=" + newRecord + " >"+
"<input type='hidden' name='seed' id='seed' value=" + seed + " >";
document.getElementById('recordForm').innerHTML = inner;
document.getElementById('recordForm').submit();
};
Thanks again for all the help, I just don't know why the first method wasn't working. This is my first attempts at PHP and javascript.
I'm getting a "cannot set property 'innerHTML' of null from getElementById, but my HTML element has the right ID, and so does my script.
I'm new to JavaScript so if I'm missing something obvious please tell me! Thanks!
Here's the full fiddle:
FIDDLE: http://jsfiddle.net/xPLD4/1/
This is the section that i'm having problems with.
Script:
function prices() {
document.getElementById("regular").innerHTML = '$' + setPrices.regular + ' /gallon';
document.getElementById("regPlus").innerHTML = '$' + setPrices.regularPlus + ' /gallon';
document.getElementById("premium").innerHTML = '$' + setPrices.premium + ' /gallon';
document.getElementById("status").innerHTML = "Status: No Automobile Present";
var carPresent = false;
}
//generates prices on pump display
window.onload = prices;
var pumpDisplayOne = 1000;
document.getElementById("pumpDisplayOne").innerHTML = "Total gallons pumped on this pump: " + pumpDisplayOne;
HTML:
<h3>Pump 1</h3>
<h4 id="pumpDisplayOne">Gallons</h4>
<button type="button" class="paybutton" onclick="pay()">Pay!</button>
You must Run Your javascript code after DOMReady, If your script tag is in head, move down before all </body>, or put all code in onload event.
Here is my jsFiddle update, that works.
Hello friends here's my code
function dropItems(idOfDraggedItem,targetId,x,y)
{
var html = document.getElementById('dropContent').innerHTML;
if(html.length<=0){
html.innerHTML='<img src="images/drag.jpg" alt=" " />'
}
if(html.length>0)html = html + '<br>';
html = html + document.getElementById(idOfDraggedItem).innerHTML;
document.getElementById('dropContent').innerHTML = html;
}
I want to to show a image in div when its empty.. but when it receive any data i want to remove that image by using this script .but its not working plz help me
function dropItems(idOfDraggedItem,targetId,x,y)
{
html = document.getElementById('dropContent');
if(html.innerHTML.length<=0){
html.innerHTML='<img src="images/drag.jpg" alt=" " />'
}
if(html.innerHTML.length>0)html = html + '<br>';
html = html + document.getElementById(idOfDraggedItem).innerHTML;
document.getElementById('dropContent').innerHTML = html;
}
function dropItems(idOfDraggedItem,targetId,x,y)
{
var html = document.getElementById('dropContent');
if(html.innerHTML.length<=0){
html.innerHTML='<img src="images/drag.jpg" alt=" " />'
}
if(html.innerHTML.length>0)html+='<br>';
html += document.getElementById(idOfDraggedItem).innerHTML;
document.getElementById('dropContent').innerHTML = html;
}
var html = document.getElementById('dropContent').innerHTML;
Here your passing the value to 'html'. not the reference of 'dropContent'. So you can't call 'innerHTML' on variables.
//Modified code
function dropItems(idOfDraggedItem,targetId,x,y)
{
var html = document.getElementById('dropContent').innerHTML;
if(html.length<=0){
html = '<img src="images/drag.jpg" alt=" " />'
}
if(html.length>0)html = html + '<br>';
html = html + document.getElementById(idOfDraggedItem).innerHTML;
document.getElementById('dropContent').innerHTML = html;
}
The problem is that the dropContent may not be empty even if it shows nothing; because, Javascript does not ignore the White-Spacing so there may be a white-space that keep the length bigger than zero.
Here is the solution, using the jQuery library as it has the needed methods to Trim the contents and other things:
function dropItems(idOfDraggedItem, targetId, x, y) {
var html = $("#dropContent").html();
html = $.trim(html);
if (html.length <= 0) {
var imageContent = $('<img src="images/drag.jpg" alt="" /><br />' + $("#" + idOfDraggedItem).html());
$("#dropContent").html(imageContent);
}
}
It worked for me in a test page I created.
The first line gets the html out of the element, second line trims it and thirth line checks if it is empty.
Forth line creates an element with the html string and the html content of the idOfDraggedItem element.
Fifth line sets the html content of the dropContent to the html content of the recently created element.
That's it.
Hope this works for you too.
PS the .html() method of jQuery extracts the innerHtml of the element, if you want the outerHtml, wrap the element in a div and get the .html() from div to get the outHtml of the wrapped element.