Jquery动态更新“其他”选项中的选项 [英] Jquery dynamically update "other" option in select
问题描述
我正在开发一个项目,该项目将使用大量选择菜单输入各种数据。我想直接在select中包含一个'other'选项,它会触发一个简单的对话框并允许用户输入一个自定义值(如果适用),类似于以下javascript代码:
I'm working on a project that will be using a lot of select menus to enter various data. I'd like to include an 'other' option directly in the select that will trigger a simple dialog and allow users to enter a custom value (where appropriate) similar to the following javascript code:
<script type="text/javascript" language="javascript">
function chkother(fld,len,idx) {
if ((idx+1)==len) {
other=prompt("Please indicate 'other' value:");
fld.options[idx].value=other;
fld.options[idx].text=other;
}
}
</script>
适用于选择:
<select onchange="chkother(this,this.options.length,this.options.selectedIndex)" name="example" id="example" class="formSelect">
<option value=""></option>
<option value="yes">yes</option>
<option value="no">no</option>
<option value="other">other</option>
</select>
并显示一个提示,用于更新用户文本选项。
And brings up a prompt that will update the option with the users text.
我想用jquery做类似的事情,所以我可以看一下扩展功能并学习一些jquery,但是我开始时遇到了麻烦。
I'd like to do something similar using jquery so I can look at extending the functionality and learning a bit of jquery, but I'm having trouble getting started.
推荐答案
这将帮助您入门。这将为页面上的任何选择添加功能,向选择附加一个新值(如果发生错误,则保留其他值)。
This will get you started. This will add the functionality to any select on the page, appending a new value to the select (and leaving other still available in case a mistake has been made).
$(function() {
$('select').change( function() {
var value = $(this).val();
if (!value || value == '') {
var other = prompt( "Please indicate other value:" );
if (!other) return false;
$(this).append('<option value="'
+ other
+ '" selected="selected">'
+ other
+ '</option>');
}
});
});
这篇关于Jquery动态更新“其他”选项中的选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!