How to dynamically generate collapsible-set in jQuery? - javascript

I retrieve from a php file some headline datas (main headlines, each of them has sub headlines).
The data I receive works fine, but when I want to generate a collapsible-set in jquery (mobile), it doesn't show the beautiful theme... just plain text?!
Here's my HTML file:
<div data-role="collapsible-set" data-content-theme="d" id="headlinegroup">
And here's my javascript file:
$.ajax({
type: "POST",
url: "headline_getter.php",
dataType: 'json',
cache: false,
success: function(data1){
console.log ("debug 2");
var i = 0;
var $elements = '';
$.each(data1[i].main, function() {
console.log ("debug 3 ");
$elements += ($('div[data-role=collapsible-set]#headlinegroup').append('<div data-role="collapsible"><h3>' + data1[i].main + '</h3><div data-role="fieldcontain"><fieldset data-role="controlgroup" id="headlinegroup'+[i]+'">'));
var j = 0;
$.each(data1[i].sub, function() {
console.log ("debug 4");
$elements += ('<label><input type="checkbox" name="headlines[]" data-mini="true" value="' + data1[i].mid[j] + '"/>' + data1[i].sub[j] + '</label>');
j++;
});
$elements += ('</fieldset></div></div>');
$elements.collapsible();
i++;
});
}
});
I don't really know where the problem is. I've read some thread here at stackoverflow and added the .collapsible attribut but it don't work... theres just plain text.
Thanks in advance. Best regards, john.

have you tried to add .trigger('create') at the end of every element you append?

Related

GetJSON jquery returns undefined

I am trying to get my search box to work and do a getJSON on text search and title. but in the console log, I get text=undefined?title=undefined. so it is not displaying any JSON. Not sure if my click is working correctly or if I have to make my JSON objects?
Script
<script>
var searchstring = $('input[type="text"]', this).val();
var url = "https://data.edu/api/v1/metadata";
url += "?text=" + searchstring;
url += "?title=" + searchstring;
$(document).ready(function() {
$('button[type="button"]').click(function(event){
$.ajax({
type: "GET",
url: url,
success: function(res){
console.log(res);
var items = res.data.metadata;
var ins = "";
for (var i = 0; i < items.length; i++){
ins += "<div>";
ins += "Title" + items[i].title;
ins += "Title" + items[i].title;
ins += "Title" + items[i].title;
ins += "</div><br />";
};
$('#results').html(ins);
}
});
});
});
</script>
html
<form class="destinations-form" role="search" >
<div class="input-line">
<input id="searchForm" type="text" class="form-input check-value" placeholder="Search Documents" />
<button type="button" class="form-submit btn btn-special" "</button>
</div>
</form>
<div class="container">
<div class="hero-text align-center">
<div id="results"></div>
</div>
</div>
json
data: [
{
collection_id: "ADGM-1552427432270-483",
metadata:{
year: "2019",
files: text ,
title: text,
},
The problem is because you only read the values from the field when the page first loads and it is empty. To fix this, move that logic inside the click handler.
The next issue is that you should remove this from $('input[type="text"]', this). You don't need a contextual selector here, and this one is incorrect regardless.
Also note that a valid querystring starts with ? and separates each value with &, so your url concatenation needs to be amended slightly. In addition you shouldn't update the url value on every click. If you do it this way your AJAX request will only work once.
Lastly the metadata in your response is an object, not an array. data is the array so you need to loop over that instead. The loop can also be simplified by using map(). Try this:
$(document).ready(function() {
const url = "https://data.edu/api/v1/metadata";
$('button[type="button"]').on('click', function(e) {
let searchstring = $('input[type="text"]').val();
let requestUrl = url + `?text=${searchstring}&title=${searchstring}`;
$.ajax({
type: 'GET',
url: requestUrl,
success: function(res) {
let html = res.data.map(item => `<div>Title ${item.metadata.title}</div><br />`);
$('#results').html(html);
}
});
});
});

I have dynamically generated 2 <tr> and I want to get the data of the <tr> I click

The Question might be confusing but this is the exact situation..
I have dynamically generated few ( as per data fetched from database) and now I want to allow the user to select one of the radio buttons and I want to capture the details of the row clicked so please check my code and assist
My ajax code
$.ajax({
data: data,
url: url,
type: 'POST',
datatype: 'JSON',
success: function (response) {
console.log(response);
var result = $.parseJSON(response);
var count = result.length;
for (var i = 0; i < count; i++) {
var $row = $("<tr><input type='hidden' id='"+ result[i].objId + "' value='"+ result[i].objId+"'><td><input type='radio' name='dbRadio' id='dbRadio'></td><td>" + result[i].name + "</td><td> Murgency Global Network</td><td>" + result[i].number + "</td><td>" + result[i].city + "</td><td> 0.5 Km</td></tr>");
$('table.queriedResponder > tbody:last').append($row);
}
console.log($row);
}
});
my radio button detection code
$('input[name=dbRadio]').change(function(){
console.log('clicked');
});
Use an instance of this and get the closest tr:
$('input[name=dbRadio]').change(function(){
console.log($(this).closest("tr"));
});
Of course, if this handler isn't being hit, it's probably because your rows are being added dynamically - so delegate the handler:
$('table.queriedResponder').on('change', 'input[name=dbRadio]', function() {
console.log($(this).closest("tr"));
});

Implement jQuery on dynamically created elements

I'm trying to integrate two jQuery scripts into one but because the elements of the first part are created dynamically using jQuery I can't get the second part of the project working.
The project:
1.Instagram pictures are parsed as JSON into li elements.
Here's a portion of the code:
<ul id="elasticstack" class="elasticstack">
</ul>
<script>
$("#elasticstack").append("<li><div class='peri-pic'><img class='instagram-image' src='" + data.data[i].images.low_resolution.url +"' /><span class='name'>"+ data.data[i].caption.from.username +"</span> <span class='likes'><span class='glyphicon glyphicon-heart'></span><p>"+data.data[i].likes.count +"</p></span></div></li>"
);
</script>
Source: LINK
2.This works fine but when I try to add the slider none of the functions work. Even if I wrap the callout function in a $( document ).ready(function() { });
Here's the call out code:
<script>
new ElastiStack( document.getElementById( 'elasticstack' ) );
</script>
Source: LINK
Here's the JS Fiddle with all my code: LINK
Where am I going wrong?
You're looking for this. After the initial loadImages(start_url) call, you should be able to call loadImages(next_url) to load and display more. new ElastiStack had to be called after the images had been appended.
var access_token = "18360510.5b9e1e6.de870cc4d5344ffeaae178542029e98b",
user_id = "18360510", //userid
start_url = "https://api.instagram.com/v1/users/"+user_id+"/media/recent/?access_token="+access_token,
next_url;
function loadImages(url){
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: url,
success: function(data){
displayImages(data);
next_url = data.pagination.next_url;
}
})
}
function displayImages(images){
for(var i = 0; i < 20; i++){
if(images.data[i]){
$("#elasticstack").append("<li><img class='instagram-image' src='" + images.data[i].images.low_resolution.url + "'></li>");
}
}
// Call it after the images have been appended
new ElastiStack(document.getElementById('elasticstack'));
}
$(document).ready(function(){
loadImages(start_url);
});
Try to initialize the ElastiStack after data (HTML elements) has been appended into the DOM in your ajax, for example:
for (var i = 0; i < count; i++) {
// ...
$("#elasticstack").append(...);
}
new ElastiStack(...);
It should work.
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: url ,
success: function(data) {
next_url = data.pagination.next_url;
//count = data.data.length;
//three rows of four
count = 20;
//uncommment to see da codez
//console.log("count: " + count );
//console.log("next_url: " + next_url );
//console.log("data: " + JSON.stringify(data) );
for (var i = 0; i < count; i++) {
if (typeof data.data[i] !== 'undefined' ) {
//console.log("id: " + data.data[i].id);
$("#elasticstack").append("<li><img class='instagram-image' src='" + data.data[i].images.low_resolution.url +"' /></li>"
);
}
}
new ElastiStack(document.getElementById('elasticstack'));
}
});
You have to move your new ElastiStack(document.getElementById('elasticstack')); inside the ajax success event. You don't have to change anything else in your. I also updated your JSFiddle.

javascript passing values dynamically to a method jquery

$(document).bind('pageinit', function () {
var vendor_id = $.urlParam('vendor_id');
$.ajax({
type: "GET",
url: "http://testservice/testmenu",
data: {
vendor_id: vendor_id
},
error: function () {
alert("Could not get the menu : " + url);
},
success: function parseXml(xml) {
var jsonData = $.parseJSON(xml);
$(jsonData).each(function (index, post) {
$(post).each(function (index, row) {
var finalString = [];
for(var index = 0; index < row.menu.length; index++) {
finalString.push('<div id="collapsibleMenu" data-mini="true" data-role="collapsible" data-inset = "true" data-content-theme="g">');
finalString.push('<h3>' + row.menu[index].category_name + '</h3>');
finalString.push('<ul id="menuDetails" data-role="listview">');
for(var j = 0; j < row.menu[index].products.length; j++) {
var output = ['<li data-icon="addToCart" id="addToCart"> <p>' + row.vendor_menu[index].products[j].prod_name + '</p><p> $' + Number(row.vendor_menu[index].products[j].price).toFixed(2) + '</p>' + '</li>'];
finalString.push(output);
}
finalString.push('</ul></div>');
}
$('#output').append(finalString.join(''));
});
});
$('#output').trigger('create');
}
});
});
function test(prod_id) {
alert("entered test " + prod_id);
addToCart(prod_id, 1);
}
In the following code, where I am doing the following:
<a href="javascript:test("+row.menu[index].products[j].prod_id")">
This is obviously giving me an error. The point is, I need to pass the prod_id dynamically into the javascript test method. I am not sure how to do that. If I just call test without passing prod_id, it works great. Please help!
Try removing the quotes in the argument.
I think I might have figured it out.
Try this.
<a href="javascript:test(\''+row.menu[index].products[j].prod_id+'\')">
This looks like the perfect reason to use a template engine. You might use a Jade template like this:
for post in posts
for row in post
for menu in row.menu
#collapsibleMenu(data-mini="true", data-role="collapsible", data-inset="true", data-content-theme="g")
h3= menu.category_name
ul#menuDetails(data-role="listview")
for product in menu.products
li#addToCart(data-icon="addToCart")
a(href="#", data-product-id=product.prod_id)
p= product.prod_name
p= '$' + Number(product.price).toFixed(2)
Then you can simplify your $.ajax call to:
$.ajax({
// ...
dataType: 'json',
success: function(data) {
$('#output').append(templateFunction(data));
}
});
For the click event, use event delegation:
$('#output').on('click', 'a[data-product-id]', function() {
addToCart(Number($(this).data('product-id')), 1);
});
Easy, yeah? Now change all of your ids to classes, because ids must be unique and yours aren't!

How to get the value value of a button clicked Javascript or Jquery

I'll try to be as straight to the point as I can. Basically I using jquery and ajax to call a php script and display members from the database. Next to each members name there is a delete button. I want to make it so when you click the delete button, it deletes that user. And that user only. The trouble I am having is trying to click the value of from one delete button only. I'll post my code below. I have tried alot of things, and right now as you can see I am trying to change the hash value in the url to that member and then grap the value from the url. That is not working, the value never changes in the URL. So my question is how would I get the value of the member clicked.
<script type="text/javascript">
$(document).delegate("#user_manage", "pagecreate", function () {
$.mobile.showPageLoadingMsg()
var friends = new Array();
$.ajaxSetup({
cache: false
})
$.ajax({
url: 'http://example.com/test/www/user_lookup.php',
data: "",
dataType: 'json',
success: function (data) {
$.mobile.hidePageLoadingMsg();
var $member_friends = $('#user_list');
$member_friends.empty();
for (var i = 0, len = data.length; i < len; i++) {
$member_friends.append("<div class='user_container'><table><tr><td style='width:290px;font-size:15px;'>" + data[i].username + "</td><td style='width:290px;font-size:15px;'>" + data[i].email + "</td><td style='width:250px;font-size:15px;'>" + data[i].active + "</td><td><a href='#" + data[i].username + "' class='user_delete' data-role='none' onclick='showOptions();'>Options</a></td></tr><tr class='options_panel' style='display:none'><td><a href='#" + data[i].username + "' class='user_delete' data-role='none' onclick='showId();'>Delete</a> </td></tr></table></div>");
}
}
});
});
</script>
<script>
function showId() {
var url = document.URL;
var id = url.substring(url.lastIndexOf('#') + 1);
alert(id);
alert(url);
}
</script>
IDEAS:
1st: I think it would be easier to concatenate an string an later append it to the DOM element. It's faster.
2nd: on your button you can add an extra attribute with the user id of the database or something and send it on the ajax call. When getting the attribute from the button click, use
$(this).attr('data-id-user');
Why don't you construct the data in the PHP script? then you can put the index (unique variable in the database for each row) in the button onclick event. So the delete button would be:
<button onclick = "delete('indexnumber')">Delete</button>
then you can use that variable to send to another PHP script to remove it from the database.
$('body').on('click', 'a.user_delete', function() {
var url = document.URL;
var id = url.substring(url.lastIndexOf('#') + 1);
alert(id);
alert(url);
});
<?php echo $username ?>
Like wise if you pull down users over json you can encode this attribute like so when you create your markup in the callback function:
'<a href="#'+data[i].username+'" data-user-id="'+ data[i].username + '" class="user_delete" data-role="none" >Options</a>'
So given what you are already doing the whole scenerio should look something like:
$(document).delegate("#user_manage", "pagecreate", function () {
$.mobile.showPageLoadingMsg();
var friends = new Array(),
$member_friends = $('#user_list'),
// lets jsut make the mark up a string template that we can call replace on
// extra lines and concatenation added for readability
deleteUser = function (e) {
var $this = $(this),
userId = $this.attr('data-id-user'),
href = $this.attr('href'),
deleteUrl = '/delete_user.php';
alert(userId);
alert(href);
// your actual clientside code to delete might look like this assuming
// the serverside logic for a delete is in /delete_user.php
$.post(deleteUrl, {username: userId}, function(){
alert('User deleted successfully!');
});
},
showOptions = function (e) {
$(this).closest('tr.options_panel').show();
},
userTmpl = '<div id="__USERNAME__" class="user_container">'
+ '<table>'
+ '<tr>'
+ '<td style="width:290px;font-size:15px;">__USERNAME__</td>'
+ '<td style="width:290px;font-size:15px;">__EMAIL__</td>'
+ '<td style="width:250px;font-size:15px;">__ACTIVE__</td>'
+ '<td>Options</td>'
+ '</tr>'
+ '<tr class="options_panel" style="display:none">'
+ '<td>Delete</td>'
+ '</tr>'
+ <'/table>'
+ '</div>';
$.ajaxSetup({
cache: false
})
$(document).delegate('#user_manage #user_container user_options', 'click.userlookup', showOptions)
.delegate('#user_manage #user_container user_delete', 'click.userlookup', deleteUser);
$.ajax({
url: 'http://example.com/test/www/user_lookup.php',
data: "",
dataType: 'json',
success: function (data) {
$.mobile.hidePageLoadingMsg();
var markup;
$member_friends.empty();
for (var i = 0, len = data.length; i < len; i++) {
markup = userTmpl.replace('__USERNAME__', data[i].username)
.replace('__ACTIVE__', data[i].active)
.replace('__EMAIL__', data[i].email);
$member_friends.append(markup);
}
}
});
});
Here's a really simple change you could make:
Replace this part:
onclick='showId();'>Delete</a>
With this:
onclick='showId("+data[i].id+");'>Delete</a>
And here's the new showId function:
function showId(id) {
alert(id);
}

Categories

Resources