【问题标题】:jQuery to auto create textbox when choosing 'other' from drop down?jQuery从下拉列表中选择“其他”时自动创建文本框?
【发布时间】:2011-04-27 17:20:48
【问题描述】:

我有一个完整的国家/地区的下拉菜单。当他们选择加拿大或美国时,一个单独的下拉列表会自动填充州/省。如果他们选择任何其他国家/地区,则第二个下拉列表将填充“其他”且值为空白。

我的问题是,如果他们选择了另一个国家并且第二个下拉列表填充了“其他”,我如何在第二个下拉列表下自动显示一个文本框,并将其动态绑定到“其他”值。换句话说,“其他”的值会在输入时动态填充文本框的值。因此,当提交表单时,第二个下拉列表的值会与他们在文本框中输入的内容一起发布。

谁能帮忙?

这是我用来绑定国家和州/省下拉列表的 jQuery 插件: https://github.com/adam12/jquery-state-select

<html>
  <head>
    <title>jQuery State Select Plugin Test</title>
    <script type="text/javascript" src="jquery-latest.pack.js"></script>
    <script type="text/javascript" src="jquery.selectboxes.pack.js"></script>
    <script type="text/javascript" src="jquery.stateselect.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
      $('#country').linkToStates('#province');
    });
    </script>
  </head>
  <body>
    <form>
      <p>
        <label>Province/State</label><br />
        <select name="province" id="province">
          <option value="">Please select a country</option>
        </select>
      </p>
      <p>
        <label>Country</label><br />
        <select name="country" id="country">
          <option>Please select</option>
          <option value="Canada">Canada</option>
          <option value="United States">United States</option>
        </select>
      </p>
    </form>
  </body>

部分插件代码:

 $.fn.extend({
        linkToStates: function(state_select_id) {
      $(this).change(function() {
        var country = $(this).attr('value');
        $(state_select_id).removeOption(/.*/);
        switch (country) {
          case 'Canada':
            $(state_select_id).addOption(canadian_provinces, false);
            break;
          case 'United States':
            $(state_select_id).addOption(us_states, false);
            break;
          default:
            $(state_select_id).addOption({ '' : 'Other'}, false);
            break;
        }
      });
    }
  });

【问题讨论】:

  • 我建议你发布一些代码。

标签: javascript jquery forms


【解决方案1】:

你应该有一个单独的 Div:

<div id="hiddendiv">
    <input type="text" id="othertextbox" />
</div>

然后:

$(window).load(function()
{
    $("#hiddendiv").hide();
});

$("#ComboBox").change(function()
{
    if($("#ComboBox option:selected").text() == "Other")
    {
        $("#hiddendiv").show();
    }
});

$("#othertextbox").change(function()
{
    $("#ComboBox").val($("#othertextbox").text());
});

我还没有测试过这段代码,所以你可能需要调整它。

【讨论】:

  • 但是#othertextbox 中输入的值如何自动填充 $("#ComboBox option:selected").val()?
  • 它不起作用,因为它试图选择一个不存在的值。 “其他”选项具有空白值。如何填充该值?顺便说一句,我试过 $("#othertextbox").val() 但没有运气。
  • 嗯....如果这不起作用,我认为这不可能...在数据发送到的页面中,您可以检查组合框是否设置为“其他”,如果是,则从文本框中获取值。
  • 太好了,成功了。感谢 TheAdamGaskins 的所有帮助! $("#ComboBox").find(":selected").val($(this).val());
【解决方案2】:
【解决方案3】:

我实际上解决了一个与此非常相似的问题,并最终编写了一个 jQuery 插件 (jQuery.otherDropdown) 来收集选择下拉菜单的“其他”响应。它在GitHubnpm 上。我将分解我的方法,以便您可以按照自己的方式实施。

在我看来,这个想法是 jQuery 的完美用例。

基本组件

聆听您的“其他”选项何时被选中

在选择输入上添加.change() 事件绑定。

$('select').change( function() {
    if(this.value === 'other') {
        // Your logic here to for when/how to prompt for user input
    }
});

监听用户输入

如果您选择文本输入而不是提示(这可能是更好的用户体验),请监听 blur 事件

// listen to a text area
$('input').blur( function() {
    if(this.value !== '') {
        // Logic to add the new option to the select
    }
});

// or bring up a prompt dialog
var value=prompt("Please indicate 'other' value:");
if(this.value !== '') {
    // Logic to add the new option to the select
}

添加新选项

无论您选择如何提示用户输入值,添加它就像通过 jQuery 创建元素并附加它一样简单。最后,您可能想要关注价值,这可以通过.val() 完成

var $option = $('<option value="' + value + '">' + value + '</option>');
$('select').append($option);
$('select').val(value);

示例

所有这些想法都包含在这个插件中,并且可能是一个很好的例子,您可以根据需要进行使用和重用。你可以看到它在工作here

/**
 * @name jquery.otherdropdown
 * @description A small jQuery plugin to support a text area when selecting an 'Other' option in a dropdown
 * @version 1.0.2
 * @author Jonathan Stassen <jstassen.com>
 * @see https://github.com/TheBox193/jquery.otherdropdown
 */
$.fn.otherDropdown = function(options) {
    var $this = this;
    // Allow a different name/value to trigger, default to 'other'
    var opts = $.extend({}, {value: 'other'}, options);
    opts.name_lower = opts.value.toLowerCase();
    opts.name_upper = opts.value.charAt(0).toUpperCase() + opts.value.slice(1);
    opts.placeholder = opts.placeholder || opts.name_upper;

    // Bind to all change events
    $this.change( function(ev){

        // Swap in the text area if our 'other' option was chosen
        if (this.value === opts.name_lower || this.value === opts.name_upper) {
            $this.hide().after( $textInput );
            $textInput.focus();
        }
    });

    // Prepare our text input
    var $textInput = $('<input type="text" class="otherdropdown" placeholder="' + opts.placeholder + '" />');

    // Allow custom classes on the text input
    if (opts.classes) {
        $textInput.addClass(opts.classes);
    }

    // Bind to blur to swap back to select dropdown
    $textInput.blur( function(ev) {
        var value = this.value;
        this.value = '';
        this.remove();
        $this.show();

        if (value === '' || value === opts.name_lower || value === opts.name_upper) {
            return;
        }

        // If something was typed, create a new option with that value
        var $searchedOption = $this.children('[value="' + value + '"]');

        // If value doesn't exist, added it.
        if ( $searchedOption.length < 1 ) {
            var $option = $('<option value="' + value + '">' + value + '</option>');
            $this.append($option);
        }

        // Focus the value
        $this.val( value );
    });
};

【讨论】:

    【解决方案4】:
    <html>
        <head>
             <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function ()
            {
                $("#ddlSelect").change(function ()
                {                                   
                    $("#divTxtGroup").empty();             
                    var selectedVal = this.value;
                    if (selectedVal == "Other") {
                            var newTextBoxDiv1 = $(document.createElement('div')).attr("id", 'divOther');
                            newTextBoxDiv1.after().html('<input type="text" id="txtOther">');
                            newTextBoxDiv1.appendTo("#divTxtGroup");                        
                    }
                });
            });
        </script>
        </head>
        <body>
             Countries
             <select id="ddlSelect" name="ddlSelect">
             <option value="-----Select-----">-----Select-----</option>
             <option value="US">US</option>
             <option value="Canada">Canada</option>
             <option value="Other">Other</option>
             </select>
             <div id='divTxtGroup'></div>
        </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-17
      • 2014-09-17
      • 2018-07-30
      • 2018-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多