wowzuzz
wowzuzz

Reputation: 1388

Getting value of dropdown

Trying to get a value from a dropdown to fire a console.log('test') upon finding the value, but its not working.

        if ($("select[name=type_lvl] option:selected").val() == 'FOREIG') {
            console.log('test');
            $("tr#countries").show();
    }

When I inspect it, it looks like this.

<option label="Foreign" value="FOREIG">Foreign</option>

Here is the dropdown in the code.

{html_options name="type_lvl" options=$category}

I've tried both foreign and FOREIG, both don't work.

EDIT//

Another question..why is it when I set my code to this

{html_options name="type_lvl" options=$category selected=""}

In the DOM it doesn't select, what I select on my browser. It just stays with the original option being selected on preload. This is the primary problem here. My selected parameter on this tag doesn't switch over when I select a different option.

Output markup follows for the {html_options} from up above.

<select name="type_lvl">
<option label="Select your category" value="" selected="selected">Select your category</option>
<option label="Exhibition/Workshop/Clinic/Testing" value="EXHIBI">Exhibition/Workshop/Clinic/Testing</option>
<option label="Invitational Meet" value="INVITA">Invitational Meet</option>
<option label="Local Meet" value="LOCAL">Local Meet</option>
<option label="Regional Meet" value="REGION">Regional Meet</option>
<option label="Sectional" value="SECTION">Sectional</option>
<option label="State Meet" value="STATE">State Meet</option>
<option label="Foreign" value="FOREIG">Foreign</option>
<option label="NC" value="NCATA">NC</option>
<option label="No Charge" value="COMP">No Charge</option>
</select>

Upvotes: 0

Views: 232

Answers (2)

wowzuzz
wowzuzz

Reputation: 1388

Managed to figure this one out.

The problem is I was thinking the selected="" attribute on the dropdown was everytime I selected an option. That is incorrect. It is only for preloading an option..not selecting. So I modified my jquery.

    $("select[name=type_lvl]").change(function () {
        if ($(this).val() == 'FOREIG') {
            console.log('test');
            $("tr#countries").show();
        }
    });

Now it works. The option selected attribute would not work because it is for preloaded options.

Using this code would not work because .val listens for a preloaded value as well. This is where I was confused. If this somehow ou

if ($("select[name=type_lvl]").val() == 'FOREIG') {
        console.log('test');
        $("tr#countries").show();
}

Upvotes: 0

Evan Davis
Evan Davis

Reputation: 36592

Try removing option:selected from your selector. $(select).val() will return the selected value.

Upvotes: 1

Related Questions