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!

1
  • 2
    On a side note, never use onclick or other javascript within your HTML layer, don't mix in business logic. Create a javascript event handler instead! Commented Oct 29, 2013 at 15:44

3 Answers 3

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/

Sign up to request clarification or add additional context in comments.

1 Comment

@BharathRallapalli -- OP is using it in his demo.
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() */

1 Comment

Thank you, will go with this approach.
0

It just simple like this:

function cselect(){
    var countryID = $(this).attr("title");
    window.location.hash = countryID
    location.reload();
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.