Append removing element content - javascript

I am trying to create a dynamic navigation which adds elements to a standard bootstrap navigation with the following code:
// Map item to the navigation
function addToNavigation (navigationItem) {
// Build the navigation item HTML string
var navigationItemHTML = '<li><a';
if(navigationItem.dataTarget){ navigationItemHTML += ' data-target="#' + navigationItem.dataTarget + '" data-toggle="collapse"';}
navigationItemHTML += ' aria-expanded="false" class="pointer">';
if(navigationItem.icon){ navigationItemHTML += '<span class="glyphicon glyphicon-' + navigationItem.icon + '></span> ';}
navigationItemHTML += navigationItem.title + '</a></li>';
// Append the new item to the navigation
$('#navigation').append(navigationItemHTML);
}
If I set a breakpoint the contents of "navigationItemHTML" appear exactly how I want them however the result on the page omits the navigation item title and the optional glyphicon.
Why is this and is there a better way of accomplishing what I want to achieve in jQuery/JavaScript?

Managed to figure out it was a problem with the string I was trying to pass to jQuery, I had more luck instantiating each tag as an element within the last:
// Map item to the navigation
function addToNavigation (navigationItem) {
// Build the navigation item HTML string
var navigationItemHTML = $('<li></li>').html(
$('<a></a>').html(
$('<span></span>').html(
' ' + navigationItem.title).prepend(
$('<span><span>').addClass('glyphicon glyphicon-' + navigationItem.icon)))
.attr('data-target', '#' + navigationItem.dataTarget)
.attr('data-toggle', 'collapse').addClass('pointer'));
// Append the new item to the navigation
$('#navigation').append(navigationItemHTML);
}
I still think this looks abit messy however, please let me know if anyone finds a more elegant solution.

Related

Need to get qtip to display correct new javascript html table data that is dynamic

I have a similar question in which I didn't have the right data in a fiddle to show. What the other question shows is doing a table row clone, but my data is table append to a div
The jQuery $.each loop shows where I have a dynamically created the title (tooltip)
This is the fiddle: http://jsfiddle.net/bthorn/Lpuf0x7L/1/
$.each(allData, function (index, issues) {
strResult += "<tr><td class='nameField'> <a href='#'>" + issues.LAST_NAME + " " + issues.FIRST_NAME + " " + issues.INITIALS + "</a></td><td>" + issues.OFFICE + "</td><td>" + issues.TITLE + "</td>";
strResult += "<td>" + issues.DEPARTMENT + "</td><td class='alias'>" + issues.ALIAS_NAME + "</td>";
// NEED TO ADD QTIP to the issues.DEPARTMENT title tooltip //////
addTooltips();
/////////
strResult += "</tr>";
});
strResult += "</table>";
$("#divEmpResult").html(strResult);
My old question from a few hours with OP answer should be helpful
dynamic javascript data with qtip is overriding all tooltips with same message
I am trying to call this function but i know that I needs to have additional data from qtip appended to it.
OP was doing a .insertBefore(this) but I am not sure how to do that with my table row
$('button').on('click', function() {
$('<div/>', {
class: 'tips',
text: 'Dynamically inserted.'
}).insertBefore(this);
addTooltips();
In the second code snippet, the addTooltips function was called after the dynamic element(s) were inserted into the DOM via the .insertBefore() method.
In your first code snippet, you are calling the addTooltips function before the elements are actually appended, which is why it isn't working as expected:
$("#divEmpResult").html(strResult);
addTooltips(); // Call the function *after* the elements exist in the DOM
In order to prevent the previous tooltips from being overridden, negate all the elements with data-hasqtip attributes. You can also set the tooltip text based on the title attribute, or some pre-defined defaults like in the example below:
$('.tips:not([data-hasqtip])').each(function() {
$(this).qtip({
content: {
text: $(this).attr('title') || 'This is the message!'
},
hide: {
fixed: false
},
position: {
corner: {
target: 'topLeft',
tooltip: 'bottomRight'
}
}
});
});
To address your last issue where the tooltips only included the first word, you need to enclose the title attribute value in quotes. Previously, your HTML was being rendered like: title=some words here, which resulted in the browser automatically inserting quotes around the first white-space separated word and turning the following words into separate attributes.
Working Example Here
The title attribute value needs to be enclosed in quotes:
strResult += '<td class="tips" title="' + issues.DEPARTMENT + '">' + issues.DEPARTMENT + '</td><td class="alias">' + issues.ALIAS_NAME + '</td>';
To avoid mistakes like this, I would highly suggest using a JS templating engine such as handlebars.

How to hard code text which are coming from javascript messages

Our application is been internationalized and being changed to different languages. For that reason we have to hard code all the messages. How can we do that for messages in javascript ?
This is how we are doing in html messages.
<span th:text="#{listTable.deletedFromTable}">deleted</span>
How do we hard code for javascript messages.(update the table)
$('#TableUpdate-notification').html('<div class="alert"><p>Update the Table.</p></div>');
You will need to put the messages in the DOM from the start, but without displaying them. Put these texts in span tags each with a unique id and the th:text attribute -- you could add them at the end of your document:
<span id="alertUpdateTable" th:text="#{listTable.updateTable}"
style="display:none">Update the Table.</span>
This will ensure that your internationalisation module will do its magic also on this element, and the text will be translated, even though it is not displayed.
Then at the moment you want to use that alert, get that hidden text and inject it where you need it:
$('#TableUpdate-notification').html(
'<div class="alert"><p>' + $('#alertUpdateTable').html() + '</p></div>');
You asked for another variant of this, where you currently have:
$successSpan.html(tableItemCount + " item was deleted from the table.", 2000);
You would then add this content again as a non-displayed span with a placeholder for the count:
<span id="alertTableItemDeleted" th:text="#{listTable.itemDeleted}"
style="display:none">{1} item(s) were deleted from the table.</span>
You should make sure that your translations also use the placeholder.
Then use it as follows, replacing the placeholder at run-time:
$successSpan.html($('#alertTableItemDeleted').html().replace('{1}', tableItemCount));
You could make a function to deal with the replacement of such placeholders:
function getMsg(id) {
var txt = $('#' + id).html();
for (var i = 1; i < arguments.length; i++) {
txt = txt.replace('{' + i + '}', arguments[i]);
}
return txt;
}
And then the two examples would be written as follows:
$('#TableUpdate-notification').html(
'<div class="alert"><p>' + getMsg('alertUpdateTable') + '</p></div>');
$successSpan.html(getMsg('alertTableItemDeleted', tableItemCount));

Sorting consistency of dynamically created IDs on DOM Elements

My application successfully creates elements and assigns them different (increasing) IDs.
Now my issue relies when the user deletes these elements (because they have the option to delete as well as create), the consistency of these IDs get broken therefore my application doesn't run well.
This Fiddle represents what I have so far. Just a textbox that appends its value and a few other elements inside a collapsible as many times as the user wants (For some reason my fiddle doesn't increment the alert value, but it works fine on my platform).
SCRIPT (Sorry the txt variable is too long)
$('#Add').click(function () {
if ($("#MedNameStren").val() != "") {
var value = $("#MedNameStren").val();
var noOfMeds = $('#NoOfMedicines').val();
//to check current value
alert(noOfMeds);
var text = '<div data-role="collapsible" data-collapsed="true" data-iconpos="left" data-content-theme="e">' + '<h2>' + desc + '</h2>' + '<div class="ui-grid-a">' + '<div class="ui-block-a" style="width:25%; margin-right:3%;">' + '<input id="quantity' + noOfMeds + '" class="quantity" type="text" placeholder="Quantity" />' + '</div>' + '<div class="ui-block-b" style="width:70%; margin-right:2%;"">' + '<textarea id="directions' + noOfMeds + '" class="directions" cols="40" rows="4" placeholder="Directions given by your GP." ></textarea>' + '</div>' + '</div>' + '<button key="' + vpid + '">Remove</button>' + '</div>';
$("#medListLi").append(text);
$('button').button();
$('#medListLi').find('div[data-role=collapsible]').collapsible();
$('#medListLi li').listview("refresh");
$('#medListLi').trigger("create");
document.getElementById("manuallyName").value = "";
noOfMeds++
$("#NoOfMedicines").val(noOfMeds);
}
else {
alert('Please Provide Medicine Name')
}
});
I am using a counter that neatly increments the ids of quantity and description like:
quantity0
quantity1
quantity2
..and so on, but once the following script is called...
//Deletes colapsible sets (Medicines) from the selected List
$('#medListLi').on('click', 'button', function (el) {
$(this).closest('div[data-role=collapsible]').remove();
var key = $(this).attr('key');
localStorage.removeItem(key);
var noOfMeds = $('#NoOfMedicines').val();
noOfMeds--
$("#NoOfMedicines").val(noOfMeds);
//location.reload();
});
depending on which element (collapsible) is deleted, the IDs stop being consistent. For example if the collapsible with id="quantity1" is deleted then the counter will go back to 1 (currently 2) and on the next addition the respective collapsible will get an id that's already taken, and unfortunately I don't need this to happen.
Maybe I'm making this sound more complicated that it is, but will appreciate any suggestions or ideas to solve this issue (if possible).
If more information is needed, please let me know.
Was brought to my attention that creating and deleting dynamic IDs can be done but keeping up with consistency of these IDs can be very tricky to work around it.
I've solved my own problem by simply creating a function that would keep count of the IDs from the amount of collapsibles inside my list and "renewing" the ID numbers on each Add and Delete.

Self written toc jQuery function: jump to link target and show corresponding element

I generate dynamically a toc for elements of class=faqQuestion.
The answer resides in a class=faqAnswer element which is hidden by default.
By clicking on class=faqQuestion entry it will show up with
$(this).next(".faqAnswer").slideToggle(300);
Everything works as expected.
What I want: by clicking on a toc link i will jump to the target faqQuestion element and show the corresponding faqAnweser element.
The way I generate the toc:
$(document).ready(function(){
var url = window.location.pathname;
$('<ol />').prependTo('#toc')
$(".faqQuestion").each(function(i) {
var current = $(this);
current.attr("id", "entry" + i);
$("#toc ol").append("<li class=\"faqToc\"><a id='link" + i + "' href='" + url + "#entry" +
i + "' entry='" + current.attr("tagName") + "'>" +
current.html() + "</a></li>");
});
This is what I tried, which will jump to the selected faqQuestion but the faqAnswer element is still hidden.
$(".faqToc").click(function(event){
$(this).next(".faqAnswer").slideToggle(300);
});
My problem is this - at least I think so - so I tried something like - which results in "undefined"
var url = $(this).prop("href");
alert(url);
Trying attr instead of prop returns also "undefined".
Can you point out my problem?
I'm trying to improve my Javascript and jQuery know how, so I don't want to use a toc-plugin.
Update: HTML looks like this:
<div id="toc">
<ol>
<li class="faqToc">
...
</li>
<li class="faqToc">
...
</li>
</div>
<p id="entry0" class="faqQuestion">...</p>
<div class="faqAnswer" style="display: none;">...</div>
<p id="entry1" class="faqQuestion">...</p>
<div class="faqAnswer" style="display: none;">...</div>
A very simple way would be to use the index() method since relationship between the TOC elements and the question/answer elements is 1 to 1.
$(".faqToc").click(function(event){
var index=$(this).index(); /* zero based index position of element within it's siblings*/
/* toggle answer element with same index */
$(".faqAnswer").eq(index).slideToggle(300);
});
jQuery API Reference : index()

using .append to build a complex menu

To build a menu block which should be switchable with hide/unhide of the menu items, I'm using .append html.
The code idea is this:
navigat += '<h3 class="infoH3"> <a id="' + menuID +'"'
+ ' href="javascript:slideMenu(\'' + menuSlider + '\');">'
+ menuName + '</a></h3>';
navigat += '<div id="' + menuSlider + '" style="display:none">';
navigat += ' <ul>';
navigat += ' <li>aMenu1</li>'
navigat += ' <li>aMenu2</li>'
navigat += ' <li>aMenu3</li>'
navigat += ' </ul>';
navigat += '<!-- menuName Slider --></div>';
$("#someElement").append (navigat);
This is doing well .. so far.
But the point is::
I use JS to read the required menu items (eg. 'aMenu1' together with title and/or link info) from a file to build all that, eg. for 'aMenu1' a complex is composed and $("#someElement").append(someString) is used to add that the 'someElement'.
At the moment I build those html elements line by line. Also OK .. as far as the resulting string has the opening and closing tag, eg. "<li>aMenu2</li>".
As can be seen from above posted code there is a line "<div id="' + menuSlider + '" style="display:none">".
Appending that -- AFAIS -- the .append is automatically (????) adding "</div>" which closes the statement.
That breaks my idea of the whole concept! The menu part isn't included in the 'menuSlider '.
QQ: How to change it -- NOT to have that "</div" added to it??
Günter
You could change you method around to use document fragment style creation and an object to populate the properties on the elements, like this:
var someElement = $("#someElement");
$('<h3 class="infoH3"></h3>').append($('<a />',
{ 'id': menuID,
'href': '#',
click: function() { slideMenu(menuSlider); }
})
).appendTo(someElement);
var div = $('<div />', { 'id': menuSlider, css: {display: 'none'} });
$('<ul />').append('<li>aMenu1</li>')
.append('<li>aMenu2</li>')
.append('<li>aMenu3</li>')
.appendTo(div);
div.appendTo(someElement);
This is a very different way of doing it, first we're caching the $("#someElement") object so we're not searching for it repeatedly. Then we're creating the <h3> as an object, putting the link inside, then inserting then appending the whole thing to someElement. In the last, the same approach it's creating the <div>, setting it's properties, then creates the <ul> menu and appends it inside...then appends that whole div to someElement as well.
As a side note, I'm not sure how .slideMenu() works, but an event handler that works via $(this).parent().next() (or give the div a class) would work as well, and you wouldn't need a function with the slider argument passed.

Categories

Resources