LocalStorage append New Element - javascript

his is : My First JSFiddle. It just appends <li></li>. It works for LocalStorage and shows the result
$(".nav").append($("<li></li>").html(inputan));
I want append like My Second JSFiddle:
var addFolder = '<li>' +
'<div class="zf-folder">' +
'<a></a>' +
'</div>' +
'</li>';
$(".nav").append($(addFolder).html(inputan));
This works for LocalStorage, but is not showing a result when the page is reloaded. I want to use use a method like that because my code looks like this :
With append method $('.nav').append(addFolder);
How can I display LocalStorage result with my second jsFiddle method?

You had addFolder inside your submitButton click handler, hence it is only available in the handler function scope.
$(".submitButton").click(function() {
var inputan = $("#input_nameFolder").val();
// move the below variable outside of this function
var addFolder = '<li>' +
'<div class="zf-folder">' +
'<a></a>' +
'</div>' +
'</li>';
...
});
Move addFolder outside of the function and it should work.
Updated your fiddle.
Edit: To get correct index
You can add a function that returns the addFolder with the current/updated index. The same function can be used for first time rendering on page load and every time on adding item from the input.
Something like:
var count = 1;
function getNewList() {
var addFolder = '<li data-index="' + (count++) + '">' +
'<div class="zf-folder">' +
'<a></a>' +
'</div>' +
'</li>';
return addFolder;
}
You can check out here:
Edited Fiddle for index
// check for the data-index on li items in the console

Related

jQuery append function is just appending the html but not the classes related to it

I am using php laravel and so it uses blade template to render the views. Following is the javascript code to append html script :-
$(function () {
var count = 0;
$("#min_bonus_value").click(function () {
count++;
var min_bonus_html =
'<div class="min_bonus_row">' +
'<hr>' +
'<div class="row">' +
'<div class="col-md-2">' +
'<div class="form-group">' +
'<label for="bonus_day[' + count + ']">#lang('admin.message759')<span class="text-danger">*</span></label>' +
'<select class="select2 form-control" id="bonus_day[' + count + ']" name="bonus_day[' + count + '][]" data-placeholder="#lang('admin.message759')" multiple>' +
'<option value="1">Monday</option>' +
'<option value="2">Tuesday</option>' +
'<option value="3">Wednesday</option>' +
'<option value="4">Thursday</option>' +
'<option value="5">Friday</option>' +
'<option value="6">Saturday</option>' +
'<option value="7">Sunday</option>' +
'</select>' +
'</div>' +
'</div>' +
'</div>' +
'</div>';
Following is the piece of blade template code where the above html needs to be appended, I want to append 'select2' class which is styled to select multiple days, but in vain :-
<div id="minimum_bonus">
</div>
I may be off here but when you say "not the classes", do you actually mean the Javascript/jQuery funcionality?
If so, I'll try to explain what is happening: when you initialize a jQuery plugin, like select2, it acts upon what exists in the DOM at the moment you initialize it. So if you later create new items, these won't have the select2 functionality, unless you initialize it again for said new items.
I suggest you create a function to initialize select2 and call it whenever you add new elements to your DOM. You'd need to somehow single out the elements that have already been initialized. You can do so with a class, in this example, the class is 'select2-enabled'. Like this:
function initSelect2() {
$(".select2").each(function(){
if (!$(this).hasClass('select2-enabled')) {
$(this).addClass('select2-enabled');
$(this).select2({
// all your select2 options
});
}
});
}
And then, after you append your new html, you can call your function to initialize select2 on the new elements:
$(parentElement).append(newHTML);
initSelect2();

onclick function in loop, executes without clicking

Im fetching data from a blizzard api(working fine) and i have a jquery $each loop to retrieve the data which i then append in a ul. i want to add a button within every time the loop gives out data to an object. the problem is that when i use onclick='"+myfunction(param)+"' inside the loop, it will execute the function before i have pressed the button the onclick is attached to. when i check the browser it says onclick="undefined". here is the code:
let tid;
function reply_click(clicked_id){
console.log(clicked_id);
}
$('#searchnow').bind('click',
function (){
function kaldapiclass(){
// console.log("card");
var classSelect=$('#thisclass').val();
$.getJSON('https://us.api.blizzard.com/hearthstone/cards?
locale=en_US&access_token=hidden&class='+classSelect, function(data) {
$('#kortliste').empty();
$.each( data.cards, function(i, card) {
$()
$('#kortliste').append("<li id='" + card.id + "'><img src='" + card.image + "'><p>"+
card.name +"</p><button onclick='"+reply_click(card.id)+"'>HERE</button></li>");
});
});
};
clearTimeout(tid);
tid=setTimeout(kaldapiclass, 500);
});
ty for your time
-Morten
The code you entered will actually execute the function. So, instead of:
"<button onclick='"+reply_click(card.id)+"'>HERE</button>"
you should just define the element the way you would place it in dom:
"<button onclick='reply_click("+card.id+")'>HERE</button>"
Only the card.id should be dynamic.
I would also suggest to append html only once, this way:
var toAppend = '';
$.each( data.cards, function(i, card) {
toAppend += "<li id='" + card.id + "'><img src='" + card.image + "'><p>" + card.name + "</p><button onclick='reply_click(" + card.id + ")'>HERE</button></li>";
});
$('#kortliste').html( toAppend );

How to concatenate and pass parameters values in html using jQuery

I'm using jQuery to get values from ajax rest call, I'm trying to concatenate these values into an 'a' tag in order to create a pagination section for my results (picture attached).
I'm sending the HTML (divHTMLPages) but the result is not well-formed and not working, I've tried with double quotes and single but still not well-formed. So, I wonder if this is a good approach to accomplish what I need to create the pagination. The 'a' tag is going to trigger the onclick event with four parameters (query for rest call, department, row limit and the start row for display)
if (_startRow == 0) {
console.log("First page");
var currentPage = 1;
// Set Next Page
var nextPage = 2;
var startRowNextPage = _startRow + _rowLimit + 1;
var query = $('#queryU').val();
// page Link
divHTMLPages = "<strong>1</strong> ";
divHTMLPages += "<a href='#' onclick='getRESTResults(" + query + "', '" + _reg + "', " + _rowLimit + ", " + _startRow + ")>" + nextPage + "</a> ";
console.log("Next page: " + nextPage);
}
Thanks in advance for any help on this.
Pagination
Rather than trying to type out how the function should be called in an HTML string, it would be much more elegant to attach an event listener to the element in question. For example, assuming the parent element you're inserting elements into is called parent, you could do something like this:
const a = document.createElement('a');
a.href = '#';
a.textContent = nextPage;
a.onclick = () => getRESTResults(query, _reg, _rowLimit, _startRow);
parent.appendChild(a);
Once an event listener is attached, like with the onclick above, make sure not to change the innerHTML of the container (like with innerHTML += <something>), because that will corrupt any existing listeners inside the container - instead, append elements explicitly with methods like createElement and appendChild, as shown above, or use insertAdjacentHTML (which does not re-parse the whole container's contents).
$(function()
{
var query=10;
var _reg="12";
var _rowLimit="test";
var _startRow="aa";
var nextPage="testhref";
//before divHTMLPages+=,must be define divHTMLPages value
var divHTMLPages = "<a href='#' onclick=getRESTResults('"+query + "','" + _reg + "','" + _rowLimit + "','" + _startRow + "')>" + nextPage + "</a>";
///or use es6 `` Template literals
var divHTMLPages1 = `` + nextPage + ``;
$("#test").append("<div>"+divHTMLPages+"</div>");
$("#test").append("<div>"+divHTMLPages1+"</div>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test"></div>

Javascript add event listener in a foreach loop only last entry works

I have a function which goes through an Array and adds <h3> elements to a div. Then it adds an event listener (an onclick) to the current <h3> element, but only the last element which goes through the function is set by the onclick.
var runstr = [];
//txt comes from the content of a tab separated textfile spilt by '\n'
txt.forEach(function (lcb) { //lcb goes through each line of txt
lcb = lcb.split(" ", 30); //split the line by tab
//MainContent_Infralist is a div where the <h3> elements are listed and lcb[2] is the title
document.getElementById("MainContent_Infralist").innerHTML =
document.getElementById("MainContent_Infralist").innerHTML +
'<h3 class="Infraa" id="' + "Infralist_" + lcb[2] + '">' + lcb[2] + '</h3>';
//I put the id into an array to get the index of the marker later
runstr.push("Infralist_" + lcb[2]);
//I'm working with openlayers here i try to set the entry of
//the list.onlick to trigger a mousedown on a marker.
//And there is the problem: It works, but only for the last entry of my <h3> list...
document.getElementById("Infralist_" + lcb[2]).onclick = function () {
var theM = runstr.indexOf("Infralist_" + lcb[2]);
markers.markers[theM].events.triggerEvent('mousedown');
};
};
The problem is here:
document.getElementById("MainContent_Infralist").innerHTML =
document.getElementById("MainContent_Infralist").innerHTML +
'<h3 class="Infraa" id="' + "Infralist_" + lcb[2] + '">' + lcb[2] + '</h3>';
Every time you assign to innerHTML, you're basically deleting all stuff and adding it all over again. This causes all event listeners to break.
That's the reason why only last one works - it's the only one after assigning which there is no more innerHTML manipulation.
To fix this, create your elements using document.createElement() and append them using element.appendChild().
It could look like:
var header = document.createElement('h3');
header.id = 'Infralist_' + lcb[2];
header.className = 'Infraa';
header.textContent = lcb[2];
document.getElementById('MainContent_Infralist').appendChild(header);
header.onclick = function () {
// you function here
}

Pass string from one function to the next javascript

I've got a simple JavaScript client that pulls from a REST API to present some book data, however I seem unable to call the function createBookRow(bookid) and return the appropriate html string to the document ready function where it is called,
The output is currently being produced correctly as verified by the append to .row-fluid on the html page, ideas or suggestions welcome
function createBookRow(bookid)
{
$.get('http://mysite.co.uk/atiwd/books/course/'+bookid+'/xml', function(xml){
$(xml).find('book').each(function(){
var $book = $(this);
var id = $book.attr("id");
var title = $book.attr("title");
var isbn = $book.attr("isbn");
var borrowedcount = $book.attr("borrowedcount");
var html = '<div class="span3"><img name="test" src="http://covers.openlibrary.org/b/isbn/'+isbn+'-L.jpg" width="32" height="32" alt=""></p>' ;
html += '<p> ' + title + '</p>' ;
html += '<p> ' + isbn + '</p>' ;
html += '<p> ' + borrowedcount + '</p>' ;
html += '</div>';
$('.row-fluid').append($(html));
});
});
}
$(document).ready(function()
{
$.get('xml/courses.xml', function(xml){
$(xml).find('course').each(function(){
var $course = $(this);
var id = $course.attr("id");
var title = $course.text();
var html = '<div class="span12"><p>' + title + '</p><row id="'+id+'" >'+createBookRow(id)+'</row></div>' ;
$('.row-fluid').append($(html));
$('.loadingPic').fadeOut(1400);
});
});
});
The line
var html = '<div class="span12"><p>' + title + '</p><row id="'+id+'" >'+createBookRow(id)+'</row></div>' ;
should be just
var html = '<div class="span12"><p>' + title + '</p><row id="'+id+'" ></row></div>' ;
createBookRow(id);
createBookRow(id) function is making a get request to get some details, which happens asynchronously. Unless you explicitly mention it is a synchronous call(which is not advised).
I guess the functionality you need is to render some rows for course and in between you need books details displayed. In that case you need to explicitly say where your book row needs to be appended.
$('.row-fluid').append($(html));
The above code will always append book row at the end.
You aren't returning anything in the code you provided. You just append some HTML to a jQuery object. Try adding a return statement
return html;

Categories