在jQuery中选择另一个选择框时,如何在选择框中显示逗号分隔值

How to display comma separated values in a select box when another select box is selected in jQuery

提问人:TBC 提问时间:5/9/2023 最后编辑:Mark BaijensTBC 更新时间:5/9/2023 访问量:44

问:

我在下面有一个类似的东西,当选择这个选择框时,dataprice 中的值入到输入文本框中,selectbox

$('.selectProduct1').on('change', function() {
  $('.regularPrice1')
    .val(
      $(this).find(':selected').data('price1')
    );

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="form-control select selectProduct1" name="university1" id="university1">

  <option>Select </option>


  <option data-price1="123" data-price2="c1,c2,c3,c4" value="Test 1">Test 1</option>
  <option data-price1="456" data-price2="c1,c2,c3,c4" value="test 2">Test 2</option>


</select>

<input type="number" name="fee1" id="fee1" value="" class="form-control regularPrice1">

这很好用,现在我希望选择选项中的逗号分隔值显示在另一个选项中,这可能吗?提前致谢selectbox

JavaScript HTML jQuery 选择 输入

评论


答:

0赞 Mitali Patel 5/9/2023 #1

$('#university1').on('change', function() {
      $('#fee1').val($("#university1 option:selected").data('price1'));
      var Price2val=$("#university1 option:selected").data('price2');
      var arr = Price2val.split(',');
      $('#selectProduct2').html('<option seleted disabled>select</option>');
      jQuery.each(arr, function(index, item) {
        $('#selectProduct2').append('<option value="'+item+'">'+item+'</option>');
      });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="form-control select selectProduct1" name="university1" id="university1">
  <option selected disabled>Select </option>
  <option data-price1="123" data-price2="c1,c2,c3,c4" value="Test 1">Test 1</option>
  <option data-price1="456" data-price2="c1,c2,c3,c4,c5" value="test 2">Test 2</option>
</select>
<input type="number" name="fee1" id="fee1" value="" class="form-control regularPrice1">
<select class="form-control select selectProduct2" name="selectProduct2" id="selectProduct2">
   <option selected disabled>Select </option>
</select>

请试试此代码。

评论

0赞 TBC 5/9/2023
我想要的是,data-price2 中的逗号分隔值显示在另一个选择框中
0赞 Mitali Patel 5/9/2023
@TBC请再次检查我有更改代码