Dynamically adding items to listview (jQuery mobile) - javascript

How i can you pull out of the object's data and dynamically add them to the listview
function (){
var person = {
title: "ddd",
mes: "sss",
op: {},
tel: 2
};
}
the data will be coming from to json server
<div data-role="page" id="page1">
<div data-role="header">
<h1>Заголовок</h1>
</div>
<ul data-inset="true" id="ideaposits" data-role="listview" data-split-icon="gear">
<script type="text/html" id="list">
<li>
<a class="ui-btn ui-icon-carat-r " href="#page2">
<h2 class="title"></h2>
<p class="mes"></p>
</a>
</li>
</script>
</ul>
</div>
and move on to the second screen page2 ........

First, make the "template" element hidden:
<li style="display:none">
<a class="ui-btn ui-icon-carat-r " href="#page2">
<h2 class="title"></h2>
<p class="mes"></p>
</a>
</li>
Then, change your javascript to copy the template item and fill in the values, and then show it:
function (){
var person = {
title: "ddd",
mes: "sss",
op: {},
tel: 2
};
var li = $("li");
var newLi = li.clone();
newLi.find(".title").text(person.title);
newLi.find(".mes").text(person.mes);
newLi.show();
li.after(newLi);
}

function getRandomInt(min, max) {
//credit : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
function dataFromAjaxExample(){
var sumall = getRandomInt(2,20);
$('#head-list').html('List View ( total item ' + sumall + ' )');
// json data from ajax example
var itemlist = [];
for(i=1;i<=sumall;i++){
itemlist.push({
itemid: i,
title: 'Item ' + i,
desc: 'is ' + i,
page: 'page'+i
});
}
return itemlist;
}
//template
function itemList(item){
var htmlList = [
'<li>',
'<a class="ui-btn ui-icon-carat-r " href="#' + item.page + ' ">',
'<h2 class="title">' + item.title + '</h2>',
'<p class="desc">' + item.desc + '</p>',
'</a>',
'</li>'
];
return htmlList.join('');
}
//add process
function addItemListView(data){
is_list = $('#ideaposits');
is_list.html('');
data.forEach(function(x){
is_list.append(itemList(x));
});
}
//main process
setInterval(function(){
addItemListView(dataFromAjaxExample());
},4000);
//onload
addItemListView(dataFromAjaxExample());
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<div data-role="page" id="page1">
<div data-role="header">
<h1 id='head-list'>List View</h1>
</div>
<ul data-inset="true" id="ideaposits" data-role="listview" data-split-icon="gear">
<li>
<a class="ui-btn ui-icon-carat-r " href="#page2">
<h2 class="title"></h2>
<p class="mes"></p>
</a>
</li>
</ul>
</div>

Related

How to get drag + drop Javascript code to apply to each individual task item, making each list item draggable, rather than items together in block?

My drag and drop code does not apply to each new added list item individually, but instead applies to all the list items in one block. However, the purpose of the drag and drop is to make the list items individually sortable and draggable. Any clue to how to correct the code to apply to each new task/list item that is appended under the 'To Do' list?
var $addButton = $(".btn-primary");
var $removeButton = $(".btn-danger");
var $todoList = $(".uncomplete");
var $doneList = $(".completed");
//Take Text Input and Add <li> to To Do List
$addButton.on("click", function(){
//Creating object Variables
var $sort = $(".sort").val();
var $newTask = $(".newTask").val();
var $taskDescr = $(".taskDescr").val();
var $taskDate = $(".taskDate").val();
// var $category= $(".category").val();
var $category= $("input[type='radio'][name='category']:checked").val();
//var $importance = $("input[type='checkbox'][name='importance']:checked").val();
var $importance = $('<input type="checkbox" name="importance"/>').val();
var $newTaskString = $sort + ", " + $taskDescr + ", " + $newTask + ", " + $taskDate + ", " + $category + ", " + $importance + " ";
var $todoList = $(".uncompleted");
//call append method on $todoList
$todoList.append("<li>" + $newTaskString + "<button><span> Done</span></button><button><span> Remove</span></button></li>").addClass("todo");
//drag and drop array
function allowDrop(e)
{
console.log("allow drop");
e.preventDefault();
}
function drop(e)
{
console.log("drop");
e.preventDefault();
var data = e.dataTransfer.getData("text");
e.target.appendChild(document.querySelector("#" + data));
}
function drag(e)
{
console.log("dragging");
//e.preventDefault();
e.dataTransfer.setData("text", e.target.id);
}
function showAllUsers(){
let allUsersDiv=document.querySelector("#allUsersDiv");
for(var i=0; i < allUsers.length; i++)
{
var newUserDiv=document.createElement("DIV");
newUserDiv.setAttribute("draggable", "true");
newUserDiv.setAttribute("ondragstart", "drag(event)"); //"editUser(this)"
newUserDiv.setAttribute("id", ("userdiv-" + i));
newUserDiv.setAttribute("style", "border:1px solid red;");
var newUserEditLink = document.createElement("A");
newUSerEditLink.setAttribute("href", "#");
newUSerEditLink.setAttribute("onclick", "editUSer(this)");
newUserEditLink.innerHTML = "Edit";
newUserEditLink.setAttribute("id", ("edit-", + i));
newUserDiv.innerHTML=allUsers[i].username;
newUserDiv.appendChild(nowUserEditLink);
allUsersDiv.appendChild(newUserDiv);
}
}
<div class="list-wrap" contenteditable="false">
<div class="list-inner-wrap">
<h2 class="title">ToDo List</h2>
<h3 class="title">Add Task</h2>
<!--<h4>Task Name</h4>-->
<label for="sort">Sort Order:</label><input type="text" class="sort"
name="sort" id="sort" value="" placeholder="A,B,C,etc.">
<br> </div></div>
<button class="btn btn-primary">
<span class="glyphicon glyphicon-plus"> Add</span>
</button>
<h3 class="title">To Do</h2>
<h6><i>Click task item to edit or modify</i></h6>
<!--Change color of editable task -->
<div id='div' contenteditable='false' oninput='change()'>
<div id="allUsersDiv" ondragover="allowDrop(event)" ondrop="drop(event)" style="position:absolute;left:5px;top:450px;height:200px;width:500px; border: 1px solid black">
<div draggable="true" ondragstart="drag(event)">
<ul class="uncompleted" contenteditable="false" id="id01" >
<li>Need to be completed task
<button class="btn btn-success">
<span class="glyphicon glyphicon-ok"> Done</span>
</button>
<button class="btn btn-danger">
<span class="glyphicon glyphicon-remove"> Remove</span></button>
<br>
</li></ul>
</div></div></div>

jquery populate new data attribute

I have a sample program using JQuery
DEMO
I'm having a trouble in adding new table row using data attribute, that should be displayed before the button or with the table row.
JS:
var newhtml = '<table><tr><td>data1</td><td>data2</td><td>data3</td></tr><!--show here--><!--new table row added in clicking more--><tr><td></td><td></td><td><button>more</button></td></tr></table>';
$(".advanced-info").click(function(){
console.log($("#" + $(this).attr("data-div")).html().length);
if ($("#" + $(this).attr("data-div")).html().length > 0) {
$("#" + $(this).attr("data-div")).empty();
} else {
$("#" + $(this).attr("data-div")).append(newhtml);
}
});
output
I apologize my problem is not clear
Here you go:
I've changed the usage of .attr to .data.
var newhtml = '<table><tr><td>data1</td><td>data2</td><td>data3</td></tr><tr><td></td><td></td><td><button>more</button></td></tr></table>';
$(".advanced-info").click(function() {
console.log($("#" + $(this).attr("data-div")).html().length);
if ($("#" + $(this).data("div")).html().length > 0) {
$("#" + $(this).data("div")).empty();
} else {
$("#" + $(this).data("div")).append(newhtml);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href='#' class='advanced-info' data-div='adv1'>Advanced Options</a>
<div id='adv1'></div>
<br/>
<br/>
<a href='#' class='advanced-info' data-div='adv2'>Advanced Options</a>
<div id='adv2'>
</div>
<br/>
<br/>
<a href='#' class='advanced-info' data-div='adv3'>Advanced Options</a>
<div id='adv3'></div>
Try this way.
var newhtml = '<table><tr style="display:none;"><td>data1</td><td>data2</td><td>data3</td></tr><tr><td></td><td></td><td><button>more</button></td></tr></table>';
$(".advanced-info").click(function() {
console.log($("#" + $(this).attr("data-div")).html().length);
if ($("#" + $(this).attr("data-div")).html().length > 0) {
$("#" + $(this).attr("data-div")).empty();
} else {
$("#" + $(this).attr("data-div")).append(newhtml);
}
});
$("div").on("click", "button", function() {
$(this).closest("table").find("tr:eq(0)").css("display", "table-row");
$(this).hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<a href='#' class='advanced-info' data-div='adv1'>Advanced Options</a>
<div id='adv1'></div>
<br/>
<br/>
<a href='#' class='advanced-info' data-div='adv2'>Advanced Options</a>
<div id='adv2'></div>
<br/>
<br/>
<a href='#' class='advanced-info' data-div='adv3'>Advanced Options</a>
<div id='adv3'></div>
Hope this your need!

A panel is not being dragable - Jquery UI

I am building a project and using Bootstrap and Jquery Ui for the frontend. The index.php File is:
<html>
<head>
<script src="weatherModule/weatherFetcherForIndex.js"></script>
<?php
include "resources/resources.php";
echo $bootstrap;
include "NewsFeed/CnnNewsFeed.php";
$cnn = new CnnNewsFeed("world");
$feed = $cnn->getRss();
echo $jquery_ui;
?>
<script src="resources/dragable.js"></script>
</head>
<body>
<?php
//navbar
echo $navbar;
$items = $feed->channel->item;
?>
<div id="temp" style="width: 30%; height: 7%; margin-top: 6.5%;">
</div>
<?php
echo $cnnNewsHeader;
for($i = 0; $i <= 2+1; $i++)
{
echo "<a href='". $items[$i]->guid ."' class='list-group-item'>
<h4 class='list-group-item-heading'>" . $items[$i]->title . "</h4>
<p class='list-group-item-text'>" . $items[$i]->description . "</p>
</a>";
}
echo $cnnNewsFooter;
?>
</body>
</html>
You could just skip the weather part which is working perfectly. And that resources/resources.php file is:
<?php
/**
* Created by PhpStorm.
* User: root
* Date: 11/7/15
* Time: 10:42 AM
*/
$jquery_ui = '<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>';
$weather_icons = "<link src='http://startyour.club/weather-icons/css/weather-icons.css' type='text/css' rel='stylesheet' />";
$bootstrap = "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">
<link rel=\"stylesheet\" href=\"http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css\">
<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js\"></script>
<script src=\"http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js\"></script>";
$navbar = "<nav class= \"navbar navbar-default\">
<div class=\"container-fluid\">
<!-- Brand and toggle get grouped for better mobile display -->
<div class=\"navbar-header\">
<button type=\"button\" class=\"navbar-toggle collapsed\" data-toggle=\"collapse\" data-target=\"#bs-example-navbar-collapse-1\" aria-expanded=\"false\">
<span class=\"sr-only\">Toggle navigation</span>
<span class=\"icon-bar\"></span>
<span class=\"icon-bar\"></span>
<span class=\"icon-bar\"></span>
</button>
<a class=\"navbar-brand\" href=\"#\">Project</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class=\"collapse navbar-collapse\" id=\"bs-example-navbar-collapse-1\">
<ul class=\"nav navbar-nav\">
<li class=\"active\">Home <span class=\"sr-only\">(current)</span></li>
<li>News</li>
<li>Weather</li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>";
$navbar_for_weather = "<nav class= \"navbar navbar-default\">
<div class=\"container-fluid\">
<!-- Brand and toggle get grouped for better mobile display -->
<div class=\"navbar-header\">
<button type=\"button\" class=\"navbar-toggle collapsed\" data-toggle=\"collapse\" data-target=\"#bs-example-navbar-collapse-1\" aria-expanded=\"false\">
<span class=\"sr-only\">Toggle navigation</span>
<span class=\"icon-bar\"></span>
<span class=\"icon-bar\"></span>
<span class=\"icon-bar\"></span>
</button>
<a class=\"navbar-brand\" href=\"#\">Project</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class=\"collapse navbar-collapse\" id=\"bs-example-navbar-collapse-1\">
<ul class=\"nav navbar-nav\">
<li>Home</li>
<li>News</li>
<li class=\"active\">Weather <span class=\"sr-only\">(current)</span></li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>";
$cnnNewsHeader = "<div class=\"col-sm-4\" style=\"margin-left: 65%; margin-top: 2.5%;\">
<div class=\"panel panel-default\">
<div class=\"panel-heading\">
Cnn News
</div>
<div class=\"panel-body\">
<div class=\"list-group\">";
$cnnNewsFooter = "</div>
</div>
</div>
</div>";
Which basically defines many variables to use in my main pages.
And my resources/dragable.js is:
$(function() {
$( ".panel" ).draggable();
});
And also my weatherFetcherForIndex.js is as follows:
/**
* Created by root on 11/7/15.
*/
navigator.geolocation.getCurrentPosition(GetLocation);
function GetLocation(location) {
var long = location.coords.longitude;
var lat = location.coords.latitude;
$.post("weatherModule/jsPhpInterface.php", {lat: lat, lon: long})
.done(function (data) {
var parsedJSON = JSON.parse(data);
$("#temp").html
(
"<div class='panel panel-primary'>" +
"<div class='panel-heading'>" +
"Temperature" +
"</div>" +
"<div class='panel-body'>"
+
parsedJSON.data.current_condition[0].FeelsLikeC + "° C" +
"</div>" +
"</div>" +
"</div>"
);
});
}
And When I open up my index.php I get the news panel dragable, but the weather panel is not dragable. Any Help Would be Very Appreciated!!!!
Cheers!
As you have specified, your selector for draggable content is panel class:
$( ".panel" ).draggable();
But your weather panel doesn't have a panel class. You must select your weather panel with proper class name or add panel class name to weather panel.
Update:
Because you're creating weather panel on the fly you must make it draggable after creating it. After adding your weather panel to DOM you must make it draggable with $(".panel").draggable();.
Add it after changing html content of the temp element:
$("#temp").html
(
"<div class='panel panel-primary'>" +
"<div class='panel-heading'>" +
"Temperature" +
"</div>" +
"<div class='panel-body'>"
+
parsedJSON.data.current_condition[0].FeelsLikeC + "° C" +
"</div>" +
"</div>" +
"</div>"
);
$('.panel').draggable();

How to display the div elements in row by row

I have a html code which displays ads ,but the ads are display like a coloumn vise, but I want them to display in a horizontal row .How can we display the horizontal rows.And ads are which are coming dynamically based on the user selection.How can we display these ads in a row wise fashion .
Html code is :
<div class="row">
<div class="col-md-3" id="adsid"></div>
</div>
Code snippet from JS:
<input type="checkbox" id=' + s[i]['id']['0'] + ' />
<a href="#" class="list-group-item ">
<input type="hidden" id="adsid" name="adsrunning" value=' + s[i]['id']["0"] + '/>
<h4 class="list-group-item-heading">
<font color="blue">' + s[i]['hea']["0"] + '</font>
</h4>
<p class="list-group-item-text">' + s[i]['desc']["0"] + '</p>
<p class="list-group-item-text">' + s[i]['desc2']["0"] + '</p>
<p class="list-group-item-text">
<font color="green">' + s[i]['url']["0"] + '</font>
</p>
</a><br/>
And JS is :
$("#groupid").change(function () {
$("#adsid").html("");
var grpvalue = $("#groupid").val();
var accid = $('#accountid').val();
var adsarray = [];
$.ajax({
type: "post",
dataType: 'json',
url: "pages/ads.php",
data: "adgroup=" + grpvalue + "&accid=" + accid,
success: function (s) {
for (var i = 0; i < s.length; i++) {
var head = s[i]['hea']["0"];
//alert(head);
var adid = s[i]['id']["0"];
var desc1 = s[i]['desc']["0"];
var desc2 = s[i]['desc2']["0"];
var url = s[i]['url']["0"];
var p = document.createElement('p');
var txt = document.createTextNode(head);
p.appendChild(txt);
//$('adsid').append(p);
adsarray.push(head, adid, desc1, desc2, url);
$("#adsid").append("");
$("#adsid").append('<input type="checkbox" id=' + s[i]['id']['0'] + ' /><input type="hidden" id="adsid" name="adsrunning" value=' + s[i]['id']["0"] + '/><h4 class="list-group-item-heading"><font color="blue">' + s[i]['hea']["0"] + '</font></h4><p class="list-group-item-text">' + s[i]['desc']["0"] + '</p><p class="list-group-item-text">' + s[i]['desc2']["0"] + '</p><p class="list-group-item-text"><font color="green">' + s[i]['url']["0"] + '</font></p><br/>');
}
}
});
});
And Json Data is:
[{
"hea": {
"0": "Kidney Stone Removal"
},
"id": {
"0": "40602813172"
},
"desc": {
"0": "Get treated at top kidney center"
},
"desc2": {
"0": "Take a free advice from our experts"
},
"url": {
"0": "www.ainuindia.com"
}
}]
I think your questions i answered here:
http://www.w3schools.com/css/css_float.asp
Use float to place the "rows" next to each other.
Though i would recommend you to change your "row" class to something more appropriate if possible. Since row are explicitly saying that it's a row, in other words a vertical alignment.
You can use ul li tag as bellow give style to li as list-style:none
<div class="row">
<ul >
<li class="col-md-3 col-sm-3 col-xs-6"><img src="" /><span class="badge">Lorem ipsum</span></li>
<li class="col-md-3 col-sm-3 col-xs-6"><img src="" /><span class="badge">Lorem ipsum</span></li>
<li class="col-md-3 col-sm-3 col-xs-6"><img src="" /><span class="badge">Lorem ipsum</span></li>
<li class="col-md-3 col-sm-3 col-xs-6"><img src="" /><span class="badge">Lorem ipsum</span></li>
</ul>
</div>
If you can modify the html of ad, try replacing col-md-3 by col-sm12 so the whole thing would read:
<div class="row">
<div class="col-sm-12" id="adsid">
</div>
</div>
I'm assuming you're using bootstrap, so having col-md-3 makes it float left with width 33%. On medium screen.

Modify JSON received and POST back update

Looking for a starting point. I'm getting my data (via json) for a JQM page. I need to be able to edit any of the returned result fields and UPDATE the database via .post json.
My thought is to iterate through the json array, make changes and post json array back, should I be populating text-boxes in the initial load and then creating separate array?
$.getJSON('JSON_MDB.php',
function (data) {
// data is now JSON object instantiated from retrieved info
$.each( data, function ( i, val ) {
($('<div>')
.attr({
'data-role': 'collapsible',
'data-content-theme': 'c',
'data-collapsed': 'true',
'id': 'cResults'
})
.html('<h4>' + this.lastName + ', ' + this.firstName + '</h4><ul data-role="listview" data-filter="true" data-filter-placeholder="Search Choices..." data-inset="true" id="makecollapsibleul"><li>'
+ 'FDID: ' + this.FDID + '</li><li>'
+ 'Choice 1: ' + this.C1 + '</li><li>'
+ 'Choice 2: ' + this.C2 + '</li><li>'
+ 'Choice 3: ' + this.C3 + '</li><li>'
+ 'Choice 4: ' + this.C4 + '</li><li>'
+ 'Choice 5: ' + this.C5 + '</li><li>'
+ 'Choice 6: ' + this.C6 + '</li><li>'
+ 'IP: ' + this.IPADDRESS + '</li><li>'
+ 'Pick Date: ' + this.PICKDATE + '</li></ul>'
))
.appendTo('#primary');
$('#makecollapsible').collapsibleset().trigger('create');
$.mobile.hidePageLoadingMsg();
});
}
);
HTML:
<div data-role="page" id="main">
<div data-role="header">
<h1>MCFRSIT JSON DATA</h1>
</div><!-- /header -->
<div data-role="content">
<ul data-role="listview" id="outer-ul">
<li>
<div data-role="collapsible">
<h4>Submitted Choices</h4>
<ul data-role="listview" data-inset="true" data-filter="true" id="makecollapsible">
<!-- AJAX CONTENT -->
</ul>
</div>
</li>
</ul>
</div><!-- /content -->
<div data-role="footer">
</div>
</div><!-- /page -->

Categories

Resources