Append url and redirect onclick - javascript

I currently have a function used to get a list of 5 website names (title) as well as 5 urls
The code below is pulling the list of 5 titles but how would I go about append the title so that it will redirect to the url on click
function getFavorites() {
$.getJSON("/Home/UserFavorites", function (result) {
var options = $("#userfavorites");
List = "";
$('#userfavorites >option').remove();
$.each(result, function () {
options.append($("<option />").val(this.url).text(this.title));
List = List + "," + this.title;
});
}).complete(function () {
$.unblockUI();
});
}

$("#userfavorites").change(function(){
window.location.href = $(this).val();
});

Related

Randomising Data in The Movie DB API

I am currently developing a Mobile App using the Movie DB API.
I have currently got the data pulling through but it's being hardcoded to bring up Spiderman from the Database.
Could anyone point me in the right direction? I have attached my code below :)
$(document).on('pageinit', '#home', function(){
// $(document).ready(function(){
console.info('hi');
var url = 'http://api.themoviedb.org/3/',
mode = 'search/movie?query=',
movieName = '&query='+encodeURI('Spiderman'),
key = '&api_key=7b0b1d8b1253e2bbfcd5602f76c52fdb';
$.ajax({
url: url + mode + key + movieName ,
dataType: "jsonp",
async: true,
success: function (result) {
console.dir(result);
ajax.parseJSONP(result);
},
error: function (request,error) {
alert('Network error has occurred please try again!');
}
});
});
$(document).on('pagebeforeshow', '#headline', function(){
$('#movie-data').empty();
$.each(movieInfo.result, function(i, row) {
if(row.id == movieInfo.id) {
$('#movie-data').append('<li><img src="http://image.tmdb.org/t/p/w92'+row.poster_path+'"></li>');
$('#movie-data').append('<li>Title: '+row.original_title+'</li>');
$('#movie-data').append('<li>Release date'+row.release_date+'</li>');
$('#movie-data').append('<li>Popularity : '+row.vote_average+'</li>');
$('#movie-data').listview('refresh');
}
});
});
$(document).on('vclick', '#movie-list li a', function(){
movieInfo.id = $(this).attr('data-id');
$.mobile.changePage( "#headline", { transition: "slide", changeHash: false });
});
var movieInfo = {
id : null,
result : null
}
var ajax = {
parseJSONP:function(result){
movieInfo.result = result.results;
$.each(result.results, function(i, row) {
console.log(JSON.stringify(row));
$('#movie-list').append('<li><a href="" data-id="' + row.id + '"><img src="http://image.tmdb.org/t/p/w92'+row.poster_path+'"/><h3>' + row.title + '</h3><p>')
})
}
}
Regards
Tom
Spiderman is being hardcoded into the Url here, so you need to obtain the search string, save it in a variable and replace the hardcoded spiderman:
var searchString = 'your_search_string'
var url = 'http://api.themoviedb.org/3/',
mode = 'search/movie?query=',
movieName = '&query='+encodeURI(searchString),
key = '&api_key=7b0b1d8b1253e2bbfcd5602f76c52fdb';
Also if you just want a list of movies not necessarily related to a search string you can try the discover endpoint of Movie DB API http://api.themoviedb.org/3/discover/movie.
Documentation link

assign multiple value to javaScript array object

i have coded jQuery widget, which list all the record title in table which user can select of multiple records but with each record user to need to put value in text box.
now i want to built jQuery or JavaScript array where i can push record with each user click add and remove data if click remove against each button.
i want to push "recordId" & "ComponentSchemeMarks" to javaScript array selectedComponentList
var selectedComponentList = {
componentIndex: "",
componentMark:""
};
$(document).ready(function () {
//click on Confirm Component Scheme
$("#ComponentSchemeTable").on("click", ".k-grid-confirm", function () {
var recordId = $(this).data("id");
var ComponentSchemeMarks = $("#" + recordId + "_CM").val();
alert("recordId " + recordId + " ComponentSchemeMarks " + ComponentSchemeMarks);
//
$(this).hide();
$(this).siblings(".k-grid-input").hide();
$(this).siblings(".k-grid-cancel").hide();
$(this).siblings(".k-grid-Remove").show();
//add data to array//
});
$("#ComponentSchemeTable").on("click", ".k-grid-Remove", function () {
$(this).hide();
$(this).siblings(".k-grid-Add").show();
});
Your selectedComponentList is not an array... I guess you want something like this:
var selectedComponentArray = [];
$(document).ready(function () {
//click on Confirm Component Scheme
$("#ComponentSchemeTable").on("click", ".k-grid-confirm", function () {
var recordId = $(this).data("id");
var ComponentSchemeMarks = $("#" + recordId + "_CM").val();
alert("recordId " + recordId + " ComponentSchemeMarks " + ComponentSchemeMarks);
//
$(this).hide();
$(this).siblings(".k-grid-input").hide();
$(this).siblings(".k-grid-cancel").hide();
$(this).siblings(".k-grid-Remove").show();
//add data to array//
selectedComponentArray.push({ComponentIndex: recordId, ComponentMark: ComponentSchemeMarks});
});
$("#ComponentSchemeTable").on("click", ".k-grid-Remove", function () {
$(this).hide();
$(this).siblings(".k-grid-Add").show();
var recordId = $(this).data("id");
selectedComponentArray = $.grep(selectedComponentArray, function(value) {
return value.ComponentIndex != recordId;
});
});
...
}
Moreover you should give the buttons IDs and use them for binding the click listeners...

AJAX list update, get new elements and count

I have this HTML list
<ul id='usernameList'>
<li class='username'>John</li>
<li class='username'>Mark</li>
</ul>
and a form to add new names via AJAX, multiple add separated by commas. The response is a list with the names
[{name:David, newUser:yes}, {name:Sara, newUser:yes}, {name:Mark, newUser:no}]
I'm trying to insert this names sorted alphabetically in the list, like this example https://jsfiddle.net/VQu3S/7/
This is my AJAX submit
var form = $('#formUsername');
form.submit(function () {
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
dataType: "json",
beforeSend: function () {
//
},
success: function (data) {
var listUsernames = $('#usernameList');
var numUsernames = listUsernames.children().length;
$.each(data, function(i, user) {
if(user.newUser == "yes"){
var htmlUser = "<li class='username'>" + user.name + "</li>";
var added = false;
$(".username", listUsernames).each(function(){
if ($(this).text() > user.name) {
$(htmlUser).insertBefore($(this));
added = true;
}
});
if(!added)
$(htmlUser).appendTo($(listUsernames));
}
// HERE I DO alert('numUsernames')
// I get the same number of users before sending form
// How can I update here the value of listUsernames and numUsernames?
});
}
});
return false;
});
My question is, how I can update the value of listUsernames and numUsernames after adding an item?
You just need to update numUsernames at that point.
Add this where your comments are:
numUsernames = listUsernames.children().length;
listUsernames already has the updated children, as it's a reference to the parent element.
Edit: Re: your comment below:
This should probably work:
$(".username", listUsernames).each(function(){
if ($(this).text() > user.name) {
$(htmlUser).insertBefore($(this));
added = true;
return false; // stop `.each` loop.
}
});
First you don't need a double jQuery wrapping:
$(htmlUser).appendTo($(listUsernames));
listUsernames is already a jQuery object, so try:
$(htmlUser).appendTo(listUsernames);
And after every adding, you can update the numUsernames variable with:
numUsernames = listUsernames.children().length;
but this is not necessary because you can always access listUsernames.children().length in the success handler.
I update your JSFiddle
var listUsernames = $('#usernameList');
var numUsernames = listUsernames.children().length;
var data = [{name:'David', newUser:'yes'}, {name:'Sara', newUser:'yes'}, {name:'Mark', newUser:'no'}]
$.each(data, function(i, user) {
if(user.newUser == "yes"){
var htmlUser = "<li class='username'>" + user.name + "</li>";
var added = false;
$(".ingredient", listUsernames).each(function(){
if ($(this).text() > user.name) {
$(htmlUser).insertBefore($(this));
added = true;
}
});
if(!added)
$(htmlUser).appendTo($(listUsernames));
}
// HERE I DO alert('numUsernames')
// I get the same number of users before sending form
// How can I update here the value of listUsernames and numUsernames?
});

How to send JSON object list to light box?

In MVC 4 application I want when click a link, to show some related Products list in lightbox. I have method returns products I need:
public ActionResult GetRelatedProducts(int id)
{
var realProducts = GetRelatedProducts(id);
List<object> productsObjectList = new List<object>();
foreach (var item in realProducts)
{
productsObjectList .Add(new
{
id = item.Id,
fullname = item.Name
});
}
return Json(productsObjectList , JsonRequestBehavior.AllowGet);
}
HTML is:
<a class="show" id="show">Show</a>
<div id="productBox" style="display: none;">
// Product list will get here
</div>
And script:
$('#show').click(function (e) {
url = '#Url.Action("GetRelatedProducts", "Product")';
var data = { id: '#Model.Id' };
$.post(url, data, function (result) {
$('#productBox').lightbox_me({
onLoad: function () {
//How to send returned product list to light box, to show them by foreach loop
}
});
e.preventDefault();
});
});
How can I send product list to productBox to show products?
You code:
$('#show').click(function (e) {
url = '#Url.Action("GetRelatedProducts", "Product")';
var data = { id: '#Model.Id' };
$.post(url, data, function (result) { // <- "result" will contain array
$('#productBox').lightbox_me({
onLoad: function () { ... }
});
e.preventDefault(); // <- this must prevent "a" tag, put it outside
});
});
You could use your list on client side like this:
$.post(url, data, function (result) {
var list = '<ul>';
for(var i = 0; i < result.length; i++)
{
list += '<li>' + result[i].fullname + '</li>';
}
list += '</ul>';
$('#productBox').html(list).lightbox_me();
});
OR as Vladimir Bozic wrote, just use PartialViewResult, from controller return PartialView, it is like normal view, but without layout, just html block and you can use it like:
$.post(url, data, function (result) {
$('#productBox').html(result).lightbox_me();
});

My table get duplicated rows with Jquery Table Sorter

I have search field in my project, which uses $.post for getting the results for the search query.
My problem: When a user click on the search button it works correctly, however when a user click on the search button again, and then click on my thead columns jquery sorter duplicates it with the previous search shows in the table.
How can I solve this so my sorter function does not duplicate?
this is the Jquery code for the search button click.
$(function () {
$('#submitfloat').click(function () {
$('#loading').show();
setTimeout(function () { $("#loading").hide(); }, 800);
var SubjectTypes = $('#SubjectTypes').val();
var Teams = $('#Teams').val();
var Companies = $('#Companies').val();
var Consultants = $('#Consultants').val();
var PlannedDates = $('#PlannedDates').val();
var CompletedDates = $('#CompletedDates').val();
var DateTypes = $('#DateTypes').val();
var data = {
Subjectypes: SubjectTypes,
Companies: Companies,
Teams: Teams,
Consultants: Consultants,
PlannedDates: PlannedDates,
CompletedDates: CompletedDates,
DateTypes: DateTypes
};
var fromDate = $('#PlannedDates').val();
var endDate = $('#CompletedDates').val();
if (Date.parse(fromDate) > Date.parse(endDate)) {
jAlert("End date must be later than start date", "Warning");
return false;
} else {
$('#GoalcardSearchResult tbody').hide();
setTimeout(function () { $("#GoalcardSearchResult tbody").show(); }, 800);
$.post('#Url.Action("Search", "SearchNKI")', data, function (result) {
$("#GoalcardSearchResult tbody").empty();
result.forEach(function (goalcard) {
$("#GoalcardSearchResult tbody").append(
$('<tr/>', {
click: function () {
id = goalcard.Id;
var url = '#Url.Action("AnswerForm", "AnswerNKI", new { id = "__id__"})';
window.location.href = url.replace('__id__', id);
},
html: "<td>" + goalcard.Name + "</td><td>" + goalcard.Customer + "</td><td>" + goalcard.PlannedDate + "</td><td>" + goalcard.CompletedDate + "</td>"
}));
});
$("#GoalcardSearchResult").tablesorter();
});
return false;
}
});
});
Your help is appreciated, thanks in advance!
I'm guessing tablesorter has already been initialized before the user clicks on the sort button. In that case, replace this code:
$("#GoalcardSearchResult").tablesorter();
with this:
$("#GoalcardSearchResult").trigger('update');

Categories

Resources