0

i have the following html snippet i need to add onchange = "namefunction(this)" to it once i replaced execute additional instructions

    <select id="test-dropdown">
        <option value="1">One</option>
        <option value="2">Two</option>
        <option value="3">Three</option>
    </select>

later

<select id="test-dropdown" onchange="namefunction(this)">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
</select>

2 Answers 2

2

here is a sample code to work with select and add a function using onchange:

<select 
    id="test-dropdown" 
    onmousedown="this.value='';" 
    onchange="selectNumber(this.value);" >
        <option value="1">One</option>
        <option value="2">Two</option>
        <option value="3">Three</option>
</select>

<script>
    function selectNumber(value) {
        alert(value);
        //add additional instructions with value
    }
</script>

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

Comments

2

You can add attribute with jQuery with simply $('#test-dropdown').attr('onchange', 'namefunction(this)');. Try it below.

$(document).ready(function() {
  $('#test-dropdown').attr('onchange', 'namefunction(this)');
});

function namefunction(el) {
  console.log(el.value);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<select id="test-dropdown">
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>

4 Comments

Thank you for your answer in the menstruation it works as indicated, when I do the test I get an error as in the following screenshothttps://prnt.sc/12gftuu
@user117732 put that whole <script> $(document)...</script> after select-box .
@user117732, $ is object from jquery and you have write code before actually loading jquery so you are getting that error. Use it in the end of your html then it will work. Or at least it should appear after <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>.
Why in the world would you add an event listener with attr?

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.