简体   繁体   中英

Javascript Forms Select Selectedindex

Having problems with the following - Not working as expected, getting JS doc errors as well.

JSFiddle Nota Worka.

try this fiddle: http://jsfiddle.net/maniator/egjF4/6/

and change the if line to:

if (document.forms['myform'].selectbox1.selectedIndex == 2)

you need the == to check values

UPDATE

Based on your comments below here is the jQuery for the same thing:

$(function(){
    $('#selectbox1').change(function(){
        if(this.selectedIndex == 2){
            $('#input1, #input2, #asterisk').css('visibility', 'visible');
            $('#input2').addClass('required');
        }
        else {
            $('input, #asterisk').css('visibility', 'hidden');
            $('#input2').removeClass('required');
        }
    })
})

you could also do this, http://jsfiddle.net/edelman/egjF4/10/

var form = document.getElementById('myform');
if (form.selectbox1.selectedIndex == 2)

this way you're caching the form in case you want to reference it later, preventing another element lookup and speeding up your code.

I believe jsfiddle runs in it's own little protective XPC bubble, so showhidebtime will not be seen as defined via an inline javascript call. Best practice is to always add events in the javascript file, not inline with the elements.

Also you need to change your form to show name="myform" in order for document.myform to work.

Try this fiddle: http://jsfiddle.net/garreh/qb6fw/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM