Not able to bind value to tooltip using replaceWith() - javascript

I have used jQuery .replaceWith() to insert new DOM contents. All the contents are getting replaced but the value of title does not bind.
I have tried the below code but the tooltip only shows {{descriptions.title}} instead of the text that's supposed to be shown.
Here is my code:
$scope.showDescription = function(descriptions) {
$("#description").find('span#header').replaceWith("<span id='header' class='mleft' title='{{descriptions.title}}'>" + descriptions.name + " - " + descriptions.title + "</span>");
}
I expect the tooltip to display descriptions.title value instead of just {{descriptions.title}}

You only add the string {{description.title}} as your title, you need to add the variable itself:
$scope.showDescription = function(descriptions) {
$("#description").find('span#header').replaceWith("<span id='header' class='mleft' title='" + description.title + "'>" + descriptions.name + " - " + descriptions.title + "</span>");
}
Edit:
A in my opinion better approach would be to not use replaceWith here but just to change the desired attributes:
$scope.showDescription = function(descriptions) {
$("#description").find('span#header').attr("title",description.title).html(descriptions.name + descriptions.title);
}
That way you can change the html itself and don't need to adapt the JS.

You need to concatenate it in - that's not an Angular variable, it's just normal JS:
$scope.showDescription = function(descriptions) {
$("#description").find('span#header').replaceWith("<span id='header' class='mleft' title='" + descriptions.title + "'>" + descriptions.name + " - " + descriptions.title + "</span>");
}
Or just use template strings (ES6):
$scope.showDescription = function(descriptions) {
$("#description").find('span#header').replaceWith(`<span id='header' class='mleft' title='${descriptions.title}'>${descriptions.name} - ${descriptions.title}</span>`);
}

You can try this. Its working fine
$("#description").find('span#header')
.replaceWith("<span id='header' class='mleft' title="+ descriptions.title+">" + descriptions.name + " - " + descriptions.title + "</span>");

Related

HTML+JavaScript: Can't add multiple parameters to onclick despite using escaped quotes

I am trying to append an HTML div with multiple parameters in the onclick function. Even though I am using escape quotes, the HTML is not rendered properly.
This is my HTML:
$("#city-list").append("<div class='user-panel' id='" + user.id + 'onclick=\'openChat(\'' + user.id + '\',\'' + user.username + '\',\'' + user.sex + "\'\")><b>" + user.username + ", " + "(" + user.sex + ", " + user.age + ")</div>");
This is what is rendered:
<div class="user-panel" id="A61o-ko0zVVJaxTbAAAHonclick=" openchat('a61o-ko0zvvjaxtbaaah','adamlee','male'")=""><b>adamlee, (male, 17)</b></div>
You missed closing quote for id attribute and function in onclick should have double quote because single quotes are used in it.
const user ={id: 'a61o-ko0zvvjaxtbaaah', username: 'henryzhu', sex: 'male', age: 17 }
$("#city-list").append("<div class='user-panel' id='" + user.id + '\' onclick="openChat(\'' + user.id + '\',\'' + user.username + '\',\'' + user.sex + "')\"><b>" + user.username + ", " + "(" + user.sex + ", " + user.age + ")</div>");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="city-list"></div>
You can use this code to work on all browsers, just need to use quotations properly as used in below code:
$("#city-list").append("<div class='user-panel' id='" + user.id + "' onclick='openChat(\"" + user.id + "\", \"" + user.username + "\", \"" + user.sex + "\")'><b>" + user.username + ", (" + user.sex + ", " + user.age + ")</b></div>");
If you are already using jQuery why not use a jQuery on click function?
Not saying it is wrong to use onclick inline but if you were curious this is another way you could achieve what you are going for.
// Add some data
var user = ({
"id":"a61o-ko0zvvjaxtbaaah",
"username":"henryzhu",
"sex":"male",
"age":"17"
});
var content = "";
// Set up your data in data-attributes
content += "<div class='user-panel' \
data-id='" + user.id + "' \
data-username='" + user.username + "' \
data-sex='" + user.sex + "' \
data-age='" + user.age + "'>";
// viewable text
content += "<b>" + user.username + ", (" + user.sex + ", " + user.age + ")";
content += "</div>";
$("#city-list").append(content);
//---------------------------------------------------------------------
// jQuery on click function to call the openChat
// putting the data you need in data attributes let you grab what you need on the clicked name and
// submit it to the chat funciton.
$("body").on("click", ".user-panel", function(){
var userid = $(this).attr("data-id");
var username = $(this).attr("data-username");
var sex = $(this).attr("data-sex");
var age = $(this).attr("data-age");
openChat(userid , username , sex);
});
// Your chat function
function openChat(id, name, sex){
console.log(id + " | " + name + " | " + sex);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="city-list"></div>
If you do not need to support IE you might want to consider using back-ticks (`) in this case. They provide functionality, a more readable experience and are less error prone. More information here MDN documentation for template literals.
Your example with back-ticks would be:
$("#city-list").append(`
<div class="user-panel"
id="${user.id}"
onclick="openChat('${user.id}', ${user.username}, ${user.sex})">
<b>${user.username}, (${user.sex}, ${user.age})
</div>
`)

Can this be turned into a for loop?

I would like to clean this up with a For loop. What would be the most efficient way coding this out?
I'm creating a search form that looks through a database for the specific form criteria. The way I have it coded would only work for the 8 Fields. But it is possible for the search form to have more then 8. For now though, I'd like to be able to map the results and display in a results page.
This is what I tried. This did not work at all and probably make no sense to anyone lol.
var obj =data[0]
$.get("obj", {data: $('select["Fields.DisplayName" + Fields.DataValue]').val()},
function(data){
$.each(data, function(i, item) {
alert(item);
});
}
);
This works for getting the data and displaying it how I'd like.
var obj = data[0];
document.getElementById("test").innerHTML =
"<p>"+ obj.Fields[0].DisplayName + ": " + obj.Fields[0].DataValue + "</p>" +
"<p>" + obj.Fields[1].DisplayName + ": " + obj.Fields[1].DataValue + "</p>" +
"<p>"+ obj.Fields[2].DisplayName + ": " + obj.Fields[2].DataValue + "</p>" +
"<p>"+ obj.Fields[3].DisplayName + ": " + obj.Fields[3].DataValue + "</p>" +
"<p>" + obj.Fields[4].DisplayName + ": " + obj.Fields[4].DataValue + "</p>" +
"<p>" + obj.Fields[5].DisplayName + ": " + obj.Fields[5].DataValue + "</p>" +
"<p>"+ obj.Fields[6].DisplayName + ": " + obj.Fields[6].DataValue + "</p>" +
"<p>" + obj.Fields[7].DisplayName + ": " + obj.Fields[7].DataValue + "</p>"
;
The next problem is if there is more then 1 data object. Currently I have it set to loop through the first object, but when I remove that I get cannot read property of '0' undefined.
Sure.
var html = "";
obj.Fields.forEach(({DisplayName, DataValue}) => {
html += `<p>${DisplayName}: ${DataValue}</p>`;
});
document.getElementById("test").innerHtml = html;
Use Array.map() and join the results:
var fields = data[0].Fields ;
document.getElementById("test").innerHTML = fields
.map(function(field) {
return '<p>' + field.DisplayName + ': ' + field.DataValue + '</p>';
})
.join('\n');

jQuery adding a div after a generated table

I am sure i have the right logic here and tried after and insertafter but does not seem to work... any ideas?
JS:
if(content) {
var $table = $('<table/>');
$table.addClass('product-table');
$table.append(
'<tr><td><img src="' + content[0].image + '" class="thumbnail"/></td>' +
'<td><strong>' + content[0].title + '</strong></td>' +
'<td>SKU: ' + content[0].sku + '</td>' +
'<td>£' + content[0].price + '</td></tr>'
);
$table.after('<div class="button-container">' +
'view cart' +
'checkout' +
'</div>');
$(notice_content).find(notice_inner).html($table);
}
after method requires that the target element ($table) be in DOM - which it isn't until next statement with .html method.
Just move line with after call after the line with html call:
$(notice_content).find(notice_inner).html($table);
$table.after('<div class="button-container">view cartcheckout</div>');
Useful references:
http://api.jquery.com/after

jQuery Mobile refresh collapsible

I have a few <div data-role="collapsible">...</div>in my page (I don't use a collapsible set because I want the possibility to open several at once) and then I remove them and create a few new ones with Javascript. Now I want them to have the jQuery Mobile Styling, but whatever I do, they won't refresh. I tried:
$("parentdiv").refresh();
$("parentdiv").trigger("create");
$(".ui-collapsible").refresh();
$(".ui-collapsible").trigger("create");
I even put a collapsible-set around each one and tried to do the refresh with this (described in the jQuery Mobile Documentation)
I add the new divs with $("<div data-role="collapsible">...</div>").insertBefore("#foo");
What is the proper way to do it? And is the content getting displayed in jQuery Mobile style, too, after the refresh?
UPDATE
The content of the collapsible was not refreshed here is my code:
var newColla = "<div id=\"colla" + i + "\" data-role=\"collapsible\" data-collapsed=\"true\" data-collapsed-icon=\"minus\" data-expanded-icon=\"bars\">" +
"<h3 id=\"" + matrikelnummer + "\">" + matrikelnummer + " " + studentName + "</h3><div class=\"colla-content\">" +
"<div data-role=\"fieldcontain\" style=\"margin:0px;width:100%;text-align:right;\">" +
"Teilnehmer bearbeiten" +
"Teilnehmer löschen" +
"</div>";
// Für jede ausgewählte Aufgabe einen Slider hinzufügen
for (var j = 0; j < aufgaben.length; j++) {
newColla += "<label for=\"slider_mini\">Aufgabe " + aufgaben[j] + ": (max." + allMaxPoints[j] + "Pkt.)</label>" +
"<input type=\"range\" name=\"slider_mini_" + matrikelnummer + "_" + aufgaben[j] +"\" class=\"slider-mini allSliders\" id=\"slider_mini_" + matrikelnummer + "_" + aufgaben[j] + "\" " + theme + " step= 0.5 value=\"0\"" +
"min=\"0.0\" max=\"" + allMaxPoints[j] + "\" data-highlight=\"true\" data-mini=\"true\" />";
}
newColla += "</div></div>";
$(newColla).collapsible().trigger("create").insertAfter("#timer");
All you need is to use .collapsible(), there is no refresh method for collapsible widget.
$(document).on("pageinit", function () {
var collapsible = '<div data-role="collapsible"><h3>Heading</h3><p>Contents</p></div>';
$("[data-role=content]").append($(collapsible).collapsible());
});
Demo
Try this one:
$( ".selector" ).collapsibleset( "refresh" );

Javascript doing what is expected

I am dynamically adding <script> tags with javascript & jQuery into my html file whenever a button is pushed. Everything gets added in correctly but only one of the two .click jQuery action functions is working. I can't seem to figure out why. No errors in console. I made sure i used \' and \" in the correct places.
$('#classBox').append('<tr id=\"' + tempCHAR + tempNUM + '\">'
+ '<td>'
+ '<i id=\"' + tempCHAR + tempNUM + '\" class=\"icon-remove-sign\">'
+ '</i> '
+ '<a id=\"' + tempCHAR + tempNUM + '\"" href=\"https://cms.psu.edu/section/default.asp?id=' + urlHOLDER + '\" target="framehidden">'
+ tempYEAR + ': ' + tempCHAR + tempNUM + ', Section ' + tempSEC
+ '</a>'
+ '</td>'
+ '</tr>'
+ '<script>'
+ '$(\'#' + tempCHAR + tempNUM + '\').click(function() {'
+ '$(\'tr\').remove(\'tr#' + tempCHAR + tempNUM + '\');'
+ '});'
+ '$(\'a#\'' + tempCHAR + tempNUM + ').click(function() {'
+ '$(\'#framehidden\').attr(\'src\', $(\'a\', this).attr(\'href\')));'
+ '});'
+ '</script>');
The indents are just for me to more easily read what I'm doing. That wouldn't be the problem would it?
If thats too impossible to read then here it is in normal view.
$('a#'IST130).click(function() {
$('#framehidden').attr('src', $('a', this).attr('href')));
});
$('#IST130').click(function() {
$('tr').remove('tr#IST130');
});
I have like 30 other .click functions that all work perfectly but I just cannot figure out what is going wrong here. Any hints?
Since .append() is instant (ie. synchronous), there is absolutely no need to put that stuff in a <script> tag. Instead, try this:
$('#classBox').append('<tr id=\"' + tempCHAR + tempNUM + '\">'
+ '<td>'
+ '<i id=\"' + tempCHAR + tempNUM + '\" class=\"icon-remove-sign\">'
+ '</i> '
+ '<a id=\"' + tempCHAR + tempNUM + '\"" href=\"https://cms.psu.edu/section/default.asp?id=' + urlHOLDER + '\" target="framehidden">'
+ tempYEAR + ': ' + tempCHAR + tempNUM + ', Section ' + tempSEC
+ '</a>'
+ '</td>'
+ '</tr>');
$('#' + tempCHAR + tempNUM).click(function() {
$('tr').remove('tr#' + tempCHAR + tempNUM);
});
$('a#' + tempCHAR + tempNUM).click(function() {
$('#framehidden').attr('src', $('a', this).attr('href')));
});
That being said, your code is HORRIBLY invalid. IDs MUST be unique. I'll leave you to fix that in whatever way works best for you, but yeah.
Your error (or at least one of them) is on this line:
+ '$(\'a#\'' + tempCHAR + tempNUM + ').click(function() {'
Just have an extra single quote there that needs to be moved to the end of the $() block:
+ '$(\'a#' + tempCHAR + tempNUM + '\').click(function() {'
In your example at the end you have $('a#'IST130). Pretty sure that should read $('a#IST130)`
To correct it, change the generation for that ID to:
'$(\'a#' + tempCHAR + tempNUM + '\')...
Additionally, since you are dynamically adding the elements, their click events may not bind properly, depending on exactly when your code is executing.
You can use jquery on to set a bind for the events on a permanent element. In this case #classBox looks like a good bet. It might look something like this (where this would be inside a normal script block and outside of your dynamic stuff:
$('#classBox').on('click','a',function () {
$('#framehidden').attr('src', $('a', this).attr('href')));
});
$('#classBox').on('click',function () {
$(this).closest('tr').remove();
});
Note: Completely untested - intended as a guide!
After you fix the syntax errors, also be sure the click events aren't being attached before the append() code has run.
I can't tell which order the code runs in the actual page - if you're appending the elements before the click events are being attached, the elements may not exist yet. You can use jQuery's delegate method to ensure the events are called for all elements, no matter when they're appended to the DOM.
For example:
$('body').delegate('.anchorClassName', 'click', function(e){});

Categories

Resources