简体   繁体   中英

Is this possible with jQuery and Select options?

I have a list of countries and their area codes in a database. I am trying to auto update a text field with the countries area code when a select option is selected.

ex.

<select name="country">
    <option value="CA" code="+1">Canada</option>
    ...
</select>

<input type="text" name="phone" />

I need to pass on to the script the value CA and the users need to see Canada. Basically what I'm asking is can I create a new option code and have jQuery update the text field that I choose to it.

Is this possible to do? or is there another way I can accomplish this?

Edit: "code" is supposed to be the country's area code. So when a user selects Canada for example the text field phone gets updated with +1. I know I can just set value to +1 and then use .change() to update phone 's .val() but I need the current value to pass on to the script that processes it.

I suggest you use an HTML5 data- attribute instead of a custom attribute:

<select name="country">
    <option value="CA" data-code="+1">Canada</option>
    ...
</select>

<input type="text" name="phone" />

and then bind a handler to the change event:

$('select[name="country"]').change(function() {
    $('input[name="phone"]').val($(this).children('option:selected').data('code'));
});

or with less jQuery:

$('select[name="country"]').change(function() {
    $('input[name="phone"]').val(this.options[this.selectedIndex].getAttribute('data-code'));
});

Another option would be to have a country -> code map in JavaScript

var map = {
    'CA': '+1',
    ...
};

and then look up the code.

Be sure to assign each element an id.

var code = $('#country option:selected').attr('code');
$('#phone').val(code);

If "code" doesn't work. Use "title".

Not entirely sure what you're asking, but dos this help?

$('select[name=country]').change(function() {

    $('input[name=phone]').val($(this).find('option:selected').attr('code'));

    alert('Do something else with this: ' + $(this).val());
});
$("select[name='country']").change(function() {
    $("input[name='phone']").val($(this).find('option:selected'));
});

You can try this. It ties into the select menus change event and then gets the "code" attribute value and sets the text of the input to it.

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