jquery what the best way to reset every positioning to default? - javascript

I have a few thumbnails upon clicked, it will display all the works of the user, for example user 1 have 1 work, user 2 have 6 works. By right i will be showing the div accordingly to how many works the user have. If i click on user 1, it show 1 work, i exit and click on user 2, instead of 6 works it show 1 only, because the function takes on what was set on user1, as i didn't reset.. So i wonder if there is a best practices for resetting the show/hide div back to default upon exit, the only solution i know of now is calling the .show each time the function activates, but doesn't seem to be a good way to do things. Please advise
Example
$(function() {
$(".img_thumb_holder").on('click', function() {
var index = $(this).index(); // get current index of clicked thumbnail, so i can call out the related name from captionArray via same index
// what i did to solve the reseting, forcing it to show out each time the function runs
$(".portfolio_thumbImg_holder").show();
$.ajax({
type: "POST",
dataType: "json",
data: ({id: idArray[index]}), // pass the name of clicked holder into php to query
url: "CMS/PHP/retrieveAuthorWorks.php",
success: function(data) {
console.log("Array consist of " + data)
$('.portfolio_thumbImg_holder img').removeAttr("src");
linksArray=[];
titleArray=[];
descArray=[];
$(".full_image_desc .title").html(data[0].title);
$(".full_image_desc .info").html(data[0].desc);
$('.portfolio_thumbImg_holder img').each(function(index, element) {
if (data[index]) {
linksArray.push("http://localhost/testdatabase/cms/" + data[index].links);
$(element).attr("src", linksArray[index]);
titleArray.push(data[index].title);
$(element).attr("title", titleArray[index]);
descArray.push(data[index].desc);
$(element).attr("desc", descArray[index]);
}
});
// check how many divs without the image data, and hide it
$(".portfolio_thumbImg_holder img:not([src])").parent().hide();
}
});
});
});

Related

add click event on img with data from a json (twitch api)

the problem I have is that after creating a list with images that come from the preview of specific streams, I would like to be able to click on these images and replace the stream playing with the stream that comes from the image.
In the code below I get the streamers that play GTA V and do GTA RP. With this info, I get the nickname of the players to create the url with the preview image of their stream.
...
function streamData(auth){
$.ajax({
type: 'GET',
url: 'https://api.twitch.tv/helix/search/channels?
query=FailyV&live_only=true', /** gta V id = 32982 */
dataType:'json',
headers: {
"Client-ID": 'id',
"Authorization": "Bearer "+auth
},
success: function(streamList) {
for (let i = 0; i < streamList['data'].length; i++){
if(streamList['data'][i]['game_id'] == 32982){
gtaList.push(streamList['data'][i]['display_name'])
$('#twitch-embed-low').append('<img id="thumbnail'+i+' " src="https://static-cdn.jtvnw.net/previews-ttv/live_user_'+streamList['data'][i]['display_name']+'-300x200.jpg">')
.on("click", function(e){
console.log(gtaList[i])
})
}
}
new Twitch.Embed("twitch-embed-main", {
width: '80%',
height: '80%',
channel: gtaList[0],
autoplay: false,
layout: "video",
// only needed if your site is also embedded on embed.example.com and othersite.example.com
parent: ["embed.example.com", "othersite.example.com"]
});
let test = $('#twitch-embed-low')
console.log(test[0])
},
error: function(data){
info = document.getElementById("info")
info.innerHTML = "ERROR: " + data["responseJSON"]["message"] + ". Make sure your CID and corresponding secret are set in the JavaScript."
}
})
}
...
As you can see, I have tested this
...
$('#twitch-embed-low')
.append('<img id="thumbnail'+i+' " src="https://static-cdn.jtvnw.net/previews-
ttv/live_user_'+streamList['data'][i]['display_name']+'-300x200.jpg">')
.on("click", function(e){console.log(gtaList[i])})
...
but as you can imagine, it doesn't work (as I suspected) and each time I click on an image, it makes the complete loop and so it doesn't put the right stream in reading but systematically the last one and I'm not talking about the performances which are disastrous since it loads each stream 1 by 1.
So the idea is that when you click on the image, it puts the right stream in reading but I don't see how to do that.
There's a couple of improvments you can make. The first one is you are binding the click handler to the parent element and not to the img element, meaning it will be called (n) times (the length of streamList['data']). This is because you bind the click handler multiple times to the same html element. You want to bind this event handler just to the img element.
Secondly, when the event handler is called, it will be referencing the value of i which will always be the last value of i in the loop iteration. If you want to log the value of i at the point when you create the img element, you will need to use a closure to save the state of i, for example:
var img = $('<img id="thumbnail'+i+' " src="https://static-cdn.jtvnw.net/previews-
ttv/live_user_'+streamList['data'][i]['display_name']+'-300x200.jpg">')
.on("click", (function (index) {
return function (e) {
console.log(gtaList[index]);
};
})(i));
$('#twitch-embed-low').append(img)

Dynamically-generated table keeps multiplying even though it's being cleared

I have a variety of fields I'm appending to a table (#dvdCollectionBody) in my function loadDvdCollectionView().
The problem: if I click the tag that calls my displayDvd() function, then hit the 'Back' button, everything works as it should. If I click the tag, calling displayDvd() a second time, then click the 'Back' button again, the table will be duplicated, indicating that rows are being appended that aren't getting cleared.
I cannot for the life of me understand why the table keeps appending itself, but only after repeating the process of clicking a 'td' tag more than once.
$(document).ready(function () {
loadDvdCollectionView();
// create on a click
createDvd();
});
function loadDvdCollectionView(){
// hide errors
$('#errorDiv').hide();
// show this view
$('#viewingTable').show();
// empty table body of any preexisting data
$('#dvdCollectionBody').empty();
$.ajax({
type: "GET",
url: "http://localhost:8080/dvds",
success:
function (data, status) { $.each(data, function (index, dvd) {
// append DVD collection to table rows in #dvdCollectionBody
var dvdRow = '<tr><td onclick="displayDvd(' + dvd.dvdId + ')">' + .......
$('#dvdCollectionBody').append(dvdRow);
});
}
// called when <td> tag is clicked
function displayDvd(dvdId){
//hide viewingTable
$('#viewingTable').hide();
// empty preexisting data
$('#releaseYearDisplay, #directorDisplay, #ratingDisplay, #notesDisplay, #dvdTitleHeader').empty();
// show table
$('#dvdDetailsDisplay, #dvdTitleHeader').show();
$.ajax({
type: "GET",
url: "http://localhost:8080/dvd/" + dvdId,
success: function (data) {
$('#dvdTitleHeader').append('
<h3>' + data.title + '</h3>'); $('#releaseYearDisplay').append('
<h3>' + data.releaseYear + '</h3>'); $('#directorDisplay').append('
<h3>' + data.director + '</h3>'); $('#ratingDisplay').append('
<h3>' + data.rating + '</h3>'); $('#notesDisplay').append('
<h3>' + data.notes + '</h3>'); }
}
});
$('#backButton').click(function(){
// hide current display and header
$('#dvdDetailsDisplay, #dvdTitleHeader').hide();
// load main view again
loadDvdCollectionView();
});
}
The problem is that, this piece of code:
$('#backButton').click(function(){
// hide current display and header
$('#dvdDetailsDisplay, #dvdTitleHeader').hide();
// load main view again
loadDvdCollectionView();
});
is placed inside your displayDvd() function.
So when the first time your <td> is clicked, the displayDvd() is called and your #backButton callback is added.
Then you hit the #backButton, the callback function is called, everything should work fine here.
However, when you hit the <td> 2nd time, displayDvd() is called again and another click callback is added to #backButton again, also.
This is where the bug occurred. Now your #backButton have 2 same click callback functions attached. So when you click on it, 2 loadDvdCollectionView() are called simultaneously.
Simply move the piece of code into $(document).ready() callback should fix the problem.
You're hiding the DOM elements, but you're not removing them from the DOM. Try the following to remove the content from dvdDetailsDisplay and dvdTitleHeader:
$('#backButton').click(function(){
// hide current display and header
$('#dvdDetailsDisplay, #dvdTitleHeader').empty();
// load main view again
loadDvdCollectionView();
});

jQuery url - editurl -> is there also a addurl

Hi I have a problem in a jquery asp.net project:
I have on one page 2 grids - the main grid is loaded while the second grid is disabled(hidden). When I click on one row in the main grid the second grid is shown then and shows the data if some exist regarding to this row. If there is now data I want to create new data in the second grid. I tried to handle this with url (to get the data), editurl (to modify existing data) which works fine and now I need e.g. a addurl to create new data.
Has anyone an idea to fix this problem because I didn't really found something on the net about this..
onSelectRow: function (id) {
var rid = jQuery('#tblJQGridBereitschaft').jqGrid("getGridParam", "selrow");
if (rid) {
var row = jQuery('#tblJQGridBereitschaft').jqGrid("getRowData", rid);
}
var bs_id = row.ID;
function seturl(bs_id){
jQuery("#tblJQGridBereitschaftFahrtkosten").setGridParam({ loadonce: false })
jQuery("#tblJQGridBereitschaftFahrtkosten").setGridParam({ datatype: "json" })
jQuery("#tblJQGridBereitschaftFahrtkosten").setGridParam({ url: '#Url.Action("GetFahrtkosten", "Bereitschaft")?BS_ID=' + bs_id +'', page: 1 }).trigger('reloadGrid');
jQuery("#tblJQGridBereitschaftFahrtkosten").setGridParam({ editurl: '#Url.Action("ModifyFahrtkosten", "Bereitschaft")?BS_ID=' + bs_id, page: 1 }).trigger('reloadGrid');
// Here I need the "addurl"
jQuery("#tblJQGridBereitschaftFahrtkosten").setGridParam({ loadonce: true })
}
seturl(bs_id);
$("#headerFahrtkosten").show();
$("#jqgrid_containerfahrtkosten").show();
},
Thanks for any help or tips!

Ajax jQuery Multiple Step Form instead of reloading div, just append new content

I wonder if it's possible to do this multistep form on one single page, so not reloading the div with the content received from the php file but append it right below..
This is what I've got so far:
$(document).on('submit', '#reg-form', function(){
var ln = $('#submit').val();
var id = $('#id').val();
var data = 'submit='+ln;
$.ajax({
type: 'GET',
url : 'step.php',
dataType : 'html',
data : data,
success : function(data)
{
$('#reg-form').fadeOut(500).hide(function()
{
$('.result').fadeIn(500).show(function()
{
$('.result'+id).append(data);
});
});
}
});
return false;
});
Also I tried to use different divs, with incremental id's to put every content in it's own div. The Problem is, I'm only getting the "second" step, so it's not going through the whole formular.
I guess it's because the form of the first page is still there and all have the same id.. Can anyone help me out here please?
id of element in document should be unique. Change the duplicate id at html source or using javascript
success : function(data) {
// change duplicate `reg-form` `id` to value
// corresponding to `.length` of elements having `id`
// containing `"reg-form"`
$(data).filter("#reg-form")
.attr("id", "reg-form-" + $("[id*='reg-form']").length);
$("#reg-form").fadeOut(500).hide(function() {
$(".result").fadeIn(500).show(function() {
$(".result" + id).append(data);
});
});
}

Clearing select options with javascript on change

Before you -1 this for being such a simple question read further, because ive spent a while searching and cant figure it out. What i have is 5 select boxes. Each ones results depend on what is selected before it. There is no submit button. I just need the to change based on whats selected in the previous box and so far i have that. Oh and the results are being pulled from a database. The problem is when you select an option in lets say box 1, box 2 options appear, but when you go and select an option in box 1 again, they options are just stacked on the others. I need them to clear when its changed again. I'll post the js i have and if you need anything else just ask.
p.s. im getting the options using php-mysql.
p.s.s this site has to be finished by tomorrow so im kinda in a rush. Please dont waste time telling me this is a stupid question or what not.
Thanks in advance for the help.
$(function () { //When the page is finished loading run this code
$('#country').change(function () {
$.ajax({
url: "<!--Base url taken out-->/discovery/aLoad",
success: function (data) {
eval(data);
},
error: function () {
alert('failed');
},
data: {
country: getSelectValues('#country')
},
type: 'POST'
});
});
});
function changeSearchBar (newBar) {
//remove the crap
function ClearOptions(country)
{
document.getElementById('country').options.length = 0;
}
for (var i = 0; i <= newBar.length; i++) {
newBar[i].id = newBar[i][0];
newBar[i].name = newBar[i][1];
$('#group').append(
$('<option></option>').attr('value', newBar[i].id).text(newBar[i].name)
);
}
}
function getSelectValues (sId) {
var str = "";
$(sId +" option:selected").each(function () {
str += $(this).val() + ",";
});
return str.replace(/.$/g, '');
}
From what I understand from your long post you just need to remove all select child's before starting to append the new option from the AJAX request.
Try something like this before your for loop:
$('#group').html('');​
Demo: http://jsfiddle.net/57TYu/2/
Here you go, I think this is basically what you are trying to do:
How do you remove all the options of a select box and then add one option and select it with jQuery?
Basically, find the 'option' tags inside the select and remove them.
$('select').find('option').remove()
will clear all the select boxes.
This will append the data, which is assume are the options in their place:
$('select').find('option').remove().end().append(data);
I think that is what you are looking for.

Categories

Resources