Jquery 检查下拉选择的值是否包含特定字符

Jquery check dropdown selected value contains particular characters

我想在页面加载时检查下拉列表中的选定值。如果选择的选项有一个文本 'abc' 那么它会禁用另一个文本字段。如果在下面的示例中选择了选项 1 或 2,那么它将禁用文本。无论所选值如何,我下面的代码都会禁用文本字段。

<select id="marks" name="studentmarks">
  <option value="1">abc-test</option>
  <option value="2">abc-test2</option>
  <option value="3">cde-test3</option>
</select>

我试过这个,但它有时会禁用即使所选选项没有文本 'abc'

$( window ).load(function() {
                                             
    ($('select[name="studentmarks"]').find("option:contains('abc')")){
                                        
             $( "#score" ).prop( "disabled", true );
                                     }
                           });

你可以这样试试,希望对你有帮助。

<!DOCTYPE html>
<html>
<head></head>
<body>
    <select id="marks" name="studentmarks">
        <option value="1">abc-test</option>
        <option value="2">abc-test2</option>
        <option value="3">cde-test3</option>
    </select>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
    jQuery(function($){
    $('select[name="studentmarks"]').on('change', function(){
        var selected_option = $('#marks option:selected');
        console.log(selected_option.text());
        if (selected_option.text().indexOf("abc") >= 0){
            alert('abc');
        }
        else{
            alert('None abc');
        }
    });
});
</script>
</html>

一种可能的方法如下:

jQuery(function($) {
  // here we select the select element via its 'id',
  // and chain the on() method, to use the anonymous
  // function as the event-handler for the 'change'
  // event:
  $('#marks').on('change', function() {

    // here we select the element with the id of 'score': We update that property using an
    // assessment:
    $('#score')
        // we update its 'disabled' property via the prop()
        // method (the first argument is the name of the
        // property we wish to update, when used as a setter,
        // as it is here) and we use $(this) to get the current
        // element upon which the event was fired:
        .prop('disabled', $(this)
        // we find the option that was/is selected:
        .find('option:selected')
        // we retrieve its text (instead of its value),
        // since your checks revolve around the text:
        .text()
        // text() returns a String, which we use along with
        // String.prototype.startsWith() - which returns a
        // Boolean true/false - based on the argument provided.
        // if the string does start with 'abc' the assessment
        // then returns true and the '#score' element is disabled,
        // if the string does not start with 'abc' the
        // assessment returns false, and the disabled property
        // is set to false, so the element is enabled:
        .startsWith('abc'));
  // here we trigger the change event, so that the '#score'
  // element is enabled/disabled appropriately on page-load:
  }).change();
});
*,
 ::before,
 ::after {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

label {
  display: block;
}

input[disabled] {
  background: repeating-linear-gradient(45deg, transparent, transparent 5px, #ccca 5px, #ccca 10px);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body>
  <label>Student marks:
    <select id="marks" name="studentmarks">
      <option value="1">abc-test</option>
      <option value="2">abc-test2</option>
      <option value="3">cde-test3</option>
    </select>
  </label>
  <label>Score: 
    <input id="score" type="text">
  </label>
</body>

JS Fiddle demo.

当然,这也可能是普通的 - 虽然相对现代 - 原生 JavaScript:

// listening for the DOMContentLoaded event to fire on the window, in order
// to delay running the contained JavaScript until after the page's content
// is available:
window.addEventListener('DOMContentLoaded', () => {

  // using document.querySelector() to find the first element matching
  // the supplied selector (this returns one element or null, so in
  // production do sanity-check and prepare for error-handling):
  const select = document.querySelector('#marks'),
    // we create a new Event, in order that we can use it later:
    changeEvent = new Event('change');

  // we use EventTarget.addEventListener() to bind the anonymous function
  // as the event-handler for the 'change' event:
  select.addEventListener('change', function(event) {

    // here we cache variables to be used, first we find the 'score'
    // element:
    const score = document.querySelector('#score'),
      // we retrieve the element upon which the event was bound:
      changed = event.currentTarget,
      // we find the selected option, using spread syntax to 
      // convert the changed.options NodeList into an Array:
      selectedOption = [...changed.options]
      // we use Array.prototype.filter() to filter that Array:
      .filter(
        // using an Arrow function passing in the current <option>
        // of the Array of <option> elements over which we're
        // iterating into the function. We test each <option> to
        // see if its 'selected' property is true (though
        // truthy values will also pass with the way this is written):
        (opt) => opt.selected
        // we use Array.prototype.shift() to retrieve the first Array-
        // element from the Array:
      ).shift(),
      // we retrieve that <option> element's text:
      optionText = selectedOption.text;

    // here we set the disabled property of the 'score' element,
    // again using String.prototype.startsWith() to obtain a
    // Boolean value indicating whether string does start with
    // 'abc' (true) or does not start with 'abc' (false):
    score.disabled = optionText.startsWith('abc');
  });

  // here we use EventTarget.dispatchEvent() to trigger the created
  // change Event on the <select> element in order to have the
  // 'score' element appropriately disabled, or enabled, according
  // to its initial state:
  select.dispatchEvent(changeEvent);
});
*,
 ::before,
 ::after {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

label {
  display: block;
}

input[disabled] {
  background: repeating-linear-gradient(45deg, transparent, transparent 5px, #ccca 5px, #ccca 10px);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body>
  <label>Student marks:
    <select id="marks" name="studentmarks">
      <option value="1">abc-test</option>
      <option value="2">abc-test2</option>
      <option value="3">cde-test3</option>
    </select>
  </label>
  <label>Score: 
    <input id="score" type="text">
  </label>
</body>

JS Fiddle demo.

参考文献: