How to continue jQuery Function - html

I am using the following code to change href links in a page to a new link by using their id.
This is what I'm using to find the href and add the id to it;
$( document ).ready(function() {
$('a[href$="/truck-bed-covers/camper-tops"]').attr('id', 'camper1');
});
And this is what I'm using to change the link.
$(document).ready(function () {
$("#camper1").attr("href", "../camper-tops");
});
It works great. Except it doesn't continue on the rest of the page. It only changes one link and then it's done. How do I continue until there is no more links to change?

ID has to be unique, else JavaScript works with the first one only.
$(document).ready(function() {
$('a[href$="/truck-bed-covers/camper-tops"]').each(function(){
$(this).attr("href", "../camper-tops");
});
});
But I don't think this is the right way. You should find place where you create incorrect links and repair it there (in PHP/DB or where links came from).

At a guess, you're adding the ID so you can refer to the element in the second line, but you don't need to. Once you have an element you can work on it.
You can select all links with something like $('a[href]') (all links with an href attribute) and then iterate over all of them with jQuery's each function. Something like
$(function(){ // shorthand for $(document).ready()
$('a[href]').each(function(index, element){
// work on each element here
var $el = $(element);
$el.attr('href', $el.attr('href').replace(/*whatever you want to do here */);
});
});

Related

Transverse Html Elements Till a Specifc Attribute (id) using Jquery

I am using Jquery 1.7.2.
I want to transverse Html Elements Till a Specifc Attribute (id) using Jquery on
mouse over on any html element in my page.
we have parents() function but problem is how to select stop on the parent element which has id attribute
$("*", document.body).click(function (e) {
e.stopPropagation();
var domEl = $(this).get(0);
var parentEls = $(domEl).parents()
.map(function () {
return this.tagName;
})
.get().join(", ");
$("b").append("" + parentEls + "");
});
this is code but i am getting all element till root
but i want to stop on a closet elements which has attribute id in the tag
Please help me out .
Just use closest:
$(this).closest('#the-id');
Unless your'e just looking for the closest one that has any id attribute, which would be:
$(this).closest('[id]');
Edit: after seeing your updated question, this should be what you want:
$(document).click(function(e) {
e.preventDefault();
var parents = $(e.target).parentsUntil('[id]')
.map(function() { return this.tagName; }).get().join(',');
console.log(parents);
});
Note that this approach accomplishes what you want without selecting and binding click events to every node in the DOM, which is a pretty heavy handed approach.
Edit (again): looks like maybe you wanted to include the tag with the id attribute on it (the above solution is everything up to, but not including that tag). To do this, the solution is pretty similar:
$(document).click(function(e) {
e.preventDefault();
var $parents = $(e.target).parentsUntil('[id]');
var tagNames = $parents.add($parents.parent())
.map(function() { return this.tagName; }).get().join(',');
console.log(tagNames);
});
It looks like you want to map the hierarchy from the clicked element up to the document root. In that case, you can apply parents() to event.target:
$(document).click(function(e) {
e.preventDefault();
var parentEls = $(e.target).parents().map(function() {
return this.tagName;
}).get().join(", ");
});
Note that, as jmar777, you should also change your selector: "*" adds an event handler to all the elements, which is probably not what you want. Bind a single handler to document instead to take advantage of event bubbling.

Why does not jQuery.live function work with static elements?

I have a dynamic HTML table, where I can add and remove rows.
Each row contains a button that has a class removeRow.
In my JavaScript, I have:
$('button.removeRow').live("click", function () {
var row = $(this).parents('tr')
row.remove();
return false;
});
The problem is that it works for all buttons that belong to rows that were inserted after the page was loaded (by clicking on 'Add row' button).
It works for existing buttons, only if I change the above code to (but then it does not work for dynamically added rows):
$('button.removeRow').click(function () {
var row = $(this).parents('tr')
row.remove();
return false;
});
I think that the live function should work for both, so can you point me into the right direction? Where can it go wrong?
OK I found a bug today. Somewhere in my code I had:
$('input[type=submit], button').click(function () {
return false;
});
I wanted it to work with the submit button, so it would not submit the form on click. I do not remember why I put button there. Anyways, because of that my static button clicks were attached this event, while dynamically created ones were not. Therefore live 'click' worked for dynamic buttons. Stupid mistake...
Hacky solution: Do both
$('button.removeRow').live("click", function () {
var row = $(this).parents('tr')
row.remove();
return false;
});
and
$('button.removeRow').click(function () {
var row = $(this).parents('tr')
row.remove();
return false;
});
It would be helpful if you posted some example HTML as well as the code responsible for inserting new rows, though.
Maybe something is going wrong if other tr elements are matched by your .parents() selector. Try .closest():
$('button.removeRow').live("click", function(){
$(this).closest('tr').remove();
return false;
});
The live should work for both dynamic and pre-rendered elements.
I'd start by working out if that content really exists before that jQuery is run...Try outputting the result of the following somewhere, or use the debugger keyword, or even the dreaded alert:
$('button.removeRow').length
// The rest of your click handler definition...

html anchor works only once

I am ashamed to say that I have an anchor issue.
So I have this code:
<a name="map"></a>
$("div.store_list").click(function() {
//do some stuff
location.href = location.href + '#map'
});
When doing the first click it works fine. And the URL changes to:
http://mydomain.local/stores#map
Second click the URL changes to the following and it doesn't work:
http://mydomain.local/stores#map#map
Any suggestions? Thanks
In case you scroll and need to jump again, this has worked for me:
onclick="location.hash=''; location.hash='#map';"
Try location.hash instead, e.g.
location.hash='#map'
Issue was solved using: document.location = "#map";
You can check to make sure the URL doesn't already contain the value you're appending:
$("div.store_list").click(function() {
//do some stuff
if (location.href.indexOf('#map') == -1) {
location.href += '#map';
}
});
The accepted solution didn't work for me sadly. I managed to get it to work in Chrome by setting the anchor value to "#" first, then setting it to my desired location.
document.location.href = "#";
document.location.href = "#myAnchor";
Once I did this, it fired every time I click a link with an anchor tag in it.
$(document).on('click', '.jump_to_instance', e => {
// Get anchor name
var anchorName = $(e.target).attr("href");
// Set anchor to nothing first
document.location.href = "#";
// Set to new anchor value
document.location.href = anchorName;
});
Click me to go to anchor, I should work multiple times
<div id="myAnchor">Will jump to here</div>
Reseting the scroll position on anchor link click event worked for me.
Seems like theres at least one bug with anchor links in Chrome versions 76 - 86 (The most recent macOS version at time of this posting).
Try:
window.scrollTo(0, 0)

How to add events to move to other page for a dynamically created listview in jquery mobile?

using the below code, I have inserted the data in the listview
var renderItemElement = function(item) {
return $.tmpl("<li><a>${text}</a></li>", item)
.data("item", item)
.insertAfter(listHeaders[item.priority]);
};
and when click it, i can remove the data, but when i click it, i want the data to be passed to the next page. Can anyone help me with this code?
$("#bankList").delegate("li.item", "click", function() {
model.remove($(this).data("item"));
$(this).slideUp(function() {
$(this).remove();
});
});
if your has a href or if you want the whole thing to display as a listview at all, you need to use .listview() method. If the ul tag already existed and is a listview, use .listview('refresh')
to move to another page with javascript, not a href, you need to use
$.mobile.changePage()

jQuery datepicker won't work on a AJAX added html element

I have a jQuery datepicker function bound to the "birthday" input html element, written in the page header:
<script type="text/javascript">
$(function() {
$( "#birthday" ).datepicker();
});
</script>
Next, I have some AJAX functionality - it adds new input html element to the page. That element is:
<input type="text" id="birthday" value="" class="detail-textbox1" />
Clicking on that birthday element does not pop up the date picker below the text field. I expected this, as the element is added after the page is loaded, thus it isn't in relation with the function provided in the header.
How can I make it work? I tried moving the script from the header to the body, but nothing seems to work. Thanks.
P.S. If I create an input html element with id="birthday" in the page body, everythig works as expected. It appears that only the elements added through AJAX are dysfunctional.
I'm a bit late to the party, but for thoroughness - and with the .live() function being deprecated from jQuery 1.7 onwards - I thought I'd provide an updated solution based on my experiences, and from all the help I got from other answers on StackOverflow!
I had a situation where I needed to add the datepicker functionality to input fields that were being added to the DOM through AJAX calls at random, and I couldn't modify the script making the AJAX calls to attach the datepicker functionality, so I opted for the new shiny .on() function with its delegation features:
// do this once the DOM's available...
$(function(){
// this line will add an event handler to the selected inputs, both
// current and future, whenever they are clicked...
// this is delegation at work, and you can use any containing element
// you like - I just used the "body" tag for convenience...
$("body").on("click", ".my_input_element", function(){
// as an added bonus, if you are afraid of attaching the "datepicker"
// multiple times, you can check for the "hasDatepicker" class...
if (!$(this).hasClass("hasDatepicker"))
{
$(this).datepicker();
$(this).datepicker("show");
}
});
});
I hope this helps someone, and thanks for all the answers so far that led me to this solution that worked for me! :)
You need to use .live() so that any newly added elements have the event handler attached: http://api.jquery.com/live/
$('#birthday').bind('load', function() {
$(this).datepicker();
});
EDIT
.live() documentation states, that it is a bit out of date. With new versions of jquery (1.7+) use .on().
Boris, JK: This was super helpful for me. I have also found that you can use the following for AJAX html if you want to use Datepicker's date range selection:
$('#groundtransporation').live('focus', function() {
var gt = $( "#rentalPickUp, #rentalDropOff" ).datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 2,
onSelect: function( selectedDate ) {
var option = this.id == "rentalPickUp" ? "minDate" : "maxDate",
instance = $( this ).data( "datepicker" ),
date = $.datepicker.parseDate(
instance.settings.dateFormat ||
$.datepicker._defaults.dateFormat,
selectedDate, instance.settings );
gt.not( this ).datepicker( "option", option, date );
}
});
});
I got another case.
My script is copying last table elements including datepicker.
The jquery will not working because the copied element has mark that it "hasDatepicker".
To activate datepicker in new element, remove that class name and the initiate it, like this.
$("#yournewelementid").attr("class","your-class-name");
$("#yournewelementid").datepicker();
your issue is always happens when elements don't exist when you try to initialize it.
When you use $(function(){/** some code **/}); elements must exsit on the document, it means that has to be on the html so you could can create a function to initialize the component or initialize it on the success event after been add it to the document.
Is important to first add the external html load in the ajax request to the document before you try to initialize it or it won't be initialize at all.
Example:
$.ajax({
url:"ajax_html.html",
dataType:"html"
}).done(function(html){
$("#selector").html(html)
init();
});
function init(){
$(".birthday").datepicker({});
}
You could initialize the date picker for the newly added element within your ajax success callback:
$.ajax({
...
success: function(response) {
if(response.success) {
$(body).append(response.html);
$("#birthday").datepicker();
}
}
});