lukassz lukassz - 6 months ago 18
Javascript Question

jQuery append, when I delete record view has changed baldy

I list some values using

append


<div data-role="main" class="ui-content">

<h2 id="list-filter">Lista produktów z lodówki</h2>
<div data-demo-html="true">
<ul data-role="listview" id="produktList" data-filter="true" data-filter-placeholder="Search fruits..." data-inset="true">

</ul>

<div id="deleteButton"><input type="button" id="merge_button" value="Usuń"></div>
</div><!--/demo-html -->

</div>


And JS

function iterateOverLocalStorage() {
$('ul#produktList').html("");
for(var i=0; i < localStorage.length; i++)
{
console.log(localStorage.getItem(localStorage.key(i)));
$('ul#produktList').append("<li class='ui-li-static ui-body-inherit ui-first-child ui-last-child'>"+localStorage.getItem(localStorage.key(i))+"" +
"<span><input type='checkbox' id='check' name='produkty[]' value='"+i+"'></span></li>");
}



}
iterateOverLocalStorage();


It looks ok

enter image description here

When I click
Usuń
button and this action was deleted selected record

$("#merge_button").click(function(event){
event.preventDefault();
var searchIDs = $("input:checkbox:checked").map(function(){

return this.value;

}).toArray(); // <----
console.log(searchIDs);

if(searchIDs.length == 0)
{
alert('Nic nie zaznaczyles');
}else {

for (var k in searchIDs) {
console.log("Element: " + k);


localStorage.removeItem(localStorage.key(k));
}

alert("Usunalem");
iterateOverLocalStorage();
}

});


The view changes, why?

enter image description here

Answer

The second view is actually the right one, with the radio button "bullet" next to the label.

The first view is different because it was built during page load, which happens before any other post-processing of the HTML occurs. Initially the div tags are not horizontally stretched to the page width, and so when your code runs the radio buttons wrap around.

It seems like you are using jQuery Mobile, which performs such post-processing ("enhancement" phase) and stretches the div tags horizontally.

You should turn the order around, and make sure you only inject the radio buttons once the page has been loaded and treated by jQuery Mobile.

This you can do as follows. Replace this line (the one which occurs outside any function):

iterateOverLocalStorage();

with this:

$(document).on("pagecreate",function(){
    iterateOverLocalStorage();
});

Note that there are several events that get triggered when jQuery Mobile pages load or transition. Check out this image:

enter image description here