Bharath Kumar Reddy
Bharath Kumar Reddy

Reputation: 53

select dropdown value always pointing to 0 index

I'm writing a simple JavaScript code to retrieve the value of selected item, it's always pointing to 0 index and giving me the first value.

HTML Code

<html>
    <head>
    <title>Simple Extension</title>
    </head>
    <body>
        Select a web page
        <select id="mySelect">
            <option value="uc4_scriptGuide">UC4 Script Guide</option>
            <option value="uc4_docu">UC4 Documentation</option>
            <option value="allSec">Pay Role</option>
            <option value="myte">Time Sheets</option>
        </select>
        <button type="button" id="myBtn">Go There</button>
    <script src="background.js"></script>
    </body>
</html>

JavaScript Code

document.getElementById("myBtn").addEventListener("click", myFunction());

function myFunction() {
    var item = document.getElementById("mySelect").selectedIndex;
    console.log(document.getElementsByTagName("option")[item].value);
}

The output is always uc4_scriptGuide i.e. the first value.

Upvotes: 0

Views: 958

Answers (1)

Gautam
Gautam

Reputation: 825

Well error is with this line

document.getElementById("myBtn").addEventListener("click", myFunction());

replace it with below line.

document.getElementById("myBtn").addEventListener("click", myFunction);

the function reference should me mentioned on event listener but you are calling it from there.

Upvotes: 2

Related Questions