如何基于单选按钮选项触发不同的功能

How to trigger different functions based on a radio button option?

本文关键字:功能 何基于 单选按钮 选项      更新时间:2023-09-26

我在尝试触发基于单选按钮选项的两个不同功能时遇到麻烦。

我有一个自动完成字段,但源必须通过单选按钮选项设置。我能做什么?

到目前为止,我已经这样做了:

var autocompleteOne = [
  "Item 01",
  "Item 02",
  "Item 03",
  "Item 04",
  "Item 05"  
];
var autocompleteTwo = [
  "Item 01.2",
  "Item 02.2",
  "Item 03.2",
  "Item 04.2",
  "Item 05.2"  
];
$('#options').blur(function(){
  if(document.getElementById("optionA").attr(checked, true{
    $("#autocompleteCaseOne").autocomplete({												  source: autocompleteOne
    });
  }
  if(document.getElementById("optionB").attr(checked, true{
    $("#autocompleteCaseTwo").autocomplete({												  source: autocompleteTwo
    });
  }	
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div>
  <label>Choosing option</label>
    <input type="radio" name="options" value="yes" id="optionA" />Yes
    <input type="radio" name="options" value="no" id="optionB" />no
</div>
<div>
  <label>autocomplete function result</label>
  <input type="text" id="options" name="autocompleteOptions">
</div>

谢谢

基本正确,但自动补全功能不正确。以下是正确的完整代码:

  $("input[name='options']").change(function(event) {
    if ($(this).val() == "yes") 
      $("#options").autocomplete({
          source: autocompleteOne
      });
    else if ($(this).val() == "no") 
      $("#options").autocomplete({
          source: autocompleteTwo
      });
  });

如果您打算以更改单选按钮事件为目标,您应该使用.change().click()来触发自动完成源中的更改。

比如

$("input[name='options']").change(function(event) {
  if ($(this).val() == "yes") 
    $("#options").autocomplete('option', 'source', autocompleteOne);
  else if ($(this).val() == "no") 
    $("#options").autocomplete('option', 'source', autocompleteTwo);
});