Jaison Brooks
Jaison Brooks

Reputation: 5826

Issues getting values from multiple <select>/<option>

Im having issues with the following code. Im simply trying to get the values from whatever is selected from my layout_select2 options.

Currently when selection multi_select and then a option from layout_select2 i end up with the first value from layout_select1 due to the way i load the url. I need a suggestion on how to fix this or reference either of my <select> object's

See Demo

Html

<select id='multi_select' name='multi_select'>
    <option value='bing.com'>Bing.com</option>
    <option value='Google.com'>Google.com</option>
</select>
<select name='layout_select' id='layout_select1'>
    <option value='/images/search?q=windowsphone'>Windows Phone - Images</option>
    <option value='/search?q=android'>Android - Search</option>
</select>
<select name='layout_select2' id='layout_select2'>
    <option value='/search?q=Windows'>Windows - Images</option>
    <option value='/images/search?q=Robots'>Robots - Search</option>
</select>
<input type='button' id='button' value='Click Me' />

JavaScript

$(document).ready(function () {

$('#button').click(function () {
    var url = 'http://www.' + $('#multi_select').val() + $('#layout_select1').val();
    window.location = url;
});

$('#layout_select1').show();
$('#layout_select2').hide();

$('#multi_select').change(function () {
    if ($('#multi_select option:selected').text() == "Bing.com") {
        $('#layout_select1').fadeIn('slow');
    }
    if ($('#multi_select option:selected').text() == "Google.com") {
        $('#layout_select1').hide();
        $('#layout_select2').fadeIn('slow');

    } else {
        $('#layout_select1').fadeOut('slow');
    }
   });

  });

Upvotes: 0

Views: 257

Answers (1)

Divey
Divey

Reputation: 1719

You can filter the layout_select elements to use the value of the visible select like this:

$('#layout_select1, #layout_select2').filter(':visible').val();

When you combine this with a couple tweaks to your fiddle, it works pretty well:

$(document).ready(function () {
    $('#button').click(function () {
        var url = 'http://www.' + $('#multi_select').val() + $('#layout_select1, #layout_select2').filter(':visible').val();
        window.location = url;
    });

    $('#layout_select1').show();
    $('#layout_select2').hide();

    $('#multi_select').change(function () {
        if ($('#multi_select option:selected').text() == "Bing.com") {
            $('#layout_select1').fadeIn('slow');
            $('#layout_select2').hide();
        } else {
            $('#layout_select2').fadeIn('slow');
            $('#layout_select1').hide();
        }
    });
});

Upvotes: 2

Related Questions