1

how to let a select trigger a javascript method when the select is being populated and set to default value?

Thanks in advance

2
  • 1
    You use on change event to trigger method on change of select. Commented Sep 29, 2016 at 8:44
  • i have updated my answer please accept so that it can help others as well. Thanks in advance. Commented Sep 29, 2016 at 10:17

2 Answers 2

1

This can easily been done with the change event handler.

$('select').change(function(){
  if ($(this).val() == 'default') { 
    console.log('selected default'); 
  } else {
    $('p').text($(this).val());
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
  <option value="default"></option>
  <option value="Hello World!">Hello</option>
  <option value="Foo and Bar are common used example names">Foo</option>
</select>
<p>Please pick an option.</p>

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

1 Comment

Thank you. I used onchange="myFunction" before. But your way is to go.
0

You can use on change event to handle it .

Javacript/Jquery

function printData() {
        console.log("On change of the select box your this fuction will get call");
    }

$(document).ready (function () {

    $('select').change(function(){
                  printData();
    });
}) 

HTML

<lable>Select option.</lable>
    <select>
      <option value="1">Hi</option>
      <option value="2">Hello</option>
      <option value="3">How are you</option>
    </select>

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.