Coder Perfect

How do I pass parameters to an html select’s onChange event?

Problem

I’m new to both JavaScript and jQuery. On onChange, I want to show one combobox-A, which is an HTML choose> with its selected id and contents ().

How do I pass the entire combobox with its select id, as well as additional arguments, when the onChange event fires?

Asked by Gendaful

Solution #1

On the OnChange event, the above example returns the selected value of the combo box.

Answered by Piyush Mattoo

Solution #2

Another technique, which might be useful in some instances, is to directly feed the value of the selected option /> to the function, as shown below:

Answered by Cazuma Nii Cavalcanti

Solution #3

In jQuery, here’s how to do it:

<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>

It’s also worth noting that Javascript and jQuery are not the same thing. Although jQuery is acceptable JavaScript code, it is not the same as all JavaScript. You should look up the differences and make sure you are using the appropriate one.

Answered by aiham

Solution #4

<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>

Answered by RobertKim

Solution #5

I found @Piyush’s response to be helpful, and to add to it, if you make a select programmatically, there is an important approach to get this behavior that may not be evident. Assume you have a function and want to add a new select:

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

It’s possible that natural behavior is to say

newSelect.onchange = changeitem;

However, because this does not allow you to specify the argument sent in, you may instead do the following:

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

You can also change the parameter. The argument you’ll get to your onchange function if you do it the first manner will be browser dependant. The second method appears to be cross-browser compatible.

Answered by Michael Plautz

Post is based on https://stackoverflow.com/questions/5024056/how-to-pass-parameters-on-onchange-of-html-select