2

I haven't found this question anywhere so I'm posting it here.

I have a bunch of select tags that are partially named using VBScript. I want to be able to get the name of a select tag that was called from the onchange event in javascript.

here is the code.

<select name="optWeeks_<%=intLineCnt%>" id = "name" onchange="changeWeek()">
       <option value=""></option>
          <option value="1">1</option>
          <option value="2">2</option>
</select>


<SCRIPT LANGUAGE = "JavaScript">

function changeWeek(){
var chosenoption = document.getElementsByTagName("select").name

}
</SCRIPT>

The select name - "optWeeks_<%=intLineCnt%>" is optWeeks prefixed with a number

I would like to know if I can get each name of the select tag that is called? Ex. optWeeks_1, optWeeks_2 etc.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
codingNightmares
  • 313
  • 2
  • 9
  • 19

4 Answers4

2

Change the call to:

...  onchange="changeWeek(this);">

Then you can simply;

function changeWeek(caller) {
   var chosenoption = caller.name;
}
Alex K.
  • 171,639
  • 30
  • 264
  • 288
1

You need to get a reference to the element. this will be one in your event handler function. You can pass it to the function you are calling from there:

onchange="var element = this; changeWeek(element)">

I included the variable assignment above for clarity, you don't need it:

onchange="changeWeek(this)">

You can then get the name from the name property on that object:

function changeWeek(element) {
    var name = element.name;

I'd generally recommend binding your event handlers with JS rather than HTML, not using HTML 3.2 though:

<select name="optWeeks_<%=intLineCnt%>" id="name">
    <!-- … -->
</select>

<script>
var select = document.getElementById('name');
select.addEventListener('change', changeWeek);
function changeWeek(evt) {
    var name = this.name;
}
</script>
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

Or you can use:

onchange="changeWeek(this.name)"

Or: (keep in mind that the changeWeek function will have to already have been defined)

    <script>
      var select = document.getElementById('name');
      select.onchange = changeWeek;
    </script>

addEventListener vs onclick -- for information between adding event listeners and the method I provided above.

Community
  • 1
  • 1
0

An alternative JavaScript way:

var selects = document.getElementsByTagName('select');

for(var i in selects)
{
    selects[i].onchange = function changeWeek(e) {console.log(e.target.name);}
}

HTML:

<select name="test">
    <option>One</option>
    <option>Two</option>
</select>
<select name="test2">
    <option>One</option>
    <option>Two</option>
</select>

Fiddle:

http://jsfiddle.net/bddwW/

Alex W
  • 37,233
  • 13
  • 109
  • 109