简体   繁体   中英

Get option value text instead of value using JavaScript for select field

I had a select field on a page like below:

<select name="billing_state" id="id_billing_state">
    <option value="AL">Alabama</option>
    <option value="AK">Alaska</option>
    <option value="AS">American Samoa</option>
    <option value="AZ">Arizona</option>
    <option value="AR">Arkansas</option>
    <option value="CA">California</option>
    <option value="CO">Colorado</option>
    <option value="CT">Connecticut</option>
    <option value="DE">Delaware</option>
    <option value="DC">District of Columbia</option>
    <option value="FL">Florida</option>
    <option value="GA">Georgia</option>
    <option value="GU">Guam</option>
</select>

<input type="checkbox" name="shipping_information" id="id_shipping_information" />

So when when we clicked on checkbox with id id_shipping_information , I should get the Option text like Florida, Georgia etc., instead of option values like CT,DE etc.,like below

$('input#id_shipping_information').click(function(){
    if ($('input#id_shipping_information').is(':checked'))
    { 
        var bill =  $('#id_billing_state').val();
        console.log(bill+'>>>>>>>>>>');
    }
});

In the above JavaScript code we will get the value of choice fields as AL, AK, AS, etc., but can we able to get them as Alabama, Alaska, American Samoa etc., ?

Use text() instead of val() and target the option

$('#id_shipping_information').click(function(){
    if ( this.checked ) { 
      var bill =  $('#id_billing_state option:selected').text();
      console.log(bill+'>>>>>>>>>>');
    }
});

the more intuitive way would be to just change the values of the options to what you want ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM