0

i'm trying to get the value of the element option:

<div id="decorazioni_agg">Decorazioni aggiuntive:<br>
        <select id="decorazioni" name="decorazioni">
            <option class="option" value="smarties">Smarties</option>
            <option class="option" value="scaglie">Scaglette di
                            cioccolato</option>
            <option class="option" value="cheerios">Cheerios</option>
            <option class="option" value="chocopops">Choco 
                            Pops</option>
        </select><br>

        <input class="button" name="aggiungi" type="button" value="Aggiungi 
                    decorazione" onClick="add_decoration(decorazioni.value)">
    </div>

And this is the function add_decoration(obj):

function add_decoration(tipo)
{
if(tipo == 'smarties')
    add_smarties();
else
    add_something(tipo);
}

Now, this is working both with Chrome and IE8 but not with Firefox 3.5; the firefox error console says:

decorazioni is not defined

How can i do without using a bunch of switch so i can keep my code clean? Thanks in advance

2 Answers 2

0
onclick="var elem = document.getElementById('decorazioni'); add_decoration(elem.options[elem.selectedIndex].value);"

However, it would be better to use proper event registration instead of inline events. Here's a jQuery example; to make it work give the button an id:

$('#buttonid').on('click', function() {
    add_decoration($('#decorazioni').val());
});
0

Do not bind event handlers in HTML.

<input class="button" id="aggiungi" name="aggiungi" type="button" value="Aggiungi decorazione" />

document.getElementById('aggiungi').onclick= function () {
    add_decoration(document.getElementById('decorazioni').value);
};
3
  • Thank you, there is no way of doing this binding event handlers in HTML and without using jquery?I don't get the sense of that error. I king "have" to use event handlers in HTML.
    – stilatore
    May 10, 2012 at 15:08
  • the code i posted is native javascript, though it can be done in jquery if you prefer (see ThiefMaster's answer)
    – jbabey
    May 10, 2012 at 15:23
  • and for the reason why: Separation of Concerns
    – jbabey
    May 10, 2012 at 15:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.