Basically, I have a .each loop that iterates over some data and for each item in the data set it appends a span class to the DOM.
$('.selected_cont').append('<span class="' + classes + '"></span>');
Classes is just the variable ive creative above that saves the name of the data I iterate over.
So after iterating over the data I could have 5, 10 span tags on the DOM all with different class names.
My issue is, I don't add the span tags in the order they're in the data so the latest one ive iterated over will be the first.
So I've created a variable
var incrementalEle = 1;
How can I add this variable into my string $('.selected_cont').append('<span class="' + classes + '"></span>'); so each class has something similar to theClassName1, theClassName2 and so on.
This errors when I try it $('.selected_cont').append('<span class="' + classes + + var incrementalEle++ + '"></span>');
As you are using jQuery to create element, use .addClass() method at set the classes.
$('.selected_emoji').append($('<span />').addClass(classes + incrementalEle++ ));
OR, when using string concatenation use operator's properly
$('.selected_emoji').append('<span class="' + classes + incrementalEle++ + '"></span>')
Related
My question is asked before for using javascript variables with the Single jQuery selector, As in this post below.
How to use javascript variables in jquery selectors
But my question is how to use one variable with two or more selectors?
var itemId = $(this).closest('li').attr('id');
This is for one selector
var contentType = $('#' + itemId + ' .content-type');
But how to use itemId when i have two selectors in one row like below
var contentType = $('.content-type1, .content-type2');
You do it the same way, by adding a , between 2 selectors.
As of, you are doing:
var contentType = $('#' + itemId + ' .content-type');
For 2 elements, you use ,:
var contentType = $('#' + itemId + ' .content-type1, #' + itemId + ' .content-type2');
You can concat manually as much as you need but maybe you can do a selector prepare the following way so you can append n-times the variable easily:
var itemId = $(this).closest('li').attr('id');
var selector = '#{i}.content-type1, #{i}.content-type2, #{i}.content-type3'; // you can extend this as much as you like or even add a loop to construct content types
var finalSelector = selector.split('{i}').join(itemId); // doing the replace
var contentType = $(finalSelector);
Where {i} is just a fictive placeholder string. I think this is a bit more readable. Anyways your question is kinda strange when it comes to the
"or more selectors"
part logically. Maybe you need to change your code flow/implementation technique for whatever you are trying to achieve.
I have this Jquery code:
var $affectedTRs = $('#location-usergroup-table tr[data-department-id="' + departmentID + '"')
So this contains all trs and I can run functions like find etc.
Now I want to push an item in this $affectedTRs
But this is not working:
$affectedTR.concat($('#location-usergroup-table tr[data-domain-id="' + domainID + '"'));
How do I push something manually in this selected object so I can have all Jquery functions like find etc available on it.
You can use jQuery's add() method: https://api.jquery.com/add/
$newSelection = $affectedTR.add($('#location-usergroup-table tr[data-domain-id="' + domainID + '"'));
Perhaps you want this:
$("#location-usergroup-table").append("<tr data-domain-id=\"" + domainID + "\""></tr>");
To add a new element to existing container, use .append(). More details here.
Your $affectedTR has all the rows i.e DOM elements. If you wish to create new row in the table, try jquery append
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>'
]);
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.)