Reputation: 1871
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.
Upvotes: 0
Views: 276
Reputation: 817128
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.
Upvotes: 3
Reputation: 6965
$("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.
Upvotes: 1
Reputation: 4325
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());
});
Upvotes: 1
Reputation: 461
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".
Upvotes: 1