无法使用jquery和PHP设置选择选项值

时间:2018-11-15 11:08:12

标签: php jquery jquery-chosen

我有一个问题。我需要使用jQuery在select框中将选择值设置为文本,但无法执行。

<select name="countryCode" class="chosen-select" id="countryCode" required>
  <?php foreach ($countrydata as $key => $value) {
     if ($value['con_code']=='IN') {
          $select='selected';
      }else{
          $select='';
     }
 ?>
  <option data-text="<?php echo $value['country']; ?>" value="<?php echo $value['dial_code']; ?>" <?php echo $select; ?>><?php echo $value['country']; ?></option>
 <?php } ?>
</select>

我的脚本部分在下面给出。

$('#countryCode').find(':selected').html($('#countryCode').find(':selected').attr('value')); // already changed onload   
 $('#countryCode').on('change mouseleave', function () {
       $('#countryCode option').each(function () {
           $(this).html($(this).attr('data-text'));
       });
       $('#countryCode option:selected').html($('#countryCode option:selected').attr('value'));
       $(this).blur();
   });
   $('#countryCode').on('focus', function () {
       $('#countryCode option').each(function () {
           $(this).html($(this).attr('data-text'));
       });
   });

我需要的是,当用户选择任何文本时,它将向用户显示其值。在我的代码中,不会发生这种情况。

2 个答案:

答案 0 :(得分:0)

第一:对JS进行一些优化:

$('#countryCode option:selected').html($(this).val());// already changed onload

现在,如何使用JS选择选项:

$(function() {
  var $sel = $('.chosen-select');
  $('#exists').click(function() {
    $sel.val('option3');
    console.log($sel.val());
  });
  $('#disabled').click(function() {
    $sel.val('option2');
    console.log($sel.val());
  });
  $('#noExist').click(function() {
    $sel.val('option5');
    console.log($sel.val());
  });
  $sel.on('change', function() {
    console.log($sel.val());
  });
});
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

<button id="exists">Select 3rd option</button>
<button id="disabled">Select disabled option</button>
<button id="noExist">Select inexistant option</button>
<select class="chosen-select">
  <option>option1</option>
  <option disabled>option2</option>
  <option>option3</option>
  <option selected>option4</option>
</select>
<button onclick="console.clear();">X</button>

如您所见,只能选择现有的而不是禁用的选项。

答案 1 :(得分:0)

应该是这样的:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(function(){
  $('#countryCode').on('change', function(){
    var val = $(this).val();
    $(this).find("option").each(function(){
      $(this).text($(this).attr("data-text"));
    });
    $(this).find(":selected").text(val);
  }).trigger("change");  
});
</script>
<select id="countryCode" class="chosen-select">
    <option data-text="A Text" value="A value">A Text</option>
    <option data-text="B Text" value="B value">B Text</option>
    <option data-text="C Text" value="C value" selected>C Text</option>
</select>

相关问题