1

I am trying to pull the title attribute from links within a class and having a bit of trouble:

<div class="menu">
<a href="#" title="4242" onclick="cselect()">United States</a>
<a href="#" title="4243" onclick="cselect()">Canada</a>
</div>

And here's what I've tried:

function cselect(){
    var countryID = $(this).attr("title");
    location.href = location.href.split("#")[0] + "#" +countryID;
    location.reload();
}

Thanks!

Wex
  • 15,539
  • 10
  • 64
  • 107
APAD1
  • 13,509
  • 8
  • 43
  • 72

3 Answers3

3

Pass in this to your inline handler:

function cselect(obj){
    var countryID = $(obj).attr("title");
    console.log(countryID);
}

<a href="#" title="4242" onclick="cselect(this)">United States</a>
<a href="#" title="4243" onclick="cselect(this)">Canada</a>

Demo: http://jsfiddle.net/yDW3T/

tymeJV
  • 103,943
  • 14
  • 161
  • 157
2

You must refer to the clicked element. One way is to pass this, as tymeJV suggested.

But I would set the event handler from a separate script block and just refer to the current element. For both of the following two solutions no additional inline onclick attribute is required.

/* using jQuery */
jQuery( '.menu a' ).on( 'click', function( event ) {
    event.preventDefault();

    var countryID = jQuery( this ).attr( 'title' ); // <-- !!!

    location.href = location.href.split( '#' )[0] + '#' + countryID;
    location.reload();

} );

or

/* using plain JS */
var countryAnchors = document.querySelectorAll( '.menu a' );
for( var anchor in countryAnchors ) {
    anchor.addEventListener( 'click', function( event ) {
        event.preventDefault();

        var countryID = this.getAttribute( 'title' ); // <-- !!!

        location.href = location.href.split( '#' )[0] + '#' + countryID;
        location.reload();

    }, false );
}
/* todo: cross-browser test for compatibility on querySelectorAll() and addEventListener() */
feeela
  • 29,399
  • 7
  • 59
  • 71
0

It just simple like this:

function cselect(){
    var countryID = $(this).attr("title");
    window.location.hash = countryID
    location.reload();
}
Tony Dinh
  • 6,668
  • 5
  • 39
  • 58