I have got this link:
Visit imLive.com
I want to use this code to add/change different url parameters:
$("a.sitelink_external.imlive").each(function(){
$params=getUrlVars(document.URL);
var promocode_addition='';
if('INFO'==$params['ref']){
promocode_addition='LCI';
}
$(this).attr("href", 'http://im.com/wmaster.ashx?WID=124904080515&cbname=limdeaive&LinkID=701&queryid=138&promocode=LCDIMLRV" + i + promocode_addition+"&"FRefID=" + FRefID + "&FRefP=" + FRefP + "&FRefQS=" + FRefQS');
});
The problem is that that jquery code doesnt work..I tried to move it to document ready..but it doesnt work there too..
The thing that jumps out at me is that you're mixing your double and single quotes on this line:
$(this).attr("href", 'http://im.com/wmaster.ashx?WID=124904080515&cbname=limdeaive&LinkID=701&queryid=138&promocode=LCDIMLRV" + i + promocode_addition+"&FRefID=" + FRefID + "&FRefP=" + FRefP + "&FRefQS=" + FRefQS');
Try changing them all to double quotes, and remove the extra " from after the ampersand in "&"FRefID=" - like this:
$(this).attr("href", "http://im.com/wmaster.ashx?WID=124904080515&cbname=limdeaive&LinkID=701&queryid=138&promocode=LCDIMLRV" + i + promocode_addition+"&FRefID=" + FRefID + "&FRefP=" + FRefP + "&FRefQS=" + FRefQS);
The way you had it was a single string containing stuff that looked like code. The way I've changed it is several strings and variables being concatenated together... (Note the difference with StackOverflow's syntax highlighting.)
Note also that the following code:
$params=getUrlVars(document.URL);
var promocode_addition='';
if('INFO'==$params['ref']){
promocode_addition='LCI';
}
...can be moved to before the .each() loop, since it operates only on the document and thus will produce the same results on every iteration.
(Of course there could be other problems since you reference several variables that aren't shown.)
Related
First post here, so please be gentle ;-)
I've been learning coding over the last couple of weeks by making a dummy page, and been implementing what i learn on it incrementaly as i progress, hence it's a mixed bag where the functionality/code is according to when i wrote it, based on pure html/CSS, inline javascript, external javascript, and finally jquery.
So i mostly wrapped it up and i'm now cleaning up the mess, and part of my mission is to cull functions and lines of codes, and in one of them i'm kind of stuck.
The before was 30 buttons calling to 30 different functions onclick like so:
function cell3() {
document.getElementById('base3').src='images/1/3/' + x + '.png';
document.getElementById('base3b').src='images/1/3/' + x + '.png';
document.getElementById('v2base3').src='images/2/3/' + x + '.png';
document.getElementById('v2base3b').src='images/2/3/' + x + '.png';
document.getElementById('cell3').style.backgroundColor= x ;
}
Where a global variable (x) defines the folder paths for images to replace the images within some divs when clicking the button (cell3). It also changes the bGroung color of it. Sorry if the naming is a bit confusing...
So i'm removing all 30 functions and the 30 onclick calls with this bit of jquery:
$('button').click(function(){
var eyeD = $(this).attr("id");
var newURLa = 'images/1/' + eyeD + '/' + x + '.png';
var newURLb = 'images/2/' + eyeD + '/' + x + '.png';
$('base' + eyeD).attr('src', newURLa);
$('base' + eyeD + 'b').attr('src', newURLa);
$('v2base' + eyeD).attr('src', newURLb);
$('v2base' + eyeD + 'b').attr('src', newURLb);
$(this).css( "background-color", x );
document.getElementsByid('check').innerhtml = eyeD;
});
For that to 'work' i changed the button's names from 'cell1', 'cell2, etc. to '1', '2', etc.
Now the thing is, when clicking on the buttons the var 'eyeD' takes the value from the button ok. ('1', '2', etc.). The elements ID's are formed correctly ('base1', 'base2'... 'base1b', base2b'...), and the URL's are formed correctly. (The last line in the code is a p element that displays values so i could try to troubleshoot it) The background color also changes as expected. But the images do not get replaced.
Tried adding commas to the resulting URL's in case it was a syntax issue, but nothing happens. i even went freestyle and tried it with the =url() on it, different commas in different places, etc. So basically scraping the barrel here. Also wrote a url without variables to see if that would work, but still nothing. Also getting no errors when looking at the console.
It's probably a basic 'DOH!' thing, but right now i have a mental block...
Also, is there a way to keep the original naming and just retrieve the numbering part of the ID's? Thought about using the [4] identifier to get the 5th digit, but that won't work when running double digit numbers. (10, 11, etc)
Thanks!
Your jQuery lines accessing the elements are missing the # sign.
Change these...
$('base' + eyeD).attr('src', newURLa);
To this...
$('#base' + eyeD).attr('src', newURLa);
Also, your last line where you use plain JS, can be done in jQuery as well with less code.
document.getElementsByid('check').innerhtml = eyeD;
To...
$("#check").html(eyeD);
However, you should always use distinct ID's for elements. If you need to use multiple elements at the same time, use a class instead.
$(".check").html(eyeD);
You're grabbing an element incorrectly.
Either Grab an element by it's class name like so:
$('.v2base' + eyeD + 'b').attr('src', newURLb);
Or by its ID:
$('#v2base' + eyeD + 'b').attr('src', newURLb);
Problem solved!! It was indeed calling the id with the hash, but also it has to be called with double quotation marks. Single inverted commas won't work.
So the working format is
$("#v2base" + eyeD + "b")
but it won't work like so
$('#v2base' + eyeD + 'b')
Thanks everyone, it's been emotional
I'm having a bit of trouble correctly displaying a message in a webpage I am trying to create. The code I have is:
content.innerHTML += "<button 'onclick=\"likeFunction(" + feed.messages[y]._id + ")\">" + "Like(" + feed.messages[y].likesCount + ")" + "</button>"
When I inspect the element on the page source, I get this output:
<button 'onclick="like(idOfObject)">Likes(likeNumber)</button>
What I need it to look like is:
<button 'onclick="like("idOfObject")">Likes(likeNumber)</button>
I'm a bit confused on how I would add more single or double quotes and where to escape them correctly to get this desired output.
I think I see a few typos. Most noticeably with the leading ' in front of onclick. I don't think this needs to be here.
As for formatting the string, consider looking into template literals introduced in ES6.
Might look something like this:
content.innerHTML += `<button onclick="likeFunction(${idOfObjectVariable})">Likes (${likeCountVariable})</button>`
Hope this helps
You're so close! First, you need to remove the ' before onclick. If you want to add double quotes around the idOfObject, then you just need escape one double quote after likeFunction( and one double quote before )\">".
"<button onclick=\"likeFunction(\"" + feed.messages[y]._id + "\")\">"
The only problem is that when the double quotes around your variable idOfObject render, they'll correspond to the opening and closing quotes you already have for onclick. So, your solution should have single quotes inside of double quotes:
"<button onclick=\"likeFunction(\'" + feed.messages[y]._id + "\')\">"
I would have guessed what you wanted in your HTML would be:
<button onclick="like('idOfObject')">7</button>
or
<button onclick='like("idOfObject")'>7</button>
You probably do not want to quote the entire on-click attribute, just the part on the right hand side of the = .
content.innerHTML += "<button onclick=\"like('" + feed.messages[y]._id + "')\">" + ...
I'm guessing you also probably don't want something that gets displayed to the user that looks like a function all, but the result of the function call, but that is not what you were asking about.
You SHOULD NOT concatenate html manually from untrusted input (suppose someone injected malicious html code to your feed.messages[y]._id or another field). Sanitization is one of your options but it's like patching a huge hole.
You can read more about preventing those security attacks named XSS here.
Consider creating your DOM manualy with createElement API and bind your event handlers manually.
function renderButton(content, feed, y) {
function likeFunction() {
alert("LIKE" + feed.messages[y]._id);
};
var button = document.createElement("button");
var text = document.createTextNode("Like(" + feed.messages[y].likesCount + ")");
button.appendChild(text);
button.addEventListener('click', likeFunction)
content.appendChild(button);
}
Then you can just render your button with a simple function call.
renderButton(content, feed, 0)
I am trying to use JavaScript to have a dynamic list, and I need to use a lot of of quotes to make the <li> line work as it should, but I cannot get innerHTML to output the correct syntax to the html doc.
here is my JS:
function settabnumber() {
alert("set tab number function called");
var settabcount = 3;
var menucode;
var i=0;
for(basetabcount = 0; basetabcount < settabcount; basetabcount++){
i++;
menucode = menucode + "<li>" + tabnames[i] + "</li>";
}
document.getElementById("eetabmenu").innerHTML = menucode;
}
Any ideas?
Try...
menucode = menucode + '<li>' + tabnames[i] + '</li>';
Always use single quotes to hold HTML strings so you can then freely use the obligatory double quotes.
I made a JSFiddle attempting to reproduce your issue, but it wasn't occurring: https://jsfiddle.net/qf19wvr0/
Either way, as the other commenters said, you should use single quotes. OR, if you're working in an ES6 environment (using a transpiler like Babel), you can use template strings:
menucode += `<li>${tabnames[i]}</li>`
Which makes your snippet a lot more readable.
However:
If you're doing complex enough work that you're looping over a collection and building up DOM nodes from strings, you may want to consider using some kind of templating system (like Handlebars, Mustache, React, or anything of the sort) to abstract some of your view creation logic. Having HTML strings in your JavaScript is a pretty big code smell and likely means you're mixing view logic with business logic.
Use single quotes ' inside of your double quotes, or viseversa
menucode = menucode + '<li>' + tabnames[i] + '</li>';
OR
menucode = menucode + "<li><a href='#tabs-" + i + "'>" + tabnames[i] + "</a></li>";
The first one is preferred
I am working with Jquery/javascript/html. I am trying to display a button inside of tags in my table. I am appending the information into/onto a section on my html page. Code is as follows:
<html>
<body>
<p id="report_area"></p>
</body>
</html>
Javascript file below
$('#report_area').append('<table>');
$('#report_area').append('<tr>');
$('#report_area').append('<th>' + view + '</th><th>' + col_1 + '</th><th>' + col_2 + '</th><th>' + col_3 + '</th>');
$('#report_area').append('</tr>');
var btn=$('<button/>');
btn.text('View');
btn.val=item.SURVEY_JOB_ID;
btn.id=item.SURVEY_JOB_ID;
// recently added code - start
btn.click(function()
{
window.localStorage.setItem("MyFirstItem", 10);
window.location = 'GoToThisOtherPage.htm'
}
// recently added code - end
$('#report_area').append('<tr><td>'+ btn +'</td><td>' + item.JOB_NUMBER +
'</td><td>' + item.TITLE + '</td><td>' + item.MODIFICATION_NUMBER + '</td></tr>');
$('#report_area').append('</table>');
THis seems to work correctly however, the button is not showing up correctly. It shows up as an object. All the other data displays correctlyMy table row is displayed as :
[object Object] 12 New Job Title 0
[object Object} 30 Title Help Me 1
I'm not sure why it is displaying as [object Object]. When I do something as simple as:
$('#report_area').append(btn);
the button shows up on the page correctly. Any help on this would be greatly appreciated. Thanks in advance.
To understand why this does not work, you have to look at the documentation for append.
Type: htmlString or Element or Array or jQuery
append is able to except any of those types, and handle each of them differently, so when you pass it an element (actually jQuery collection), it is able to intelligently convert it into the desired html.
However, in your case, you are passing it a string, so it will naively treat the string as html. The reason that this produces [object Object], is because it is relying on native JavaScript to convert the element into a string. You'll produce the same output with console.log(btn).
// append recieves a jQuery collection, calls appropriate methods to obtain html
$('#report_area').append(btn);
// append receives a string, blindly assumes that it is already the desired html
$('#report_area').append(btn + '');
Solution 1 - Append separately
From your comments on other answers, it doesn't seem like this solution works. I think this is because append will automatically add the close tags for the tr and td when appending, causing the button to be added afterwards. You could check if this was the case by looking at the html produced in the developer tools of your browser.
$('#report_area').append('<tr><td>', [btn, '</tr></td>'])
Solution 2 - Convert to string properly
$('#report_area').append('<tr><td>'+ btn[0].outerHTML +'</td><td>')
Solution 3 - Constructing everything as jQuery collections
I think the main problem you have been having is to do with mixing elements and strings. I've written a working jsfiddle solution that constructs everything as jQuery collections.
var table = $('<table>');
var btnRow = $('<tr>');
var btnCell = $('<td>');
var btn=$('<button>');
btn.text('View');
btn.val('val');
btn.attr('id', 'id');
btn.on('click', function()
{
window.alert('Click');
});
btnCell.append(btn);
btnRow.append(btnCell);
table.append(btnRow);
btnRow.append('<td>1</td><td>2</td><td>3</td>');
$('#report_area').append(table);
JavaScript is converting btn to a string because you're concatenating several strings to it.
It should work if you do this.
$('#report_area').append('<tr><td>');
$('#report_area').append(btn);
$('#report_area').append('</td><td>' + item.JOB_NUMBER +
'</td><td>' + item.TITLE + '</td><td>' + item.MODIFICATION_NUMBER + '</td></tr>');
$('#report_area').append('</table>');
You're attempting to set native DOM properties on a jQuery object. Remember, a jQuery object is a superset of a native DOM object. Alter your code to use the .val() and .attr() jQuery methods like so:
var btn=$('<button/>');
btn.text('View');
btn.val(item.SURVEY_JOB_ID);
btn.attr('id', item.SURVEY_JOB_ID);
Alternately, you can chain these methods together for convenience:
var btn= $('<button/>')
.text('View')
.attr('id', item.SURVEY_JOB_ID)
.val(item.SURVEY_JOB_ID);
Finally, alter your use of the .append() method to append the content like so:
$('#report_area').append(
'<tr><td>',
[
btn,
'</td><td>' + item.JOB_NUMBER + '</td><td>' + item.TITLE + '</td><td>' + item.MODIFICATION_NUMBER + '</td></tr></table>'
]);
This is fixed! Already have a correct answer.
("<div class='script' onclick='" + 'open_script(' + data + ', ' + data_name_found + ')' + "'>" + data_name_found + "</div> ")
What is wrong with the above code? I am making a project, and am assigning a variable that information to store inside of a div. The variable data is all the data, and data_name_found is the specified name is all the names with other info inside the data variable. The open_script function is supposed to open a div with information about the given script. Sort of like an edit menu, if at all possible, I would prefer not to give out any more code from my project.
Thanks for the help in advance!
EDIT--> The problem is that it won't even trigger the other function. I have been working on this problem for quite a while and can't find out why. May be cause I'm tired, sorry if it's a silly mistake!
It's hard to tell without more code, but the offending piece of code seems to be:
+ 'open_script(' + data + ', ' + data_name_found + ')'
If data and data_name_found are strings, they're being outputted into the HTML without quotation marks. Assuming that's the problem, this should fix it:
+ 'open_script("' + data + '", "' + data_name_found + '")'