adg
adg

Reputation: 35

Javascript Forms Select Selectedindex

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

JSFiddle Nota Worka.

Upvotes: 0

Views: 2552

Answers (3)

Naftali
Naftali

Reputation: 146300

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');
        }
    })
})

Upvotes: 1

Gary Green
Gary Green

Reputation: 22395

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/

Upvotes: 0

Jason
Jason

Reputation: 52523

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.

Upvotes: 0

Related Questions