Jason
Jason

Reputation: 11363

Pass drop down list value to jquery in Grails

I'm revamping a registration form, and am looking to use jQuery to simplify the form.

Users to the site can be either Teachers, Donors or both. Teachers have fields that Donors don't need, and vice versa. So, rather than stuffing a form with all the fields and confusing international users by asking their teaching grade level, I've implemented a drop down list so that the user can select their role and the unique required fields come into view via the append() method.

This is the form I've built thus far:

<g:formRemote name="register" url="[controller:'user', action:'register']" onSuccess="showFields()">
    <dl>
        <dt>User name</dt>
        <dd><g:textField name="username" value ="${user?.username }"/></dd>

        <dt>Password</dt>
        <dd><g:passwordField name="password" value = "${user?.password }"/></dd>

        <dt>Repeat Password</dt>
        <dd><g:passwordField name="passwordRepeat" value = "${user?.passwordRepeat }" /></dd>

        <dt>Account Type</dt>
        <dd>
            <g:select name="role" from="${['Teacher', 'Donor', 'Both'] }"/>
        </dd>
    </dl>



    <input type="submit" value="Register" />
</g:formRemote>

and the script is

<script type="text/javascript">
    $('#role').change(function(){
        var user = $('#role option:selected').text();

        alert(user);

        if (user == 'Teacher'){

        } else if (user == 'Donor'){

        } else {

        }

    });
</script>

Using firebug, I've verified that the select list has the id role, but the function is not firing off. In fact, its completely ignored, no matter what selection I make.

Why is this happening?

Upvotes: 0

Views: 1470

Answers (2)

Simon Edstr&#246;m
Simon Edstr&#246;m

Reputation: 6619

The problem is that the script is executed Before the DOM has loaded. So when you trying to bind the eventhandler the element don't exist.

So what you have to do is to wrap the complete function inside the document ready event, which will try to bind the change eventhandler after the complete DOM have been loaded.

$(document).ready(function (){
    $('#role').change(function(){
        var user = $('#role option:selected').text();

        alert(user);

        if (user == 'Teacher'){

        } else if (user == 'Donor'){

        } else {

        }
    });
});

Or you can simply add the script at bottom of your page. It's not recommended but FYI...

Upvotes: 3

Mathew Thompson
Mathew Thompson

Reputation: 56429

You need to do:

$("[name='role']").change(function () {

You are selecting on an id property using #name, using the above code you're selecting elements that have the name attribute of role.

Upvotes: 1

Related Questions