[javascript] How to pass parameters on onChange of html select

I am a novice at JavaScript and jQuery. I want to show one combobox-A, which is an HTML <select> with its selected id and contents at the other place on onChange().

How can I pass the complete combobox with its select id, and how can I pass other parameters on fire of the onChange event?

This question is related to javascript jquery html combobox onchange

The answer is


Simply:

_x000D_
_x000D_
function retrieve(){
alert(document.getElementById('SMS_recipient').options[document.getElementById('SMS_recipient').selectedIndex].text);
}
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
< script type = "text/javascript> {

function retrieve_other() {
  alert(myForm.SMS_recipient.options[document.getElementById('SMS_recipient').selectedIndex].text);
}

function retrieve() {
  alert(document.getElementById('SMS_recipient').options[document.getElementById('SMS_recipient').selectedIndex].text);
}
} 
</script>
_x000D_
<HTML>
<BODY>
  <p>RETRIEVING TEXT IN OPTION OF SELECT </p>
  <form name="myForm" action="">
    <P>Select:
      <select id="SMS_recipient">
        <options value='+15121234567'>Andrew</option>
          <options value='+15121234568'>Klaus</option>
      </select>
    </p>
    <p>
      <!-- Note: Despite the script engine complaining about it the code works!-->
      <input type="button" onclick="retrieve()" value="Try it" />
      <input type="button" onclick="retrieve_other()" value="Try Form" />
    </p>
  </form>
</HTML>
</BODY>
_x000D_
_x000D_
_x000D_

Output: Klaus or Andrew depending on what the selectedIndex is. If you are after the value just replace .text with value. However if it is just the value you are after (not the text in the option) then use document.getElementById('SMS_recipient').value


Another approach wich can be handy in some situations, is passing the value of the selected <option /> directly to the function like this:

_x000D_
_x000D_
function myFunction(chosen) {_x000D_
  console.log(chosen);_x000D_
}
_x000D_
<select onChange="myFunction(this.options[this.selectedIndex].value)">_x000D_
  <option value="1">Text 1</option>_x000D_
  <option value="2">Text 2</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_


This worked for me onchange = setLocation($(this).val())

Here.

    @Html.DropDownList("Demo", 
new SelectList(ViewBag.locs, "Value", "Text"), 
new { Class = "ddlStyle", onchange = "setLocation($(this).val())" });

JavaScript Solution

<select id="comboA">
<option value="">Select combo</option>
<option value="Value1">Text1</option>
<option value="Value2">Text2</option>
<option value="Value3">Text3</option>
</select>
<script>
 document.getElementById("comboA").onchange = function(){
    var value = document.getElementById("comboA").value;
 };
</script>

or

<script>
 document.getElementById("comboA").onchange = function(evt){
    var value = evt.target.value;
 };
</script>

or

<script>
 document.getElementById("comboA").onchange = handleChange;

 function handleChange(evt){
    var value = evt.target.value;
 };
</script>

You can try bellow code

<select onchange="myfunction($(this).val())" id="myId">
    </select>

this code once i write for just explain onChange event of select you can save this code as html and see output it works.and easy to understand for you.

<html>
    <head>
        <title>Register</title>
    </head>
    <body>
    <script>
        function show(){
            var option = document.getElementById("category").value;
            if(option == "Student")
                  {
                        document.getElementById("enroll1").style.display="block";
                  }
            if(option == "Parents")
                  {
                        document.getElementById("enroll1").style.display="none";
                  }
            if(option == "Guardians")
                  {
                        document.getElementById("enroll1").style.display="none";
                  }
        }
    </script>
            <form action="#" method="post">
                <table>
                    <tr>
                        <td><label>Name </label></td>
                        <td><input type="text" id="name" size=20 maxlength=20 value=""></td>
                    </tr>
                    <tr style="display:block;" id="enroll1">
                        <td><label>Enrollment No. </label></td>
                        <td><input type="number" id="enroll" style="display:block;" size=20 maxlength=12 value=""></td>
                    </tr>
                    <tr>
                        <td><label>Email </label></td>
                        <td><input type="email" id="emailadd" size=20 maxlength=25 value=""></td>
                    </tr>
                    <tr>
                        <td><label>Mobile No. </label></td>
                        <td><input type="number" id="mobile" size=20 maxlength=10 value=""></td>
                    </tr>
                    <tr>
                        <td><label>Address</label></td>
                        <td><textarea rows="2" cols="20"></textarea></td>
                    </tr>
                    <tr >
                        <td><label>Category</label></td>
                        <td><select id="category" onchange="show()">    <!--onchange show methos is call-->
                                <option value="Student">Student</option>
                                <option value="Parents">Parents</option>
                                <option value="Guardians">Guardians</option>
                            </select>
                        </td>
                    </tr>
                </table><br/>
            <input type="submit" value="Sign Up">
        </form>
    </body>
</html>

This is helped for me.

For select:

$('select_tags').on('change', function() {
    alert( $(this).find(":selected").val() );
});

For radio/checkbox:

$('radio_tags').on('change', function() {
    alert( $(this).find(":checked").val() );
});

Just in case someone is looking for a React solution without having to download addition dependancies you could write:

<select onChange={this.changed(this)}>
   <option value="Apple">Apple</option>
   <option value="Android">Android</option>                
</select>

changed(){
  return e => {
    console.log(e.target.value)
  }
}

Make sure to bind the changed() function in the constructor like:

this.changed = this.changed.bind(this);

For how to do it in jQuery:

<select id="yourid">
<option value="Value 1">Text 1</option>
<option value="Value 2">Text 2</option>
</select>

<script src="jquery.js"></script>
<script>
$('#yourid').change(function() {
  alert('The option with value ' + $(this).val() + ' and text ' + $(this).text() + ' was selected.');
});
</script>

You should also know that Javascript and jQuery are not identical. jQuery is valid JavaScript code, but not all JavaScript is jQuery. You should look up the differences and make sure you are using the appropriate one.


I found @Piyush's answer helpful, and just to add to it, if you programatically create a select, then there is an important way to get this behavior that may not be obvious. Let's say you have a function and you create a new select:

var changeitem = function (sel) {
  console.log(sel.selectedIndex);
}
var newSelect = document.createElement('select');
newSelect.id = 'newselect';

The normal behavior may be to say

newSelect.onchange = changeitem;

But this does not really allow you to specify that argument passed in, so instead you may do this:

newSelect.setAttribute('onchange', 'changeitem(this)');

And you are able to set the parameter. If you do it the first way, then the argument you'll get to your onchange function will be browser dependent. The second way seems to work cross-browser just fine.


jQuery solution

How do I get the text value of a selected option

Select elements typically have two values that you want to access.
First there's the value to be sent to the server, which is easy:

$( "#myselect" ).val();
// => 1

The second is the text value of the select.
For example, using the following select box:

<select id="myselect">
  <option value="1">Mr</option>
  <option value="2">Mrs</option>
  <option value="3">Ms</option>
  <option value="4">Dr</option>
  <option value="5">Prof</option>
</select>

If you wanted to get the string "Mr" if the first option was selected (instead of just "1") you would do that in the following way:

$( "#myselect option:selected" ).text();
// => "Mr"  

See also


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to combobox

How to set combobox default value? PHP code to get selected text of a combo box How to add items to a combobox in a form in excel VBA? How add items(Text & Value) to ComboBox & read them in SelectedIndexChanged (SelectedValue = null) Get Selected value of a Combobox jQuery "on create" event for dynamically-created elements How to get the selected item of a combo box to a string variable in c# HTML combo box with option to type an entry twitter bootstrap autocomplete dropdown / combobox with Knockoutjs C# winforms combobox dynamic autocomplete

Examples related to onchange

Why can't I change my input value in React even with the onChange listener React Checkbox not sending onChange Set Label Text with JQuery android on Text Change Listener Jquery select change not firing onchange event on input type=range is not triggering in firefox while dragging select2 onchange event only works once Dropdown using javascript onchange How to fire a change event on a HTMLSelectElement if the new value is the same as the old? jQuery - on change input text