How to empty div before append - javascript

I'm using Freebase Search Suggest to bind a certain keyword to a getJson request. The problem is that I bind getJson functions and the corresponding .append/.prepend functions to to the input field that has the search suggest. Now if want to clear(.empty) my div that contains the result from the getJson functions i end up not being able to appennd anything.
So every time I do a search the result div stays empty. If I not try to run the empty function and do a second search, the new information gets appended on top of the previous information.
My site www.karsten-tietje.dk/sw
$('#myinput').suggest({key: "<mykey>","filter": "(all type:/music/musical_group )"
})
.bind("fb-select", function(e, data) {
$.getJSON("http://ws.spotify.com/search/1/track.json?q="+search_val, function(data) {
items = [];
$.each(data["tracks"], function(key, val) {
items.push('<li class="spot"><span typeof="MusicRecording" property="track"><p>Name: <strong><span property="name">' + val["name"] + '</span></span></strong></p> <p>Album <strong>' + val.album["name"] + '</strong></p><p> Released: <strong>' + val.album["released"] +'</strong></p><p><strong><i class="icon-play-sign"></i> Start Spotify</strong></p>');
if ( key === 7 )
{
return false;
}
});
$('#spotify-div').prepend('<h3 style="border-bottom:1px solid white;">Spotify tracks</h3>');
$('#spotify').html(items.join('</li>'));
});
});
This is just a snippet of my some of my code. I run multiple getJson functions.
How can I clear/empty my result div before running the other functions?

Lots of people have explained the mechanics of clearing, which it sounds like you already understand, so perhaps the missing piece is when to do it. You probably want to clear things as the very first thing in your Freebase Suggest select callback, before you fire off any of the queries to other services like Spotify (i.e. before the first $.getJSON()).
Not related to your question, but don't forget the attribution requirement of the Freebase license (not currently provided on your web site).
EDIT: Here's your code with empty added:
$('#myinput').suggest({key: "<mykey>","filter": "(all type:/music/musical_group )"
})
.bind("fb-select", function(e, data) {
$('#spotify-div').empty(); // empty the div before fetching and adding new data
$.getJSON("http://ws.spotify.com/search/1/track.json?q="+search_val, function(data) {
items = [];
$.each(data["tracks"], function(key, val) {
items.push('<li class="spot"><span typeof="MusicRecording" property="track"><p>Name: <strong><span property="name">' + val["name"] + '</span></span></strong></p> <p>Album <strong>' + val.album["name"] + '</strong></p><p> Released: <strong>' + val.album["released"] +'</strong></p><p><strong><i class="icon-play-sign"></i> Start Spotify</strong></p>');
if ( key === 7 )
{
return false;
}
});
$('#spotify-div').prepend('<h3 style="border-bottom:1px solid white;">Spotify tracks</h3>');
$('#spotify').html(items.join('</li>'));
});
});

Select the element and put HTML blank like below
jQuery('#selector').html('');
then after apply the append jquery function on same selector like below
jQuery('#selector').append("<p>text</p>");

You can also do this by clearing the inner html of the html, with id "spotify":
$('#spotify').empty();

With jQuery there can be many ways of emptying an element of its contents and appending/prepending content.
One is .empty(); ( Documentation )
$('#spotify-div').empty().prepend('<h3>YourHTML Here</h3>');
Another is .html( [ html ] ); ( Documentation )
$('#spotify-div').html('').prepend('<h3>YourHTML Here</h3>');
If you are changing the html and not worried about keeping events, you could just pass your html through the .html( 'Your HTML' ); function
$('#spotify-div').html('<h3>YourHTML Here</h3>');

Related

How can make data of each table row into different query string and pass data to another view

As I have made the table body in my javascript which is shown in the below code. As I am new to programming, can anyone tell how to make data of each table row into querystring then pass to another page like html? Thank in advance
var Ref = firebase.database().ref().child("posts");
Ref.on("child_added", snap => {
var name = snap.child("name").val();
var region = snap.child("region").val();
var form = snap.child("form").val();
var code = snap.child("code").val();
$("#table_body").append("<tr><td><a href='postlist.html?key='>" + code + "</td><td>" + name + "</td><td>" + region + "</td><td>" + form. +"</a></td><td>");
$("#table_body").off("click").on( "click", "tr", function() {
});
I would use an HTML5 data attribute on each row to associate the table row with a record held in a persistent array. The click handler would read the data-attribute, pull the target row from the array in order to construct the URL.
So...
const posts = []
const Ref = firebase.database().ref().child("posts")
Ref.on("child_added", snap => {
posts.push({
'name': snap.child("name").val(),
'region': snap.child("region").val(),
'form': snap.child("form").val(),
'code': snap.child("code").val()
})
})
Then, use that array to generate the table:
posts.forEach((post, i) => {
$("#table_body")
.append(`
<tr data-post-index="${i}">
<td>${post.code}</td>
<td>${post.name}</td>
<td>${post.region}</td>
<td>${post.form}</td>
</tr>
`);
})
I removed an <A> tag that was being used badly. You cannot start an <A> in one table cell and then close it in a different table cell. And, since it seems you want row-clicks to be handled using javascript, that anchor is superfluous.
Finally, let's set up the click handler. It will rely on the fact that each row has an HTML attribute that indicates the index of the full record in the array.
$("#table_body").off("click").on( "click", "tr", function() {
const postIndex = $(this).attr('data-post-index')
const post = posts[postIndex]
window.location = `postlist.html?key=${post.code}` // or whatever
});
Warning: it's been a while since I used jquery. I seem to recall that jquery event handlers receive the clicked element as this. If that's not the case, you might need to do a little more work inside that handler to identify the relevant <TR> from the event.
If that's the case, post a comment and I can dig into it. Or you could do a little research and figure it out yourself.

How to reveal dynamic data on click with jquery

EDIT: This is a more sound approach, since provided answer may have bugs when implementing a tags, or img tags.
================================================================
I am calling blog data from an API. (I've reformatted the data into an array by month).
So far, the blog titles print to the web page. I'd like a user to be able to click a title and have its description revealed.
Here is some of my code so far:
var blogPosts = $('#blog-posts');
$.each(byMonth, function(key, value) {
var outer = byMonth[key]
$.each(outer, function(k, v) {
var inner = outer[k]
var monthBlogPosts = $('<div class = "month"> </div>').appendTo(blogPosts);
$.each(inner, function(i, obj) {
title = inner[i].Title
description = inner[i].Description
date = inner[i].DatePublished
$('<div class = "title-list"><h3 class = "unique-title">' + title + '</h3></div>').appendTo(monthBlogPosts)
// if a title is clicked, show its Description
showDescription(description);
})
})
});
function showDescription(d){
$('.unique-title').on('click', function(){
$('<p>' + d + '</p>').appendTo('body')
console.log(d)
})
}
When I click a title, all descriptions print instead of the matching description. I understand this is because I called the function in a nested loop, but I've also had trouble calling the description variable outside of it.
I have also tried
showDescription(title, description)
//...
function showDescription(t, d){
$(title).on('click', function(){
$('<p>' + d + '</p>').appendTo('body')
console.log(d)
})
}
but then nothing is printed to the html page.
Essentially, I'd like to grab the title index, and print it's respective description when its clicked.
you should use event delegation to attach a click event to the document that will bubble up and trigger when .title-list is the event target.
$(document).on('click', '.title-list', function(event) {
showDescription(event.currentTarget) // pass the element being clicked (we will need it later)
})
you would also need to modify the way you get the description.
you could store you description in a data attribute of .title-list like so:
$('<div class = "title-list" data-description="'+ description +'"><h3 class = "unique-title">' + title + '</h3></div>').appendTo(monthBlogPosts)
so you can now modify showDescription() so it would get the data from the element we pass to the function
function showDescription(element){
var d = $(element).data('description')
$('<p>' + d + '</p>').appendTo('body')
console.log(d)
})
So ok. From whatever I could understand (by looking at your code). You cannot register an event with simple on for dynamically added element. You have to use on delegate.
Try this
1) remove the function call (inside a loop)
2) delete the entire function showDescription and add event as below:
$('#blog-posts').on('click', '.unique-title',function(){
alert('title clicked').
});
3) As to display the description I think the best way will be to add the description in a div and hide it. Display it later once the title is clicked.
(inside the loop)
$('<div class = "desc" style="display:none">' + description + '</div>').appendTo(monthBlogPosts);
then on #2 above. Replace with this.
$('#blog-posts').on('click', '.unique-title',function(){
$(this).next('.desc').show(); //I am assuming desc will be next to the clicked title here. You can modify it as needed.
});
Finally, this is just an overview of a code so might not work as expected but I am pretty sure this should give you an idea and get you started

Hide/show div acting on keyup filter input

I have a script that works with a filter to display the current view of tr's in a table. Pretty simple...when you type in the filter, the table updates based on that query and returns the corresponding amount: Displaying 25 results for Search: ________ (the number changes). I then have a div included at the end of that statement that just reflects the text put into the filter: Displaying 25 results for Search: _______ and Filter "blah". I am looking to be able to hide that div when the filter text is deleted from the filter...the filter is deactivated. As of now, it will clear the actual text blah but leave the rest of the div and Filter " ".
Why is this happening? It should be activated/deactivated by the "keyup" of the filter, right? I have tried creating a separate function and adding an if else statement...no dice. I've also tried jQuery's hide() and show() methods as is used for the $('tbody.searchable').hide(); without luck. I'd like it to remain within the same "keyup" function.
$(document).ready(function(){
(function($) {
$('#filter').keyup(function() {
var rex = new RegExp($(this).val(), 'i');
$('tbody.searchable').hide();
$('tbody.searchable').filter(function() {
return rex.test($(this).text());
}).show();
var x = $('tbody.searchable:visible').length;
document.getElementById("filterUpdate").innerHTML = x;
//NEED TO HIDE THIS AFTER TEXT IN THE FILTER IS BACKSPACED (FILTER IS DEACTIVATED)
$('#filterText').html('and Filter = "' + $('#filter').val()+'"');
})
$('tbody').on("click", function() {
if($(this).data('href') !== undefined){
document.location = $(this).data('href');
}
});
}(jQuery));
});
You just need to check whether the input value is empty or not:
$('#filterText').html($(this).val() ? 'and Filter = "' + $('#filter').val()+'"' : '');
JSFiddle

How do you create variables to open up the same type of div?

I am making a website that displays profiles of people. Each person is designated a svg button and when that button is clicked, a pop up displays that persons information.
I have this jquery function:
$('.button1').click(function() {
$('.person1-profile').fadeIn();
});
$('.button1-exit').click(function() {
$('.person1-profile').fadeOut();
});
$('.button2').click(function() {
$('.person2-profile').fadeIn();
});
$('.button2-exit').click(function() {
$('.person2-profile').fadeOut();
});
$('.button3').click(function() {
$('.person3-profile').fadeIn();
});
$('.button3-exit').click(function() {
$('.person3-profile').fadeOut();
});
I'm wondering if it is possible to do this with Javascript so that it significantly shortens the coding, and rather than copy & pasting that code every time for each person, if variables can be made for people/profile and so it would be something like:
$('var person + button').click(function() {
$('var person + profile').fadeIn();
});
$('var button + exit').click(function() {
$('var person + profile').fadeOut();
});
Thank you I really appreciate it! Sorry if it is unclear.
You could use data-attributes for this one:
Define your buttons like that:
<button class="openButton" data-person="3">Open</button>
<button class="closeButton" data-person="3">Close</button>
And your open/close-code like that:
$('.openButton').click(function() {
var personNumber = $(this).attr("data-person");
$('.person'+personNumber+"-profile").fadeIn();
});
$('.closeButton').click(function() {
var personNumber = $(this).attr("data-person");
$('.person'+personNumber+"-profile").fadeOut();
});
In action: http://jsfiddle.net/ndx4fn9n/
I can think of few ways of doing it.
You could read only 7th character of the class name. This limits you to having only 10 fields. Or you could put id on very end like this person-profile1 and read 16th and up character.
You could also set up additional tag to your container. But this will cause your web page to not HTML validate.
<div class="person" personid="1">// content</div>
You can do this in your selector:
var buttons = document.getElementsByTagName(svgButtonSelector);
for (i = 0; i > buttons.length; i++) {
$(".button" + index).click(function() {
$(".person" + index + "-profile").fadeIn();
});
}
This will attach the event to every svg button you've got on your page. You just gotta make sure the scope of selection for the buttons is declared right (I'm using document as an example).

Dynamically added input box problem?

I have dynamically added div.In which i have text box.While adding dynamic div i can put a value to the current div but not the previously open divs. I want to ask how to add Value to the previously open text boxes of Div.
Thank You
here is a solution that refresh ALL. (I don't understand the "previously open text box" part of your question. Well I understand it, but it doesn't show in your code. I assume the "rhythm" column of your table is an input/textarea html element (since you use it's value).
Please note I'm not sure what the vitalset function is supposed to accomplish, or what "vitals_form_readings_1_rhythm" is.
function queryDb(statement)
{
dbQuery = new air.SQLStatement();
dbQuery.sqlConnection = db;
dbQuery.text = statement //"SELECT * FROM rhythm";
//alert(dbQuery.text);
try {
dbQuery.execute();
} catch (error) {
air.trace("Error retrieving notes from DB:", error);
air.trace(error.message);
return;
}
return (dbQuery.getResult());
}
function crhythm()
{
var statement = "SELECT * FROM rhythm";
return queryDb(statement)
}
function reading_speedcode()
{
if (!cvitals) {
var crhythms = crhythm();
var i=0;
$(crhythms).each( function () {
crhythm = this.crhythm;
var pr = 'card_' + i;
$('#rhythm1').append('<br/><td class="content_big" id="'+pr+'" name="'+pr+'">' + crhythm + ' </td>');
i++
});
}
});
$(document).ready( function () {
reading_speedcode();
$('#rhythm1 .content_big').live('click', function(event) {
$('#rhythm1').empty()
reading_speedcode();
});
});
now, there are several things about your code.
variable naming. (for god sake use meaningful names!)
reading full table when you need one row
where is cvitals declared or assigned?
string parsing. Jquery is good at working with set of elements, there should be no need to parse "pr" to recover the row number.
if a value is inserted in rhythm table (or deleted) before your click, the vitalset logic fails. you might want to use the table id instead.
make sure "#vitals_form_readings_1_rhythm" is unique, not retrieved from the table.
if you can answer my question from the top of this post(vitalset function, vitals_form_readings_1_rhythm, cvitals) I will try improve the code.

Categories