Will
Will

Reputation: 389

JQM Get a value from a form option

I have some basic HTML ie;

    <select id="list1">
        <option value="1">Item1</option>
        <option value="2" selected="selected" >Item2</option>
    </select>
    <select id="list2">
        <option value="3">Item3</option>
        <option value="4">Item4</option>
    </select>

By default I have the #list2 hidden and shown upon a change #List1 to option value 2 as such...

    $('#list2').hide();

    $('#list1').on('change', function () {
     if ($(this).val() == '2') {
      $('#list2').parent('div').hide();
     } else {
       $('#list2').parent('div').show();
    }
    });

What I am wondering, is how do I SHOW list 2 if the dynamically SELECTED value is "2" on page load. ie not after an event, but before one.

Thanks in advance for any help/advice. What I am wondering, is how can I

Upvotes: 2

Views: 79

Answers (3)

Will
Will

Reputation: 389

I used the following to get it to work. $('#list2').hide();

    var selVal = $("#vlist1 :selected").val() ;

     if (selVal == 2) {

     $('#list2').show();

Upvotes: 0

Gajotres
Gajotres

Reputation: 57309

Working example: http://jsfiddle.net/Gajotres/uX3NL/

Few things to notice, data-role="none" is added to second select. It will prevent jQuery mobile from showing it even if display is set to none. That's why I am removing that attribute, then showing the select and restyling it with a function selectmenu.

Javascript :

$(document).on('pagebeforeshow', '#index', function(){       
    if($('#list1').find(":selected").val() == 2) {
        $('#list2').removeAttr('data-role').show().selectmenu();
    }
});

CSS :

#list2 {
    display: none;
}

HTML :

    <div data-role="page" id="index">
        <div data-theme="a" data-role="header">
            <h3>
                First Page
            </h3>
            <a href="#second" class="ui-btn-right">Next</a>
        </div>

        <div data-role="content">
            <select id="list1">
                <option value="1">Item1</option>
                <option value="2" selected="selected">Item2</option>
            </select>
            <select id="list2" data-role="none">
                <option value="3">Item3</option>
                <option value="4">Item4</option>
            </select>
        </div>

        <div data-theme="a" data-role="footer" data-position="fixed">

        </div>
    </div>  

Upvotes: 1

tymeJV
tymeJV

Reputation: 104795

You can trigger a change event on the page load

$("#list1").trigger("change");

Upvotes: 1

Related Questions