Index of list item clicked does not reset - javascript

On a fresh page load, the code works just fine and will display the correct information, but if you navigate backwards and try again, it displays the information from the first click. First off, here is the code and I will explain what I have...
$(document).on('pageinit', '#months', function(){
$('#listOfHolidays').on('click', 'li', function () {
listIndex = $(this).index();
$.mobile.changePage('#detail');
});
});
$(document).on('pageinit', '#detail', function(){
console.log(listIndex);
$('#ho').text(holidayNames[listIndex]);
$('#hi').text('The index of the list item clicked is: ' + listIndex);
});
I have 2 pages (divs with data-role="page") named #months, which is the one containing my list of items to select from, and #detail which is a page that I want to populate based on the user's choice from the list. The id for my listview is #listOfHolidays and the array which holds the values of each item in the list is called holidayNames. I then display this basic info in the detail page in divs called #hi and #ho (some of this will be changed, I am just trying to test my way out of this problem). I have a back button enabled in the header of detail also.
Like I said, when I load this fresh, the correct holiday name and index number show up in my detail page, but when I use the back button to navigate back and try again, it populates the detail page with the same info from the first click.
I would assume this is because jquery is initializing the detail page in the second $(document).on() function with 'pageinit' and since it is initialized with the first index and holiday name I choose, it just doesn't need to initialize again and draws the data from the first request when I click another list item.
That is my vague understanding of what is going on, so please correct me where I'm wrong and guide me in the right direction!
Thanks!

The 'pageinit' event only fires when the page is introduced to the DOM. Thus the code you have bound to replace the holiday text with the new one, only fires on the original click. The next few clicks do not cause that function to fire.
If you bind to the 'pagebeforeshow' then it will trigger everytime you change pages and you can bind the same function there and it should work correctly.
$(document).on('pagebeforeshow', '#detail', function () {
console.log(listIndex);
$('#ho').text(holidayNames[listIndex]);
$('#hi').text('The index of the list item clicked is: ' + listIndex);
});
I removed some things to simplify the example.
JSFiddle example

Related

Jquery datatables pagination issue

So I have a map defined where there are two tables as an example. When you click on one item in the first table, it will highlight the corresponding related item/row on the second table. The issue I am facing is that I have added Pagination on these tables. So lets say when I select an item in table 1 and if it corresponds to an item in table 2 which is on page 2, when I click on page 2 on the second table, it loses the highlight.
Now I have the function which essentially has the objects which I care about but I feel I am missing the right jquery function (onclick/something else??) that I need to call.
ForEg: Lets say I pass the information during the below function. What happens is that the below function works when I click on the current page twice. i.e. Once to go to page and second when I am on that page.
Scenario:
Click on item in table1 (that corresponds to item in table 2 on page 3)
Click on button 3 to view the corresponding page (Ideally the below function should have been called but it doesn’t)
Click on button 3 again and the below function gets called.
jquery(function1 + ‘ .page_button.current’).on(‘click’, function(e){
console.log(“Entering here”)
});
I want it to be called when I go to that page for the first time.
Can anyone please help me with what I am doing wrong. What function do I need to use apart from this ‘click’ which would help?

Checked boxes on one page are carrying over to a new page

I am building a site for work.
It consists of four pages which are the exact same structure but different content.
The structure is three columns, the first is a vertical series of check boxes, the second is a logo, the third is another vertical series of check boxes.
The goal is to,
Be able to go to page one, click the check boxes needed, and keep those boxes checked upon refresh.
Then you should be able to click a link to the second page and have a fresh set of check boxes.
The content is there, the links are there, all of the check boxes are there and remain upon refresh.
The problem I'm having is that when I check a few boxes on page one and then click on the link to page two, the same check boxes are still checked, even though it's an entirely new page and new content.
I tried linking each of the four pages to their own JavaScript file and that didn't change anything. I am new to developing and am not sure what to try next.
Here is the JavaScript code I am using:
jQuery(function(){
if (localStorage.input) {
var checks = JSON.parse(localStorage.input);
jQuery(':checkbox').prop('checked', function(i) {
return checks[i];
});
}
});
jQuery(':checkbox').on('change', function() {
localStorage.input = JSON.stringify(jQuery(':checkbox').map(function() {
return this.checked;
}).get());
});
This works great if it's a one page site but again, when I visit one of the other pages, the check boxes don't refresh.
If anyone can, please help me with this.
You're storing the checkbox information in input on localStorage for every page. The data is just an array of true/false values indicating whether or not the checkboxes on a page are checked.
If you run this code on another page which has checkboxes then they'll be put into that state.
You need to store the information in a way that identifies which page it's on, e.g.
localStorage[window.location.href] = ...
Or
localStorage.setItem(window.location.href, ...)
You could also store the state of the checkboxes against their names/ids to avoid coupling the state to the order of the boxes on the page e.g.
let state = {
'choice0': true,
'choice1': false,
...
}

Multiple instances of same variable

I'm using an AJAX call to pull filenames from a database which are then used to populate a carousel with images of the same name.
My web app makes use of tabs which when tapped, reload the AJAX and pull from the database a different set of filenames which then repopulate the carousel.
What I'm finding is when the web app initially loads, the carousel works fine, but if I tap any of the tabs, the carousel begins to function incorrectly, i.e. the first time I tap and then use the carousel the carousel moves by two images at at time, a second tap and the images move three at a time, so on and so forth.
If I check console I can see that following the call, when I click either the left or right arrow in the carousel, it's as if there are two instances of the same variable, or as if both AJAX calls are being called in some way. Image attached to show what I mean.
As you can see, following initial load everything is fine, however once any subsequent calls are made it's as if the count from the previous call continues, and a secondary count also starts associated with the new data, or a third or fourth or fifth, dependent on how many calls have been made.
$('.tabs-nav li').on('click', function() {
tabName = $(this).html();
place = 0;
products = getProductDetails(selected); //AJAX call
data = dealWithData(products, place); //Deferred object that works data
});
Sounds like you are having a scoping issue. The easiest way is to have your logic in a closure so your variables get scoped to the particular tab. So instead of something like this:
var place,count
$(".tabs").on('click',function(){/*shares same place & count */});
it would look like this:
$(".tabs").each(function(){
var place,count
$(this).on('click',function(){/*each has their own place,count*/});
});

Call javascript from appended text (order cart)

Let's say that I'm building something like order cart.
I have one main page, and a lot of subpages.
On the subpages I have some specified product which user can add to the order by clicking on the button.
If the user click the button, javascript is called grabbing the name of the product and sending it AJAX to some PHP file which add this product name to some $_SESSION array.
If there's atleast one product in the cart, the FIXED div on the bottom of the screen appear. This div runs modal (bootstrap) and it contains all of the products which user had add to the order. Again I'm using here javascript + AJAX to determine click. If it's, there is a call to .php file which return STRING contains all the products. Then, this string is appended to the div inside this modal.
Content of this modal looks like:
'name_of_the_product', 'delete', 'id_from_session_array'
...
...
So I want allow the user to use DELETE option for any of his products in this list if he no longer want this product in the cart. I wrapped the delete text in some anchor and gave it class - let's say '.delete_from_cart'.
And now, when I'm trying to check in javascript if this element ('.delete_from_cart') has been clicked, nothing happens.
Sample code for this looks like:
$('.delete_from_cart').click(function() {
alert("foo");
});
No alert at all after clicking some .delete_from_cart div. However, in the code source all of this anchors has this class.
How to fix that? It seems like javascript doesnt see appended elements from ajax in this div. Any help?
since you said that your modal is generated using an Ajax call, you will not be able to attach the click event to the element. You will need to use jQuerys on() method to bind the onclick.
$("#themodal").on( "click", ".delete_from_cart", function(){
alert('it worked');
});
See on() method more details.
https://api.jquery.com/on/

Trying to build a clickable index with PHP / Javascript that displays data for each item clicked

I have spent a lot of time trawling the web for help on this, but I haven't found anything that does what I'm looking for and having tried to cobble together solutions from multiple sources, have basically run into a dead end.
What I'm trying to do is create a web page to list musicians on one part of the page so that I can click on the name of an individual musician and load a list of their albums, songs, lyrics, etc. on another part of the same page. The data is all in a MySQL database and each item in the database has a unique ID.
I can get the data out of the database and into an array and I can create a list of musicians and also a list of their info on a separate part of the page if I manually set a the ID. If I can get a click to return the ID I can then focus on trying to get my head around using Ajax to load the required data, and I guess JQuery to display it where I want it on the page, but I am stuck on getting the clickable list working.
I am using Joomla 3.1 to create the site but the code is just PHP and Javascript.
My most recent effort is as follows:
<ul id="nav" style="list-style:none">
<?php
foreach ( $this->items as $item ) {
echo '<li id='.$item->itemid.' onclick="$(this).index()" >'.$item->title.'</li>';
}
?>
"</ul>"
<script>
linkClicked = function (index) {
alert($('#nav li').get(index).id);
}
Like all my other efforts this creates a nice list but nothing happens when I click on any of the listed items and I am clearly way off track. I had intended that this would display an alert showing the id of the item selected, but no alert appears. I have a feeling that the solution is pretty trivial but I am just not getting it and any help would be very gratefully received.
For anyone not familiar with Joomla, it provides functions that load MySQL data into an array, with individual items being accessed using the name of the relevant column from the database. So $item->title gives the value of the 'title' field for the current row of data.
you need to fire your code when the document is ready. your code is not triggered. You need to bind a click event to your li tags on document ready like so:
//on document ready
$(function(){
//select the li tags from #nav and bind a click event to them
$('#nav li').on('click', function(){
//When li is clicked: alert the attribute "id" from the clicked element (this = li element)
alert($(this).attr('id'))
})
});
with delegation:works also for elements that are dynamical added to the dom (after the page has loaded, for example by an ajax call)
$(function(){
$('#nav').on('click', 'li', function(){
alert($(this).attr('id'))
})
});

Categories

Resources