Sean R
Sean R

Reputation: 1

.options[e.selectedIndex].innerHTML Not grabbing value

I have a form with a select field with the id of to. I want to grab the selected value inside a javascript function. The first time I run this function it does not grab the selected value, but the second time I run the function it grabs the function. I have tried .text, this did not work. Thank you very much for your help.

var e = document.getElementById("to");
var str = e.options[e.selectedIndex].innerHTML;

Upvotes: 0

Views: 4573

Answers (2)

epascarello
epascarello

Reputation: 207531

So the first time you run it, are you running it before the element is rendered? If so you have to wait for document.ready or page load event.

Working example getting both text and value of a select element

HTML

<select id="foo">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
</select>
<button id="bar">Console it</button>

JavaScript

function getText() {
    var sel = document.getElementById("foo");        
    var option = sel.options[sel.selectedIndex];
    //assuming that there is always a selection
    var text = option.text;
    var value = option.value;
    console.log(text, value);
}

document.getElementById("bar").onclick = getText;

getText();

Working Example In the fiddle, you can see that it is running onload when it tries to read the value.

Upvotes: 1

ForOhFor
ForOhFor

Reputation: 796

Try putting it in the onReady function.. maybe the JS is running before the page is fully loaded? If you're using jQuery:

$(document).ready(function(){
    alert($("#to option:selected").text());
)};

Upvotes: 1

Related Questions