简体   繁体   English

使用jQuery和Select选项是否可能?

[英]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. 我需要将CA值传递给脚本,用户需要查看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. 基本上,我要问的是我是否可以创建一个新的选项code并让jQuery更新我选择的文本字段。

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. 因此,例如,当用户选择加拿大时,文本字段phone将更新为+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. 我知道我可以将value设置为+1,然后使用.change()更新phone.val()但是我需要当前值传递给处理它的脚本。

I suggest you use an HTML5 data- attribute instead of a custom attribute: 我建议您使用HTML5 data-属性而不是自定义属性:

<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: 然后将处理程序绑定到change事件:

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

or with less jQuery: 或使用更少的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 另一种选择是在JavaScript中有一个country -> code映射

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

and then look up the code. 然后查找代码。

Be sure to assign each element an id. 确保为每个元素分配一个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. 它绑定到选择菜单更改事件,然后获取“代码”属性值并为其输入文本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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