繁体   English   中英

如果克隆的选择具有特定值,则使输入字段可见

[英]Make input field visible if cloned select has a specific value

我是JQuery的新手,也没有Java的开发经验。 我的目标是允许用户添加一个选择元素,如果他需要更多选择元素,并且他选择了特定选项以在其旁边显示另一个输入字段。 我可以进行克隆,但无法显示输入字段。 我的HTML:

<div class="right">
   <a href="#" id="addField">Add parameters</a><br>
   <label for="link[]" class="wrap"><span class="label">Parameter:</span>
      <select name="link[]" size="1" id="link">
        <option value="lang">lang</option>
        <option value="action">action</option>
        <option value="mode">mode</option>
        <option value="other">Other...</option>
      </select>
      <input type="text" name="other_link[]" style="display:none" class="params">-
      <input type="text" name="parameter[]">
      <a href="#" style="display:none;" class="remove">Remove</a><br>
    </label>
</div>

如果选择了“其他...”选项,我想使输入的类为“ params”。 到目前为止,我的JQuery:

$(function(){
  var i = 1;

  // Add a clone
  $('#addField').click(function(){
    if(i < 6){
      $(".wrap").clone().attr('class','wrap'+i).appendTo(".right");
      $(".wrap"+i).children("select").attr('id','link_'+i);
      $(".wrap"+i).children("a").attr('style','display: inline;');
      $(".wrap"+i).children("input.params").attr('id','i_wrap'+i);
    }
    i++;
    return false;
   });

   // Remove a clone
   $(document).on('click', '.remove', function(e){
    $(this).parent().remove();
    i--;
   });

   // Make the input visible
   $("select").change(function(){
     parentID = $(this).parent().attr('class');
     if ($(this).val() === 'other'){ 
       $('.i_'+parentID).show();   
     } else {
       $('.i_'+parentID).hide(); 
     }
   });
});

我的目标是将onchange绑定到每个选择元素,但到目前为止,没有元素响应...

的jsfiddle

我会考虑以下更改:

function additionalField() {
    parentID = $(this).parent().attr('class');
    if ($(this).val() === 'other') {
      $(this).parent().find('input.params').show();
    } else {
      $(this).parent().find('input.params').hide();
    }
  }

// Make the input visible
$(document).off("change", 'select', additionalField);
$(document).on("change", 'select', additionalField);

另一种方法是更改​​您的功能:

$("select").change(function(){

TO:

$(document).on('change', "select", function(){ parentID = $(this).parent().find('.params'); if ($(this).val() === 'other'){ parentID.show(); } else { parentID.hide(); } });

Noobed的答案不正确。 所有“参数”字段将显示是否已将一个设置为另一个。

您想获得相对于选择的输入

$(document).on("change", 'select', function() {
  if ($(this).val() === 'other') {
    $(this).next().show();
  } else {
    $(this).next().hide();
  }
});

https://jsfiddle.net/qnLembmx/3/

暂无
暂无

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

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