使用下面的代码,我根据下拉选择显示或隐藏两个div。
我的问题是如何使div thar显示为需要文本框?

$(document).ready(function(){
    $("#europerkg").hide();
    $("#flatfee").hide();
    $('#rate').on('change', function() {
        if (this.value == '1') {
            $("#europerkg").show();
            $("#flatfee").hide();
        }

        if (this.value == '2') {
            $("#europerkg").hide();
            $("#flatfee").show();
        }

        if (this.value == '3') {
            $("#europerkg").show();
            $("#flatfee").show();
        }
    });
});


<div class="col-md-3" id="europerkg">
    <label class="form-label">&euro; / kg</label>
    <input name="europerkg" id="europerkg" type="text" class="form-control" placeholder="">
</div>
<div class="col-md-3" id="flatfee">
    <label class="form-label">Flat Fee</label>
    <input name="flatfee" id="flatfee" type="text" class="form-control" placeholder="">
</div>

最佳答案

首先,对于不同的元素,您不能具有相同的ID,此处为div标签和input标签
您使用了相同的ID,

请检查修改后的代码,在这些代码中我更改了元素的ID,并添加了所需的代码。

$(document).ready(function(){
$("#europerkg").hide();
        $("#flatfee").hide();
    $('#rate').on('change', function() {
      if ( this.value == '1')
      {
        $("#europerkg").show();
        $("#flatfee").hide();
        $("div input[id = 'europerkgtxt']").attr('required','required');
      }
      if ( this.value == '2')
      {
        $("#europerkg").hide();
        $("#flatfee").show();
       $("div input[id = 'flatfeetxt']").attr('required','required');
      }
            if ( this.value == '3')
      {
        $("#europerkg").show();
        $("#flatfee").show();
        $("div input[id = 'europerkgtxt']").attr('required','required');
        $("div input[id = 'flatfeetxt']").attr('required','required');

      }
    });
});

<div class="col-md-3" id="europerkg">
<label class="form-label">&euro; / kg</label>
<input name="europerkg" id="europerkgtxt" type="text" class="form-control" placeholder=""  >
</div>
<div class="col-md-3" id="flatfee">
<label class="form-label">Flat Fee</label>
<input name="flatfee" id="flatfeetxt" type="text" class="form-control" placeholder=""  >
</div>

10-06 04:20
查看更多