Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change href value using jQuery

How do I rewrite an href value, using jQuery?

I have links with a default city

<a href="/search/?what=parks&city=Paris">parks</a>
<a href="/search/?what=malls&city=Paris">malls</a>

If the user enters a value into a #city textbox I want to replace Paris with the user-entered value.

So far I have

var newCity = $("#city").val();
like image 557
ram1 Avatar asked Jun 30 '11 19:06

ram1


People also ask

How to change a href using jQuery?

To set of modify the value of the href attribute of a link or the <a> tag, you can use the jQuery . attr() method. This method can also be used to get the value of any attribute.

How to set href value dynamically in jQuery?

Answer: Use the jQuery . attr() Method attr() method to dynamically set or change the value of href attribute of a link or anchor tag. This method can also be used to get the value of any attribute.

How to use jQuery href?

jQuery: Set href attribute at runtime Set href attribute at runtime using jquery. JavaScript Code: $(document). ready(function(){ $('#button1').

Can we use value attribute in anchor tag?

To do that, you can use the ping attribute of the anchor tag. A ping attribute accepts one or more URLs as values.


4 Answers

 $('a').attr("href", "/search/?what=parks&city=" + newCity);
like image 160
AndyL Avatar answered Nov 14 '22 13:11

AndyL


Given you have unique href values (?what=parks, and ?what=malls) I would suggest not writing a path into the $.attr() method; you would have to have one call to $.attr() for each unique href, and that would grow to be very redundant, very quickly - not to mention difficult to manage.

Below I'm making one call to $.attr() and using a function to replace only the &city= portion with the new city. The good thing about this method is that these 5 lines of code can update hundreds of links without destroying the rest of the href values on each link.

$("#city").change(function(o){
  $("a.malls").attr('href', function(i,a){
    return a.replace( /(city=)[a-z]+/ig, '$1'+o.target.value );
  });
});

One thing you may want to watch out for would be spaces, and casing. You could convert everything to lower case using the .toLowerCase() JavaScript method, and you can replace the spaces with another call to .replace() as I've down below:

'$1'+o.target.value.replace(/\s+/, '');

Online Demo: http://jsbin.com/ohejez/

like image 22
Sampson Avatar answered Nov 14 '22 13:11

Sampson


As soon as a key is released within the #city input field, the href will be updated.

$('#city').keyup(function(){

    $('a').attr('href','/search/?what=parks&city='+$(this).val());

});
like image 5
Kokos Avatar answered Nov 14 '22 12:11

Kokos


Like this:

var newCity = $("#city").val();

$('a').attr('href', '/search/?what=parks&city=' + newCity);

EDIT: Added the search string

like image 2
Phil Avatar answered Nov 14 '22 12:11

Phil