1

I want the same result without using the onchange attribute. Some ideas?

Here's the HTML:

<select onchange="filtro(this)" id="tipo" name="noticia/conteudo/tipo">
    <option  value="Layout1">Layout1</option>
    <option value="Layout2">Layout2</option>
    <option value="Layout3">Layout3</option>
    <option value="Layout4">Layout4</option>
    <option value="Layout5">Layout5</option> 
</select>

Here is the JS:

function filtro(a) {
    var x = (a.value || a.options[a.selectedIndex].value);
    alert(x);
    if (x == "Layout4"){
        alert('test4');
    } 
}
Jaak Kütt
  • 2,566
  • 4
  • 31
  • 39
user1309015
  • 89
  • 4
  • 10

3 Answers3

2

You can add an event listener to avoid having the onchange attribute.

HTML:

<select id="tipo" name="noticia/conteudo/tipo">
    <option value="Layout1">Layout1</option>
    <option value="Layout2">Layout2</option>
    <option value="Layout3">Layout3</option>
    <option value="Layout4">Layout4</option>
    <option value="Layout5">Layout5</option> 
</select>

JavaScript:

function filtro(a) {
    var x = (a.value || a.options[a.selectedIndex].value);
    alert(x);
    if (x == "Layout4"){
        alert('test4');
    } 
}

var sel = document.getElementById('tipo');
sel.addEventListener('change', function() { filtro(sel) }, false);

JSFiddle: http://jsfiddle.net/jeffshaver/HfmWV/7/

Jeff Shaver
  • 3,315
  • 18
  • 19
1

you can do it on easy way

var e = document.getElementById("tipo");
var tipoValue = e.options[e.selectedIndex].value;

Would make tipoValue be value of selected option. In case that you would like to get text you can do it with:

var e = document.getElementById("tipo");
var tipoText = e.options[e.selectedIndex].text;

In general my suggestion is to consider introduction of some javascript library, such as jQuery

vaske
  • 9,332
  • 11
  • 50
  • 69
0

You could do this only in js without attribute

document.getElementById("id").onchange=function(){ ... };
Nikolay Osaulenko
  • 1,462
  • 1
  • 12
  • 21