Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: set title of option in select tag with javascript

I am working on a project where I have a select tag with its options being generated in a javascript function. I am currently populating the "title" attribute of each option with a detailed description.
Inside the javascript function I am currently doing something like this:

var country = new Option("countryUSA", "United States of America");
$("#mySelect").get(0).options[1]=country;

This works fine, the option shows up. However, I also need to set the "title" attribute of that html option element. I have tried something like this:

country.title="Full description of USA";

but it does not work.
I know I can do something like this:

 $("#mySelect").get(0).options[1].title="My title";

but I was trying to set the title before adding the option to the select tag. Isn't the "Option" object suppose to allow me to set the "title" property? The javascript function is not even executed. Is there no way I can set the "title" attribute for an "option" html element in javascript?

like image 939
Johnny Avatar asked Aug 10 '11 23:08

Johnny


People also ask

How do I get the text value of a selected option in JavaScript?

function myNewFunction(element) { var text = element. options[element. selectedIndex]. text; // ... }


2 Answers

It looks like you're using jQuery. There is a much simpler way to do what you want. Just use the jQuery API rather than regressing back to vanilla DOM:

$('<option>',
{
    value: 'countryUSA',
    title: 'Full description of USA',
    text: 'United States of America'
}).appendTo("#mySelect");

That said, do you expect setting the title to make a browser-native tooltip to appear while the hovering over the <option>? At least in Chrome, no such tooltip will appear.

Try it yourself: http://jsfiddle.net/GMTLn/1/


Edit Chrome and Safari do not show a tooltip on <option>s with a title attribute because WebKit doesn't. See this bug report.

like image 191
Matt Ball Avatar answered Oct 18 '22 10:10

Matt Ball


You can set the title attribute

   $('#mySelect').append(
   $("<option/>", { text: value }).attr("title",value)); 

Here is a working sample http://jsbin.com/ozudoTod/1/

Or this way :

     value = cleanNulls( value );
     var option = $( '<option/>', {
     title: value,
     text: value
     });
     $('#mySelect').append( option );
like image 28
Ali Sarshogh Avatar answered Oct 18 '22 12:10

Ali Sarshogh