微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Jquery选择按名称或ID删除属性

如何解决Jquery选择按名称或ID删除属性

我正在使用来自 jQuery 的 Chosen 来添加/隐藏一些基于先前输入的表单数据。 谢谢。

基于

$("#otherField2").chosen()
$("#seeAnotherField2").chosen()

// This way I can hide all options if nothing is chosen

$("#seeAnotherField2").change(
  function() {
    if ($(this).val() == "nothing") {
      $('#otherFieldDiv2').show();
      $('#otherField2').attr('required','');
      $('#otherField2').attr('data-error','This field is required.');
    } else {
      $('#otherFieldDiv2').hide();
      $('#otherField2').removeAttr('required');
      $('#otherField2').removeAttr('data-error');
    }
  });
$("#seeAnotherField2").trigger("change");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js" ></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.css"  />

<div class="form-group" id="otherFieldDiv3">
  <label for="otherField3">Sev</label>
  <select class="form-control" id="otherField2">
    <option value="nor" id="1">nor</option>
    <option value="sev" id="2">Sev</option>
    <option value="min" id="3">Min</option>
  </select>
</div>

Hide only option1 from this:

<div class="form-group">
  <label for="seeAnotherField2">Options</label>
  <select class="form-control" id="seeAnotherField2">
    <option value="nothing">nothing</option>
    <option value="option1">Option1</option>
    <option value="option2">Option2</option>
  </select>
</div>

解决方法

试试这个:

$("#seeAnotherField2").change(function() {
  if ($(this).val() == "nothing") {
    $("#otherField2 option[value='nor']").hide();
    $("#otherField2 option[value='sev']").attr('selected','selected');
  }else{
   $("#otherField2 option[value='nor']").show();
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group" id="otherFieldDiv3">
  <label for="otherField3">Sev</label>
  <select class="form-control" id="otherField2">
    <option value="nor" id="1">Nor</option>
    <option value="sev" id="2">Sev</option>
    <option value="min" id="3">Min</option>
  </select>
</div>

Hide only option1 from this:

<div class="form-group">
  <label for="seeAnotherField2">Options</label>
  <select class="form-control" id="seeAnotherField2">
    <option value="nothing">Nothing</option>
    <option value="option1">Option1</option>
    <option value="option2">Option2</option>
  </select>
</div>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。