Question

Ok so I am trying to write a script that will show and hide items based on a users selection. I was able to figure out how to do this with a radio group but when it comes to a select item I just cant figure it out. Anyone have an idea what I'm doing wrong here?

my jQuery

 $('select#contact').change(function() {
    var isPhone = $('#phone').is(':selected');
    var isEmail = $('#email').is(':selected');
    $('#cell').toggleClass('req', isPhone);

    if ( isPhone === true ) {
        $('#phoneNum').animate({'height':'show'}, 500);
    } else if ( isPhone === false ){
        $('#phoneNum').animate({'height':'hide'}, 200);
    }
    $('#Remail').toggleClass('req', isEmail);

    if ( isEmail === true ) {
        $('#emailAdd').animate({'height':'show'}, 500);
    } else if ( isEmail === false ){
        $('#emailAdd').animate({'height':'hide'}, 200);
    }
});

my HTML

<p>
     <label for="contact">How Would You Like Us To Contact You?</label> 
     <select id="contact" name="contact" class="req">
        <option></option>
        <option id="phone">By Phone</option>
        <option id="email">By Email</option>
     </select>
</p>
<p id="phoneNum">
    <label for="cell">Best Phone Number</label>
    <input id="cell" name="cell" type="tel" placeholder="e.g. 555-555-5555" class=""/>
</p>
<p id="emailAdd">
    <label for="Remail">Email</label>
    <input id="Remail" name="Remail" placeholder="something@something.com" type="email" class=""/>
</p>
Was it helpful?

Solution

Figured it out:

    $('select#contact').change(function() {
    var isPhone = $(this).find("option:selected").is('#phone');
    var isEmail = $(this).find("option:selected").is('#email');
    $('#cell').toggleClass('req', isPhone);

    if ( isPhone === true ) {
        $('#phoneNum').animate({'height':'show'}, 500);
    } else if ( isPhone === false ){
        $('#phoneNum').animate({'height':'hide'}, 200);
    }
    $('#Remail').toggleClass('req', isEmail);

    if ( isEmail === true ) {
        $('#emailAdd').animate({'height':'show'}, 500);
    } else if ( isEmail === false ){
        $('#emailAdd').animate({'height':'hide'}, 200);
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top