Refering to a HTML ID with mutliple variables - javascript

So, I am trying to create a game with blocks in the level being send from the server.
I have loop cycling through the blocks each time it recieves an update from the server. It will then if the block is solid, append the block to the html document if it is not already existing.
if(blocks[blockCount].solid === true){
if($("#" + blocks[blockCount].posX.toString() + "," + blocks[blockCount].posY.toString()).length > 0){
alert("Block already exists");
}else{
$("body").append("<div style='height: " + blockSize + "px;width: " + blockSize + "px;background-color: blue;position: absolute;display: inline;margin-left: " + blocks[blockCount].posX * blockSize + "px;margin-top: " + blocks[blockCount].posY * blockSize + "px;' id='" + blocks[blockCount].posX.toString() + "," + blocks[blockCount].posY.toString() + "'> </div>");
}
}
blocks[blockCount].posX and Y should both equal to 4. But for some reason they keep being created, the if statement does for some reason not work. Can you please explain me why? or post the correct code. Thanks a lot for your help. :)
I learned here: How to check if element exists in the visible DOM?
that the jquery .length would allow me to see if the element already existed.

You can't have a , in an ID (or class for that matter) [see comment, you can, but why make life hard for yourself] - because a , is used as a separator in CSS .. i.e
#id1,div would select an element with id="id1" AND any div
you're creating elements with id's like "123,456" - which as a CSS selector would be #123,456
solution: try using _ instead of ,
also, I'm not sure if an id is allowed to begin with numbers, but don't quite me on that, if not, just prepend your id's with x or whatever
note: the HTML5 spec allows ID's to begin with numbers, however, that too does not work in CSS selectors (for CSS at least, not tested with jQuery or querySelector[All] )
you'll end up with id's like x123_456 - which is OK

Since , has a special meaning in CSS, you'd have to escape in in your selector. To write a CSS selector targeting an element with id="foo,bar", you have to write #foo\,bar. In jQuery selector allow you to do the same, but you need to remember about JS syntax and write $("#foo\\,bar") to achieve what you want (the first backslash is to escape the second one in JS string).
Also, as Jaromanda X pointed out, IDs can't start with numbers so you'll have to prepend it with a letter.
To sum up, your code may look like this:
if(blocks[blockCount].solid === true){
if($("#x" + blocks[blockCount].posX.toString() + "\\," + blocks[blockCount].posY.toString()).length > 0){
alert("Block already exists");
} else {
$("body").append("<div style='height: " + blockSize + "px;width: " + blockSize + "px;background-color: blue;position: absolute;display: inline;margin-left: " + blocks[blockCount].posX * blockSize + "px;margin-top: " + blocks[blockCount].posY * blockSize + "px;' id='x" + blocks[blockCount].posX.toString() + "," + blocks[blockCount].posY.toString() + "'> </div>");
}
}

Related

How to add an ID value to a div append

I have a "fault-counter" that stores a value of all incorrect answers. It starts at 0 and goes up one for every wrong answer.
I'm looking to have the results screen show the amount of faults you've made. So if the div #fault-counter has a value of 3, the end text will say "Sorry, you've made 3 faults!"
This is the code I've tried, but it doesn't seem to work. Any ideas on how to do this?
var faultcounter = $('#fault-counter');
$('#slickQuiz').prepend('<h1>Sorry, you have ' + $('#fault-counter') + ' faults!</h1>');
EDIT:
The HTML for the 'fault-counter' looks like this:
<div id="fault-display">
<div id="fault-counter">0</div>
<h3>FAULTS</h3>
</div>
And the jQuery being used to increase the value for every wrong answer is this:
$(".failQuestion").click(function(){
$('#fault-counter').html(function(i, val) { return val*1+1 });
});
Try this, as your fault-counter is a div than .text() should suffice.
$('#slickQuiz').prepend('<h1>Sorry, you have ' + $('#fault-counter').text() + ' faults!</h1>');
var faultcounter = $('#fault-counter').val();
$('#slickQuiz').prepend('<h1>Sorry, you have ' + faultcounter + ' faults!</h1>');
You'll have to grab the value from #fault-counter using .val() and then append the variable, instead of the jQuery selector to the #slickQuiz.
That being said, i'm assuming you're using an input or select for #fault-counter. Otherwise .text() would be sufficient
i think there is a problem :
var faultcounter = $('#fault-counter');
if $('#fault-counter') is a input control then use "VAL()" :
$('#slickQuiz').prepend('<h1>Sorry, you have ' + $('#fault-counter').val() + ' faults!</h1>');
OR
if $('#fault-counter') is a DIV control then use "html()" :
$('#slickQuiz').prepend('<h1>Sorry, you have ' + $('#fault-counter').html() + ' faults!</h1>');
var faultcounter = $('#fault-counter').text();
$('#slickQuiz').prepend('<h1>Sorry, you have ' + faultcounter + ' faults!</h1>');
This is what you want to use because you mentioned that #fault-counter is a div. If that's so then you'll want to use the .text method. If it's an input or textarea then use the .val method.

Dynamically changing innerText's start without eval()

I have some code (several batches) that look like this:
1 <div id="backgrounds" class="centery">Backgrounds
2 <div id="bk1" class="attr">Background 1
3 <div class="container">
4 <!-- Lots more HTML here /-->
5 </div>
6 </div>
7 </div>
I have a JS function I wrote (changefirstCharacters) that will return the script to change line 2 to read:
2 <div id="bk1" class="attr">Some text I specify
But because I want this to only execute when an event listener fires, it only outputs the code, rather than evaluating it. As a result, my event listener contains a line like this:
eval(changeFirstCharacters('bk1', "'" + document.getElementById('background1').value + "'"));
Where background1 is a select box.
How can I re-write changeFirstCharacters to not need eval, but still work only when called?
changeFirstCharacters() code
function changeFirstCharacters(id, newText) {
return 'document.getElementById(\"' + id + '\").innerHTML = ' + newText + ' \+ document.getElementById(\"' + id + '\").innerHTML.substr(' + document.getElementById(id).innerText.length + ', document.getElementById(\"' + id + '\").innerHTML.length \-' + document.getElementById(id).innerText.length + ')';
}
I don't see what's so dynamic about that statement. The only reason we need eval is when code is dynamically generated, but neither newText nor id changes the produced code. Therefore, the following ought to work:
document.getElementById(id).innerHTML = newText +
document.getElementById(id).innerHTML.substr(document.getElementById(id).innerText.length,
document.getElementById(id).innerHTML.length - document.getElementById(id).innerText.length);
Called by (without adding quotes around the second argument):
changeFirstCharacters('bk1', document.getElementById('background1').value)
Also that first code calls getElementById(id) five times, which is not only a performance hit, it's rather ugly. You might want to rewrite it as:
var el = document.getElementById(id);
el.innerHTML = newText + el.innerHTML.substr(el.innerText.length,
el.innerHTML.length - el.innerText.length);

How to get the total of the list ordered, with Javascript

I'm making a code of a online delivery webpage, and I having a hard time trying to figure out how to output the total of the list ordered by the user.
function ListOrder(){
document.getElementById('order').innerHTML += "<div id=\"YourOrders\">" + + document.getElementById('FoodName').value + document.getElementById('quantity').value + document.getElementById('Totality').value + "</div><br>";}
Edited: I want to know how I can get the sum of the total price. So, I placed a parseInt between the document.getElementById('Totality').value . It looks like this now,
function ListOrder(){
document.getElementById('order').innerHTML += "<div id=\"YourOrders\">" + + document.getElementById('FoodName').value + document.getElementById('quantity').value + parseInt(document.getElementById('Totality').value) + "</div><br>";}
Can someone help me make a function or something for that? Javascript only, please. I'm still kinda new at it.
function ListOrder(){
document.getElementById('order').innerHTML +=
"<div id=\"YourOrders\">" +
parseInt(document.getElementById('FoodName').value) +
parseInt(document.getElementById('quantity').value) +
parseInt(document.getElementById('Totality').value) +
"</div><br>";
}
the kernel of your code should look like the following (double + operator deleted, reformatted):
function ListOrder(){
document.getElementById('order').innerHTML +=
"<div id=\"YourOrders\">" + (
document.getElementById('FoodName').value
+ document.getElementById('quantity').value
+ document.getElementById('Totality').value
)
+ "</div><br>"
;
}
You've phrased your question in a way that suggests you wish to output an order list assembled from the content of all (html) elements with certain ids.
this won't work reliably:
Ids should be document unique.
The Js functions you use do not iterate over lists.
instead, proceed along the following lines (which assume that you import jquery, a cross-browser dom-handling and ajax library (which you should use anyway :)):
function ListOrder(){
var e_orders = $("<div id=\"YourOrders\">");
$("#order").append(e_orders);
$(".FoodName").each ( function ( idx_fn, e_fn ) {
$(e_orders).append(
$("<div/>").append(
$(e_fn).val()
+ $(e_fn).nextAll('.quantity').val()
+ $(e_fn).nextAll('.Totality').val()
);
);
$(e_orders).append("<br>");
});
return e_orders;
}
The code template assumes that the source data are elements with value attributes being marked with css classes quantity, Totality and 'FoodName``, that these elements are siblings and unique within a container element for each item incl. quantity information. It should be flexible enough to be tailored to your actual needs and html structure.

jQuery append trouble with url parameter

I've been working for hours trying to get the single and double quotes nested correctly in order for this search result display to work, with having a dynamically appended "uniqueId" in part of the URL string on output.
Basically, the part of the JS code that is giving me trouble is this:
$('#results-list').append("<li rel='" + this.uniqueId + "'>" + this.dateTimeStamp + " — " + this.message + " — " + "<a class='iframeSmaller' href='commentDetails.php?uniqueId='" + this.uniqueId + "''>XXX</a>" + "</li>");
I want to have the "this.uniqueId" after the equal sign so that it generates a dynamic URL, which I then am going to link to a "details" page for that unique ID.
Can anyone please help me with the "this.uniqueId" syntax to get this correctly inserted into the URL for output?
Sorry if I am being unclear, I am learning all of this by the day :)
thanks!
ps... this does work, but it has a hardcoded uniqueID... what I want is a dynamic one based on the row, which is working as far as the "rel" part goes, just not the anchor part...
$('#results-list').append("<li rel='" + this.uniqueId + "'>" + this.dateTimeStamp + " — " + this.message + " — " + "<a class='iframeSmaller' href='commentDetails.php?uniqueId=32'>XXX</a>" + "</li>");
thanks again for any help with this syntax (or if there's a better way to go about what I'm trying to do)...
The quoting in your HTML for the anchor isn't quite right. You have this:
+ "<a class='iframeSmaller' href='commentDetails.php?uniqueId='" + this.uniqueId + "''>XXX</a>" +
I think it should be this (fix quoting on the link URL):
+ "<a class='iframeSmaller' href='commentDetails.php?uniqueId=" + this.uniqueId + "'>XXX</a>" +
You could see what's going on better if you build the string into a variable and then do a console.log() on the string of HTML you've built or look at its contents in the debugger.
Replace this part of your code:
... uniqueId='" + this.uniqueId + "''>XXX</a>" + "</li>");
for this one:
... uniqueId=" + this.uniqueId + "'>XXX</a>" + "</li>");

jQuery: trying hook a function to the onclick when page loads

I have seen a similar question, HERE and have tried that, but I can't seem to get it working.
Here is my code for dynamically generating table rows.
for (var contribution = 0; contribution < candidate.contributions.length - 1; contribution++) {
var id = candidate.contributions[contribution].donor_id;
var uid = candidate.contributions[contribution].user_id;
$("#history-table").append(
"<tr onclick='" + parent.viewEngine.pageChange('public-profile', 1, id, uid) + ";>" +
"<td class='img-cell'>" +
"<img class='profile-avatar-small' src='/uploads/profile-pictures/" +
candidate.contributions[contribution].image + "' alt='' /></td><td class=''>" +
"<h2>" + candidate.contributions[contribution].firstname +
" " + candidate.contributions[contribution].lastname + "</h2></a><br/><br/>" +
"<span class='contribution-description'>" + candidate.contributions[contribution].contribution_description + "</span></td>" +
"<td><h3>$" + formatCurrency(candidate.contributions[contribution].contribution_amount) + "</h3></td></tr>");
}
This still executes the click event as soon as the page loads, which is not the desired behavior. I need to be able to click the tr to execute the click event.
Pass the whole thing as a string:
"<tr onclick='parent.viewEngine.pageChange(\'public-profile\', 1, " + id + ", " + uid + ");>" // + (...)
But, as you are using jQuery, you should be attaching the click handler with .on().
(I really don't recommend using inline event handlers like that, especially when you're already using jQuery, but anyway...)
The problem is that you need the name of the function to end up in the string that you are passing to .append(), but you are simply calling the function and appending the result. Try this:
...
"<tr onclick='parent.viewEngine.pageChange(\"public-profile\", 1, " + id + "," + uid + ");'>" +
...
This creates a string that includes the name of the function and the first couple of parameters, but then adds the values of the id and uid variables from the current loop iteration such that the full string includes the appropriately formatted function name and parameters.
Note that the quotation marks around "public-profile" were single quotes but that wouldn't work because you've also used single quotes for your onclick='...', so you should use double-quotes but they need to be escaped because the entire string is in double-quotes.
I'm wondering if you might be better simplifying things a bit.
If your rows are being dynamically added, then try putting some kind of meta-data in the <tr> tag, e.g. something like this:
<tr id="id" name="uid">
Then try the following with your jQuery (v.1.7 required):
$('#history-table tr').on('click', function(){
parent.viewEngine.pageChange('public-profile', 1, this.id, this.name);
});
This will likely require modification depending on how your page rendering works but it's a lot cleaner and easier to read having been removed from your main table markup.
Well that's because you're executing the function, not concatenating it. Try:
onclick='parent.viewEngine.pageChange("public-profile", 1, id, uid);'
Take this ->
$("#contribution-" + uid).click(function(){
parent.viewEngine.pageChange('public-profile',1, id, uid);
});
And do two things:
1) Move it outside of the 'for' statement
As soon as the for statement is executed, the click function will be executed as well. The click function is not being supplied as a callback function in this for statement.
2) Change it to ->
$("tr[id^='contribution-'").on('click', function(){
var idString = $(this).attr("id").split("-"); //split the ID string on every hyphen
var uid = idString[1]; //our UID sits on the otherside of the hyphen, so we use [1] to selec it
//our UID will now be what we need. we also apply our click function to every anchor element that has an id beginning with 'contribution-'. should do the trick.
parent.viewEngine.pageChange('public-profile',1, id, uid);
});
This is my solution.

Categories

Resources