0

I have been trying to get the values stored inside a data attribute called data-title, however JavaScript doesn't display the value I have stored inside it. Been trying to put the value inside alert for testing, but it doesn't work. The following is my piece of code. Thank you.

<select id='item_ID' onchange='changeValue();'>
    <option data-title="Title 1">1</option>
    <option data-title="Title 2">2</option>
    <option data-title="Title 3">3</option>
    <option data-title="Title 4">4</option>
</select>

<script type="text/javascript">

function changeValue(){

    var option=document.getElementById('item_ID');
    alert(option.getAttribute('data-title'));
}
</script>

4 Answers 4

3

The select element doesn't have a data-title attribute. The option elements do.

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

Comments

2

That's because your select element doesn't have a data-title attribute. Only the option elements have them.

Here's a working example:

var options = document.getElementsByTagName("option");
for (var i = 0; i < options.length; i++) {
    var title = options[i].getAttribute("data-title");
    alert(title);
}

http://jsfiddle.net/E49hm/

2 Comments

Sorry, don't understand what you mean. My elements have a data-title as you can see above
@Jordan I wrote <select> and <option> but without the backticks, so StackOverflow whited it out. See my updated answer
1

To retrieve the data-title value from the currently-selected option, as your select element itself is lacking that attribute:

function changeValue(){
    var select = document.getElementById('item_ID'),
        option = select.getElementsByTagName('option')[select.selectedIndex];
    alert(option.getAttribute('data-title'));
}

1 Comment

thank you very much, your answer was correct, thanks so much, will accept it in a second. Hugs
0

You want: option.value

<select id='item_ID' onchange='changeValue();'>
    <option data-title="Title 1">1</option>
    <option data-title="Title 2">2</option>
    <option data-title="Title 3">3</option>
    <option data-title="Title 4">4</option>
</select>

<script type="text/javascript">

function changeValue(){
    var option=document.getElementById('item_ID'); 
    console.log(option.value);
}
</script>

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.