0

I want to access the value of the HTML title attribute as a variable for the onclick function.

This is an example for my HTML elements:

<a title="id:4" onclick="openWin(4)">example</a>

This is my JavaScript function:

function openWin(number)
{
    window.open("http://www.some-example.org/some/example/id:"+number)
}

This works but since I have a lot of HTML elements, I'd like to find a way to reference the title value inside the openWin() function instead of writing "openWin(someNumber)". Do you have any ideas how to do this?

Any help would be much appreciated!

2

6 Answers 6

4

You could do this :

HTML :

<a title="id:4">example</a>

JavaScript :

$(function(){
     $('a[title]').click(function(){
         window.open("http://www.some-example.org/some/example/"+this.title)
     });
});
Sign up to request clarification or add additional context in comments.

Comments

3
$('a').on('click', function () {
    var number = this.title.replace('id:', '');
    window.open("http://www.some-example.org/some/example/id:" + number)
});

Comments

3

Here is solution if you want Number value only from Tittle:

HTML

<a title="id:4" onclick="openWin(this)">example</a>

JS

function openWin(el)
{
    window.open("http://www.some-example.org/some/example/id:"+el.title.split(':')[1]);


}

Here is live URL:

http://jsbin.com/eGUCoWU/4/edit

1 Comment

+1 for split(':')[1] even if this answer still uses inline JS event handler;
1

How about this

$('a').click(function(){
    titleVar = $(this).attr('title').slice(3,4);
    ... do something with titleVar
 });

I might not have got the slice parameters right but, this will grab the title attribute, remove the 'ID:' bit and put the number alone into 'titleVar'. You can then do whatever you wish with titleVar.

Comments

1
$('a').click(function(){
  window.open("http://www.some-example.org/some/example/id:"+ $(this).attr('title').split(':')[1]);
});

Comments

-1

Inside your event handler function, this will be the HTML element on which the event fired.

HTML elements have a title property containing the value of the title attribute.

onclick="var foo = this.title"

You can then do whatever you like with foo.

Comments

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.