jQuery enable/disable show/hide button w/ SELECT options. Get remaining option values

后端 未结 4 1946
半阙折子戏
半阙折子戏 2021-01-23 05:05

I have a select list which is being populated using the values from a text field. I also have two buttons: an add button which adds the entered value to the select list and a re

4条回答
  •  既然无缘
    2021-01-23 05:45

    I made a heavy edit of the original question, assuming my edit is correct, here is a solution to your problem:

    XHTML:

    
    
    
    
    

    JavaScript (assumes above document structure):

    $(function(){
    
      $("#textField").keypress(function(){
    
        var val = $(this).val();
    
        if (val === '') {
          return;
        }
    
        // Clear selections
        $("#selectList option").removeAttr("selected");
    
        // Value not in select list
        if ($("#selectList option").length === 0 || $("#selectList option[value="+val+"]").length === 0) {
          $("#removeButton").hide();
          $("#addButton").show();
    
        // Value in select list
        } else {
          $("#removeButton").show();
          $("#addButton").hide();
    
          // Select it
          $("#selectList option[value="+val+"]").attr("selected", "selected");
        }
      });
    
      $("#removeButton").click(function(){
        var val = $("#textField").val();
        val !== '' && $("selectList option[value="+val+"]").remove();
      });
    
      $("#addButton").click(function(){
        var val = $("#textField").val();
        val !== '' && $("#selectList").append('');
      });
    
    });
    

提交回复
热议问题