Dynamically add jquery mobile components to listview with formatting - javascript

When I'm dynamically inserting the following code, I can force the page to refresh so it applies the jQuery mobile formatting.
For some reason its doesn't allow me to set the button formatting. Its really odd, because it allows the list to be dynamically inserted and the button, but i cant seem to format the button except for the name.
It can be manipulated via CSS but I want to use the jQuery API.
$('#cartList').append('<li>'
+ '<h3>' + game.Title+'</h3>'
+ '<p>' + '£' + game.Price + '</p>'
+ 'Remove'
+ '<h3 class="ui-li-aside">' + game.Format + '</h3>'
+ '</li>').trigger("create");

The jQuery Mobile Doc mentions that if new list items are added to the list or removed from it, the dividers are not automatically updated and you should call refresh() on the listview to redraw the autodividers.
Try to add: $('#cartList').listview('refresh'); after you have populated the list.
Example:
<!doctype html>
<html lang="en">
<head>
<title></title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.css" />
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.js"></script>
<script>
$(document).ready(function(){
$("#add-li-button").click(function(){
$('#listList').append("<li data-role=\"collapsible\"> <h3>New List</h3> <div data-role=\"fieldcontain\"></div> </li>").listview("refresh");
});
});
</script>
</head>
<body>
<div data-role="page" id="page">
<ul id="listList" data-role="listview">
</ul>
<input type="button" id="add-li-button" value="add a checkbox to list1" />
</div>
</body>
</html>

Related

Assigning a link and description to a column cards dynamically

I want to create column cards (like buttons).
in that cards, description should appear in its top and when it is clicked, separate link should be opened in new page.
every cards has its own description and link.it should not be hard coded by directly assigning the desc and link to it.and every function and elements should be assigned in javascript file not html.
the desc and link should given in an array like
Table={{"desc":"apple","link":"www.google.com"},{"desc":"banana","link":"www.youtube.com"}}
I tried this code and I'm getting only one card with last description and link
for(i=0;i<10;i++)
{
var temp=my.Table[i].link;
$('.demo').html('<div class="column"><p id="i"></p></div>');
document.getElementById(i).innerHTML ='' + my.Table[i].desc + '';
}
You can iterate the table object, after append what you should use.
HTML code:
<html>
<head>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="script.js"></script>
<!-- <link rel="stylesheet" type="text/css" href="styles.css"> -->
</head>
<body>
<div class="demo">
</div>
</body>
</html>
And the jquery code looks like the following:
$(document).ready(function(){
const table=[{"desc":"apple","link":"www.google.com"},{"desc":"banana","link":"www.youtube.com"}];
table.forEach((v, i)=>{
$('.demo').append('<div class="column"><p id="temp_'+i+'">' + v.desc + '</p></div>');
});
});

Create div-element (jQuery mobile pages) dynamically

When I try to add a data-role div-element dynamically in jquery it fails - it shows up but its not formatted any longer. In the html-file you can see where I put the created div-element.
What is wrong and how could I make it work?
htlm-file
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5 /jquery.mobile-1.4.5.min.css">
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile- 1.4.5.min.js"></script>
<script src="my_js.js"></script>
</head>
<body>
<!-- jquery mobile-pages does not work here-->
<div id="mydiv">
</div>
<!-- this works just fine -->
<div data-role="collapsible">
<h4>B</h4>
<ul data-role="listview">
<li>Billy</li>
<li>Bob</li>
</ul>
</div>
</body>
</html>
jquery
var string = "" +
"<div data-role='collapsible'>" +
"<h4>B</h4>" +
"<ul data-role='listview'>" +
"<li><a href='#'>Billy</a></li>" +
"<li><a href='#'>Bob</a></li>" +
"</ul>" +
"</div>";
console.log(string);
$(string).appendTo("#mydiv");
the upper part of the image is when it's created dynamically, the lower part is what it looks like if I just put the code in the html-file. To the right you can see the string which i append to the div
You have to bind collapsible element when you add it dynamically.
Like :
$(string).appendTo("#mydiv");
/** Add this line and try **/
$("data-role='collapsible'").collapsible();
Ref Link : https://api.jquerymobile.com/collapsible/

trying to add an option to a dropdown list and have it displayed in the dropdown

As the title says, I'm trying to add an option to a dropdown and have it displayed in the list.
Here's a sample example (I maybe old but this is my first stab at the world of web)
When you press the add button a new option should appear in the list "Pasta", but it is not being displayed. If you "select all" and press the "Products" button the alert displays "Pasta".
I've spent over a week looking for a solution and I am here out of desperation!
<!DOCTYPE html>
<html>
<head>
<title>Simple List Example</title>
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<link href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/js/bootstrap.min.js"></script>
<link href="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/css/bootstrap-multiselect.css" rel="stylesheet" type="text/css" />
<script src="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/js/bootstrap-multiselect.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
$("#productsList").multiselect({
includeSelectAllOption: true
});
$("#selectedButton").click (function() {
var selected = $("#productsList option:selected");
var message = "Products:\n";
selected.each(function () {
message += " " + $(this).text() + " " + $(this).val() + "\n";
});
alert(message);
});
$('#addButton').click(function(){
$("#productsList").append(new Option("Pasta", "6"));
});
});
</script>
</head>
<body>
<select id="productsList" multiple="multiple">
<option value="1">Cereal</option>
<option value="2">Soft Drinks</option>
<option value="3">Staples</option>
<option value="4">Salad Dressing</option>
<option value="5">Ice Cream</option>
</select>
<input type="button" id="selectedButton" value="Products"/>
<input type="button" id="addButton" value="Add"/>
</body>
</html>
Please feel free to reduce the problem (but not too much) and please don't get too esoteric.
Thanks in advance
Since you're using bootstrap multi-select , everytime you add a new option element you need to "rebuild" the element. You can check that method on the documentation right here: http://davidstutz.github.io/bootstrap-multiselect/#methods
So the code would be something like this:
$('#addButton').click(function(){
$("#productsList").append(new Option("Pasta", "6"));
$('#productsList').multiselect('rebuild');
});
The problem is that when you initialise your multiselect, it appends a hidden DOM element class="multiselect-container dropdown-menu" to your productlist.
This new element is responsible for displaying items in your list.
You need to rebuild your multiselect after adding the new option.
$('#addButton').click(function(){
$("#productsList").append(new Option("Pasta", "6")).multiselect("rebuild");
});
I would highly recommend using Firebug or Chrome's dev tools to view your DOM.

Change URL based on change of dynamic select box

I have a select box populated from a JSON file, I want to reload the URL but pass the value from the select box.
Here is a cut down version of my index.html file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Timetables</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div id="navbar" class="navbar-collapse collapse">
</div>
<!--/.navbar-collapse -->
</div>
</nav>
<!-- Main jumbotron for a primary marketing message or call to action -->
<div class="jumbotron">
<div class="container">
<div id="headerArea">
</div>
</div>
</div>
</body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
var $crs = GetURLParameter('crs');
// Function that uses this variable removed as not relevant
$.getJSON('csr.json', function (data) {
var stationDropdown = '<form class="navbar-form navbar-right" action="">';
stationDropdown += '<select class="form-control" id="stations">';
for (var i in data) {
stationDropdown += '<option value="' + data[i].Code + '">' + data[i].StationName + '</option>';
}
stationDropdown += '</select>';
stationDropdown += '</form>';
$("#navbar").html(stationDropdown);
});
$(function(){
// bind change event to select
$('#stations').bind('change', function () {
var url = $(this).val(); // get selected value
if (url) { // require a URL
window.location = 'index.html?crs='.url; // redirect
}
return false;
});
});
</script>
</html>
and here is a sample of the JSON
[
{
"StationName":"Abbey Wood",
"Code":"ABW"
},
{
"StationName":"Aber",
"Code":"ABE"
}
]
The select box generates fine and is 'injected(?) into the navbar div, but the on change event wont register
Basically if someone was to select Aber, the onchange event will reload index.html?crs=ABE automatically.
Dev tools is not throwing up any errors, its just not doing anything when I change the select box.
I suspect I need to run the on change event as a function that is called exclusively when needed as putting it in at the bottom of the index.html file means its loading before the DOM is ready?
Thanks in advance for any assistance.
You should move all of your HTML building INTO the HTML.
Inside of your getJSON() you can cut that code down to this:
var stations = $( '#stations' );
for (var i in data) {
stations.append( '<option value="' + data[i].Code + '">' + data[i].StationName + '</option>' );
}
Once you do that, everything else should work appropriately. Here's what I changed in your HTML:
<div id="navbar" class="navbar-collapse collapse">
<form class="navbar-form navbar-right" action="">
<select class="form-control" id="stations">
<option>Select One</option>
</select>
</form>
</div>
Also, as a note. jQuery recommends using the on() method instead of the bind() method as of 1.7.
http://api.jquery.com/bind/
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the event binding call.
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.
As you are creating elements dynamically.
You need to use Event Delegation. You have to use .on() using delegated-events approach.
General Syntax
$(document).on(event, selector, eventHandler);
Ideally you should replace document with closest static container.
Example
$("#navbar").on('change', '#stations', function(){
//Your code
});
Always the same question... you initiate your bind event before the dropdown is created, because it depends on an ajax call.
What's wrong with your code :
$.getJSON('csr.json', function (data) { // This is done #1
.......
$("#navbar").html(stationDropdown); // this is done #3 : creating #stations.
});
$('#stations').bind('change', function () { // This is done #2 and won't do anything because #stations doesn't exist yet
........
});
The right way is :
$.getJSON('csr.json', function (data) { // This is done #1
.......
$("#navbar").html(stationDropdown); // this is done #2 : creating #stations.
$('#stations').bind('change', function () { // This is done #3
........})
});
It's because the $.getJSON function is called after the $(function(){
If you move the code in $(function(){, to the end of the $.getJSON function, then it'll work.
You need to use on for dynamic content:
$('#navbar').on('change', '#stations', function () {
^ Static container content is appended to
^ #stations = target element

how to use javascript onclick event handler for same class of anchor elements

This is my javascript:
Here i grab data using ajax get request and call this function:
function fetch_user_data(data) {
$(user_board['results']).each(function(attributes,value){
$('.main_container').append(
'<div class="pin" id='+attributes+'>\
<div class="holder">\
<a class="image" href="" title="Photo number 1" pin_id='+ attributes +'>\
<img src="'+ value['profile'] + '" />\
</a>\
<p class="desc">' + value['name'] + '</p>\
<ul id="pin_actions">\
<li id="awe"></li>\
<li id="cof"><a href="#" onClick="onTabAction('+value['user_id']+'); return false;" ></a></li>\
<li id="ban"><a href="#" onClick="onTabAction('+value['user_id']+'); return false;" ></a></li>\
</ul>\
</div>'
);
});
}
function onTabAction(id,action) {
console.log(id);
console.log(action);
}
Here is a problem, my data contains 33 objects, and then according to object there are 33 html boxes belong to person profile. I attached onclick event handler in anchor tag and get user id through custom function which is onTabAction. Along with id i want to get a string like: onTabAction('+value['user_id']+',actionstr) but when i call this function and print output in console.log: it prints user id once and string equal to object quantiy like li#actionstr. In short I would like to get both string and id and make an url to query on other url. Please help me on this stuff, also if i get string and id i have to remove that anchor from main page as i place that anchor on other page.
Here is a working example, with the code you posted I can't make a working example because most of it is missing:
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type">
<title>Example</title>
<style type="text/css">
.clickable{
cursor:pointer;
}
</style>
<script type="text/javascript" src="jquery-1.9.0.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var someData=["one","two","three"],
i=0,
user_id="my user id",
$main=$('.main_container');
for(i=0;i<someData.length;i++){
$main.append(
"<h1>"+someData[i]+"</h1>\
<ul id=\"pin_actions\">\
<li class=\"clickable\" data-action='awe'>awe</li>\
<li class=\"clickable\" data-action='cof'>cof</li>\
<li class=\"clickable\" data-action='ban'>ban</li>\
</ul>"
);
}
$main.attr("data-userID",user_id);
//attach onclick
$('.main_container').find("li").on("click",onTabAction);
});
function onTabAction(e) {
console.log("userID:",this.parentElement.parentElement.getAttribute("data-userID"));
console.log("action:",this.getAttribute("data-action"));
}
</script>
</head>
<body>
<div class="main_container">
</div>
</body>
</html>

Categories

Resources