user1489083
user1489083

Reputation: 29

onclick Select's option tag strangly trigger even without click on option

I have a code like this:

    <select id='chapter'>
        <option onclick="return my_function('1')" value='1'>1</option>
        <option onclick="return my_function('2')" value='2'>2</option>
        <option onclick="return my_function('3')" value='3'>1</option>
    </select>

When user click on select it trigger one of options onclick events. I really don't know what to do. Here is my code in work and see problem(check select tags):

http://animup.net/manga/claymore/c127/#1

Upvotes: 0

Views: 90

Answers (2)

Sterling Archer
Sterling Archer

Reputation: 22395

Like mayabelle said, use the onchange event. However, I don't like inline JS. It's bad practice and ugly. Use an MVC approach and separate your code, using addEventListener to attach an event and function (can be predefined, can be anonymous)

<select id='chapter'>
    <option value='1'>1</option>
    <option value='2'>2</option>
    <option value='3'>1</option>
</select>

var x = document.getElementById("chapter");
x.addEventListener("change",function() {
    var value = my_function(this.options[this.selectedIndex].value);
),false);

Upvotes: 1

mayabelle
mayabelle

Reputation: 10014

I think what you want is an onChange event.

Try this:

<select id='chapter' onChange="SelectOption(this)">
    <option value='1'>1</option>
    <option value='2'>2</option>
    <option value='3'>1</option>
</select>

function SelectOption(sel) {
    var selectedValue = sel.value;
    // Do something with selectedValue here, e.g. call function1 if value 1 is selected
}

Upvotes: 1

Related Questions