Removing HTML code from a javaScript array? - javascript

Hi I have the following code in a javaScript file called songs:
var marchMD = new Array();
marchMD[0] = ["Save the Best for Last - Vanessa Williams"];
marchMD[1] = ["Informer - Snow"];
marchMD[2] = ["The Sign - Ace of Base"];
for (var i=0;i<marchMD.length; i++) {
songList = songList + '<p>' + marchMD[i] + '</p>';
}
$('#songs').html(songList);
Once this has been loaded, the follow javaScript in the file youtube reacts with the code above:
$(document).ready(function() {
$('#songs p').click(function(e) {
var $el = $(e.currentTarget);
var search = $el.html();
//alert(search);
//return;
var keyword = encodeURIComponent(search);
var yt_url = 'http://gdata.youtube.com/feeds/api/videos?q=' + keyword + '&format=5&max-results=1&v=2&alt=jsonc';
$.ajax({
type:"GET",
url: yt_url,
dataType: "jsonp",
success: function(response) {
if(response.data.items) {
$.each(response.data.items, function(i, data) {
var video_id = data.id;
var video_frame = "<iframe width='420' height='315' src='http://www.youtube.com/embed/" + video_id + "' frameborder='0' type='text/html'></iframe>";
$("#ytVid").html(video_frame);
});
} else {
$("#ytVid").hmtl("<div id='no'> No Video</div>");
}
}
});
});
});
The alert that I have in the code above was a test to see if it would return anything and it doesn't. However, if I remove the href html tag from the code this works. The reason I have it is so when someone clicks one of the songs, it takes them to the top of the page to view that song in youtube.
Thanks

If you know that the element that contains your link will only ever contain your link, you could use text() to strip out the HTML formatting, like this:
var search = $el.text();

When you have the <a> in there, var search = $el.html(); includes the tag as well, not just the text. Try this:
$('#songs p').click(function(e) {
var search = $(this).find('a').html();

Related

Retrieving data from myapifilms.com api

I am following a tutorial on YouTube showing how to get data from the myapifilms.com api and I am having trouble rendering the data to HTML. Currently my ajax call is working and the data is showing in the console. The problem I am having is getting the data to show on the page itself. I searched through the question already asked but had no luck. Here's my js code so far:
$(document).ready(function(){
$("#searchMovie").click(searchMovie);
var movieTitle = $("#movieTitle");
var table = $("#results");
var tbody = $("#results tbody"); //table.find("tbody");
function searchMovie() {
var title = movieTitle.val();
$.ajax({
url: "http://www.myapifilms.com/imdb/idIMDB?title="+ title +"&token= + token goes here +&format=json&language=en-us&aka=0&business=0&seasons=0&seasonYear=0&technical=0&filter=2&exactFilter=0&limit=1&forceYear=0&trailers=0&movieTrivia=0&awards=0&moviePhotos=0&movieVideos=0&actors=0&biography=0&uniqueName=0&filmography=0&bornAndDead=0&starSign=0&actorActress=0&actorTrivia=0&similarMovies=0&adultSearch=0&goofs=0&quotes=0&fullSize=0&companyCredits=0",
dataType: "jsonp",
success: renderMovies
})
function renderMovies(movies) {
console.log(movies);
tbody.empty();
for(var m in movies) {
var movie = movies[m];
var title = movie.title;
var plot = movie.simplePlot;
var posterUrl = movie.urlPoster;
var imdbUrl = movie.urlIMDB;
var tr = $("<tr>");
var titleTd = $("<td>").append(title);
var plotTd = $("<td>").append(plot);
tr.append(titleTd);
tr.append(plotTd);
tbody.append(tr);
}
}
}
});
I feel like I am so close but can't quite figure what I am missing. Again I was following a tutorial so if there's a better way to accomplish this goal I'm definitely open to suggestions.
Update:
I changed my code to this and I'm getting undefined in the browser. I changed the for loop to this
success: function (movies) {
console.log(movies);
tbody.empty();
for (var m in movies) {
$(".movies").append("<h3>"+ movies[m].title +"</h3>");
$(".movies").append("<h3>"+ movies[m].plot +"</h3>");
}
}
I figured out a solution, instead of using myapifilms, I used the tmdb api instead. Changing my code to this worked:
var url = 'http://api.themoviedb.org/3/',
mode = 'search/movie?query=',
input,
movieName,
key = 'myapikey';
//Function to make get request when button is clicked to search
$('button').click(function() {
var input = $('#movie').val(),
movieName = encodeURI(input);
$.ajax({
type: 'GET',
url: url + mode + input + key,
async: false,
jsonpCallback: 'testing',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
console.dir(json.results);
for (var i = 0; i < json.results.length; i++){
var result = json.results[i];
$(".moviesContainer").append('<div class="movies col-md-12">'+
'<img class="poster" src="http://image.tmdb.org/t/p/w500'+ result.poster_path +'" />'
+'<h3>'+ result.title +'</h3>'
+'<p><b>Overview: </b>'+ result.overview +'</p>'
+'<p><b>Release Date: </b>'+ result.release_date +'</p>'
+'</div>');
}
},
error: function(e) {
console.log(e.message);
}
});
});

toggle class of element and add new element in view with old class

I'm working at a comment system for a website.
I am using jquery to update the view after comment under post is posted.
The element I am pushing the comment after post is like this:
<p class="card-text new_comment_{{$i->id}}" style="display:none"></p>
So what I do is
//Manages post in view
jQuery(function ($) {
$(document).ready(function () {
$("body").on("submit", ".dynamic-form", function (e) {
var form_id = '#' + $(this).attr('id');
//removes the 'post_' part from id
var id = this.id.replace('post_', '');
var new_comment_class = '.new_comment_' + id;
var new_comment_class_removal = 'new_comment_' + id;
var comments_id = '#comments_' + id;
var form = $(this);
$.ajax({
url: form.prop('action'),
type: 'post',
dataType: 'json',
data: $(this).serialize(),
success: function (data) {
var resultStr = "";
resultStr = resultStr + "<a href=\"#\">" + data.user_name + " <\/a>" + data.body ;
$(comments_id).find(new_comment_class).html(resultStr).slideToggle(150).promise().done(function () {
$(new_comment_class).fadeIn("fast").toggleClass(new_comment_class_removal);
});
$(form_id).slideToggle(150).promise().done(function () {
$(form_id).fadeOut("fast");
});
}
});
e.preventDefault();
});
});
});
so after the javascript gets executed the element loses the class that permits me to find it in the view so that if the user posts again the body of the post doesn't get appended to that element. But now how do I put a new target element as the original one just above the newly creatded one? like this:
<p class="card-text new_comment_{{$i->id}}" style="display:none"></p>
<p class="card-text">This is the body of the comment</p>
solved using http://api.jquery.com/before/ and some temp variables

Can't add Href to image in Javascript calls, inside Jquery Mobile

I am wondering how to add href link an image to next page in Javascript inside Jquery Mobile.
I am using the exact same code from my normal Jquery but it isnt working in my Jquery Mobile.
Wondering if it is possible to do so inside Jquery Mobile.
I am just trying load some dynamic images into Javascript via AJAX call, then add href to these images which it will click to the next html.
Thanks for your time!
<script>
$.ajax({
type: "GET",
url: "http://test.com/App/testpic.php",
dataType:'json',
success: function(data){
console.log(data);
$(document).ready(function() {
var $el = $('#list');
var listView = new infinity.ListView($el);
for (var i=0; i<50; i++) {
var listingid = data[i].listingid;
var image = "http://test/image/"+data[i].pic;
var myOtherUrl = "detail.html" + encodeURIComponent(listingid);
var $newContent = "<li id=indi href='"+myOtherUrl+"'><img src='"+image+"' width=100% ></img><li>" ;
listView.append($newContent);
var listItems = listView.find('.my-items');
for(var index = 0, length = listItems.length; index < length; index++) {
listItems[index].remove();
}
}
});
}
});
</script>
The li tag does not take an href attribute. You also need an a tag.
var $newContent = "<li id='indi'><a href='" + myOtherUrl + "'><img src='"
+ image + " width='100%'/></a></li>" ;
(Note that you also needed a closing </li>.)

Seeing span tag when I want to be rendering the text within the span tag

I have some words on a page that display "present" or "absent" that a user can click to toggle between being present or absent.
When the word is set to "absent" I want that text to be red.
The word represents a bool and is updated on screen using the following code:
<script type="text/javascript">
absentText = $.trim('#MyApp.Resources.MyAppResource.Absent_Text').toLowerCase();
presentText = $.trim('#MyApp.Resources.MyAppResource.Present_Text').toLowerCase();
updateAttendanceUrl = '#Url.Action("UpdateAttendance", "Attendance")';
</script>
Where MyAppResource.Absent_Text = absent the page displays fine with the word, "absent" on the page.
When I change MyAppResource.Absent_Text to read "absent" my page literally displays <span style="color:red">absent</span>
Here is a sample of my view source:
<td><span style="color:red">absent</span></td>
So somehow my < and > symbols are getting taken away.
How can I change my code so that when the word on my screen is written as "absent" it is colored red?
Is there a simpler way to just color any text on the screen that matches "absent" red?
For reference, here is the rest of the javascript from my page:
var userId;
var attendanceDay;
var isPresent;
var updateAttendanceUrl;
var absentText;
var presentText;
var courseId;
$(document).ready(function (event) {
$('.attendance').live('click', function () {
userId = $(this).parents('tr').attr('id');
if (userId != '') {
attendanceDay = $(this).attr('id');
isPresent = $.trim($(this).find('span').text().toLowerCase());
courseId = $(this).parents('tbody').attr('id');
$(this).find('span').addClass('currentClass');
if (isPresent == absentText) {
UpdateAttendance(1);
} else {
UpdateAttendance(0);
}
} else {
event.preventDefault();
}
});
});
function UpdateAttendance(present) {
url = updateAttendanceUrl;
$.ajax({
type: "POST",
url: url,
data: "userId=" + userId + "&attendanceDay=" + attendanceDay + "&courseId=" + courseId + "&present=" + present,
success: function (data) {
if (isPresent == absentText) {
$('#' + userId).find('.currentClass').text(presentText).removeAttr('class');
} else {
$('#' + userId).find('.currentClass').text(absentText).removeAttr('class');
}
return true;
}
});
}
What your looking for is called unescape or htmldecode. There are various topics available on SO already. Here is one.

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