根据jquery的文本框值更改下拉选择值

change dropdown selected value based on textbox value in jquery

本文关键字:选择 根据 文本 jquery      更新时间:2023-09-26

我有一个文本框和4个选项的选择列表,如下所示…

<select id="select2" class="form-control">
                <option value="pre">Pre</option>
                <option value="rep" selected="selected">Rep</option>
                <option value="new">New</option>
                <option value="dec">Dec</option>
              </select>

和一个文本框,用户输入一些关键字和基于关键字,我想改变选定的选项在上面的选项列表

<td id="fpv_col1"  contenteditable="">decorating and repair work</td>

选择的主要值来自PHP和ajax基于用户输入所以我只想在上面的选项列表

中设置选定值

下面是我的jquery代码

$(document).on('keyup', '#fpv_col1', function(event) {
    var desc_text = $(this).text();
    $.ajax({
            url: 'php/fpv_lbyl_prediction.php',
            type: 'POST',
            data:{
                    value1:desc_text,
            },
            dataType:'text',
            success: function(data){
                $("#error_msg").fadeIn();
                $("#error_msg").html("<strong>Success!</strong> "+data);
                //$('select#select2 option').removeAttr('selected');
                //$('select#select2').find('option[value='+data+']').attr("selected",true);
                $('select#select2 option').removeAttr('selected').filter('[value='+data+']').attr('selected', true);  
            }
        });
event.preventDefault();
});

我的jquery代码工作得很好,它设置了选中的选项,但不显示选中的选项,它看到使用inspect

$(document).ready(function() {
  $('#otherCategory').keyup(function() {
    if ($(this).val() == 0) {
      $('#category').val(1);
    } else if ($(this).val() > 0) {
      $('#category').val(2);
    } else {
      $('#category').val(0);
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="category" name="category">
  <option value="0">Please select</option>
  <option value="1">Clear</option>
  <option value="2">UnClear</option>
</select>
<input type="text" id="otherCategory" name="otherCategory">