1

I'm look for a way I can have a list of countries using ... so when you click on a link, the country code parameter is passed over to qjuery which will inturn return a list of cities.

I have been able to do all this using a dropdown, but want to change it to a.href links.

Something like the below...

$('#country').click(function(event) {  
// get the countryCode value here
var $country=$("a#country").val();
...

These need to pass countryCode

<a href="#" id="country">Australia</a>
<a href="#" id="country">United Kingdom</a>
<a href="#" id="country">NewZealand</a>
3
  • 1
    I suggest that id should be unique. and .val() returns null. Use .html() instead. Commented Nov 18, 2013 at 19:25
  • 3
    Using the same "id" for multiple elements is incorrect. You can use a "class" instead. Commented Nov 18, 2013 at 19:25
  • 1
    anchor tags don't have a value. What you want is it's text. Commented Nov 18, 2013 at 19:26

4 Answers 4

5

In html5 its best to use custom attribute:

<a href="#" class="country" data-code="au">Australia</a>
<a href="#" class="country" data-code="uk">United Kingdom</a>
<a href="#" class="country" data-code="nz">NewZealand</a>

In JS:

$('.country').click(function(event) {  
    var $country = $(this).data('code');
}
Sign up to request clarification or add additional context in comments.

2 Comments

You can't have them all with the ID country.
Thanks guys, I'm sure a few of these would have worked, but I've gone straight to the one at the top and it's done exactly what I was hoping. Cheers! :-)
1

Change that id to a class and do:

$(".country").click(function(e) {
    e.preventDefault();
    var country = $(this).text();
});

Comments

1

First off, you shouldn't have multiple items with the same id.

You could store the country code as data:

<a href="#" class="country" data-country="aus">Australia</a>

And then retrieve it:

$('.country').on('click', function(e) {
    e.preventDefault();
    var country = $(this).data('country');
})

Comments

-1
<a href="#" class="c" id="country1">Australia</a>
<a href="#" class="c" id="country2">United Kingdom</a>
<a href="#"  class="c" id="country3">NewZealand</a>


$('.c').click(function(event) {  

event.prenventDefault(); 
var $country=$(this).html();
//var $country=$(this).text(); //or you can try this.
//...
});

1 Comment

No. $("a#country") won't work as you expect since IDs are supposed to be unique.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.