This function uses jQuery to modify the contents of a DOM element. What am I doing wrong?
function updateScore() {
alert("Test score is: " + bucket.score);
$("#testScore").innerHTML = 'Current score is: + bucket.score';
}
The alert runs, but nothing else does. I have a <p> with the id testScore, but it doesn't change when I run the function. Why?
Thanks, Elliot Bonneville
Try .html() on a jQuery object. innerHTML is for DOM-Elements.
$("#testScore").html('Current score is: '+ bucket.score);
If, for some reason, you really want to use innerHTML, you can convert the jQuery Object back to its DOM variant, for example using [0] or .get(0). Call like this, then:
$("#testScore")[0].innerHTML ='Current score is: '+ bucket.score
But I don't see why you would want to do that - since you're already writing in jQuery, there's no need to fallback to DOM methods that have a perfectly fine jQuery equivalent.
function updateScore() {
alert("Test score is: " + bucket.score);
$("#testScore").text('Current score is: ' + bucket.score);
}
try
$("#testScore").innerHTML('Current score is: + bucket.score');
The jQuery objects do not support assignment to the attributes. (Its a Javascript limitation) You have to call the function with a parameter to set something.
Related
I am trying to write a game where on-click innerText of the object changes.
Below is the function from my JS file which is called on-click. In the console I can see the expected sign, but doesn't reflect on the page.
function printx(number){
let isko = document.getElementById("r" + number);
console.log(isko);
if(isko.innerText==""){
isko.innerText = sign;
console.log(isko.innerText);
checksign();
disp.innerHTML= "<center>" + sign + " Turn " + "</center>" ;
winner();
}
}
JS Fiddle link: https://jsfiddle.net/c9ejhox4/
Your problem is that the winner function loops through and resets innerHTML for every tile item for every turn. Make sure that loop is inside the if statement to check if someone actually won.
for loop in winner() override text in td tag
There are few errors that can be corrected.
Loop in winner() function must be inside the if condition.
innerText, innerHTML and some outdated attributes are used.
You must use jquery to avoid such lengthy code.
Update this code to jquery to see if the problem solve.
I'm trying to make a loop in jQuery that finds all 'img' elements and places a caption below them, according to the value of the element's 'caption' attribute. Whenever I run the loop below, I am left with no captions under any of the images.
for (var i = 0; i < $('.myimage').length; i++) {
$('.myimage')[i].after('<h6>' + $('.myimage').attr('caption') + '</h6>');
};
However, when I run this code
$('.myimage').after('<h6>TEST</h6>');
the word 'TEST' appears below all of the images. Therefore I know my html is correct, I have no typos, and the selector is working, I just cannot get the for loop to work... What have I done wrong?
$('.myimage')[i] returns a DOM element (not a jQuery object) so there is no after method. If you want to loop, simply use .each
$(".myimage").each(function() {
//this refers to each image
$(this).after('<h6>' + $(this).attr('caption') + '</h6>');
});
You can loop through the .myimage elements like this, using .after()'s callback function
$('.myimage').after(function(){
return '<h6>' + $(this).attr('caption') + '</h6>';
});
One minor note, don't make up your own attributes. use the custom data attribute instead, like data-caption="something".
jsFiddle example
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
}
I'm creating a javavascript object which I'm calling rulesObject. The idea is for it to be a javascript object containing all of the rules I need to check to enable/disable other checkboxes that is dynamically generated from a mysql database at the very beginning of the script. For now, I'm just testing it out with two rules which I know create the scenario I'm looking for, so here's what my object looks like at the moment:
rulesObject = {
chk533570 : ["533577", "503671", "503667", "604028", "503661"],
chk503928 : ["533577", "533578","503671", "503666", "533576", "503667", "324201", "503221", "604028", "503668", "533580", "503669", "533579", "533581", "503670"]
};
Now what I need to do is access the information out of that object. If I do a simple alert(rulesObject. chk533570), it works PERFECTLY – gives me exactly what I need. However, what I'm going to need to do is access a specific rule based on what was just clicked by running through the following. So, for example, if I clicked the checkbox valued "533570", it would go through the following:
$('input').click(function(){
if(this.checked) {
checkRules(this.value, 'checked');
} else {
checkRules(this.value, 'unchecked');
}
});
(Of course I'm using jQuery there, but I'm using it throughout the web app so I don't mind going back and forth.)
Now onto my checkRules function. It's still very simple as it's in the beginning stages – I just want to alert the value of what I just selected. Again, if I do alert(rulesObject. chk533570), even within the function, I get the right result, but I need to access what I just selected, so I have to add the letters 'chk' to the beginning of the object property name and then append the justselected value (which in this case equals 533570). Here are the ways I've tried to do it:
function checkRules(justselected, state) {
rulename= 'chk' + justselected;
currentrules = rulesObject.rulename;
alert(rulename);
alert(currentrules);
}
Alert 1: chk533570
Alert 2: undefined
function checkRules(justselected, state) {
rulename= 'chk' + justselected;
alert(rulesObject.rulename);
}
Alert: Undefined
function checkRules(justselected, state) {
rulename= 'chk' + justselected;
alert(rulesObject + '.chk' + justselected);
}
Alert: [object Object].chk533570
function checkRules(justselected, state) {
alert(rulesObject.chk533570);
}
Alert: 533577,503671,503667,604028,503661
So, any idea how to properly call that name so that I get the right results? I also tried not having the 'chk' in there at all, but the javascript object didn't like a completely numeral property.
obj.key is the same as obj['key'] - but in the second way the key can be dynamic since it's a plain JavaScript expression.
So you can simply use rulesObject['chk' + justselected]:
function checkRules(justselected, state) {
alert(rulesObject['chk' + justselected]);
}
Long time ago people used to use alert(eval('rulesObject.chk' + justselected)); by the way. While this works, do not use this. Using eval() should be avoided at all times; and in this case there is a much cleaner way anyway.
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!