比较选择选项

时间:2015-04-03 04:41:49

标签: jquery forms

我尝试比较两个选项的值,并根据两个选定的选项显示第三个值。我找到了this example on Stack Exchange

但似乎无法让它发挥作用。我自己的代码如下:

 $('#forest-size', '#forest-age').change(function() {
          var val =  $('#forest-size').val() + $('#forest-age').val(), 
         initial_crediting;

         switch (val) {

          case "A1" : 
              initial_crediting = "0 - 10";
              break;

          case "A2" : 
              initial_crediting = "0 - 10";
              break;

          case "B1" : 
              initial_crediting = "0 - 8";
              break;

          case "B2" : 
              initial_crediting = "10 - 18";
              break;

          case "B3" : 
              initial_crediting = "18 - 24";
              break;

          case "C1" : 
              initial_crediting = "20 - 30";
              break;

          case "C2" : 
              initial_crediting = "30 - 40";
              break;

          case "C3" : 
              initial_crediting = "40 - 50";
              break;
         }

          $('#results').text(initial_crediting);
      });
      </script>

到目前为止,我没有在#results中显示值,但是,我在控制台中看不到任何错误。任何建议都将不胜感激。

谢谢!

2 个答案:

答案 0 :(得分:1)

$('#forest-size', '#forest-age')选择器意味着#forest-size元素是#forest-age元素的子元素,或者更好地理解代码的工作方式

  $('#forest-age').find('#forest-size')

但你想在两个选择器上附加事件,所以改变

 $('#forest-size', '#forest-age').change(function() {

$('#forest-size, #forest-age').change(function() {

答案 1 :(得分:1)

请尝试以下( Demo JSFiddle ):

HTML代码

<label>Option A</label>
<select id="forest-size">
    <option value=""></option>
    <option value="A">A</option>
    <option value="B">B</option>
    <option value="C">C</option>
</select>
<br />
<label>Option B</label>
<select id="forest-age">
    <option value=""></option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>
<br />
Results: <span id="results"></span>

<强>脚本

$('#forest-size, #forest-age').change(function() {
   var val = $('#forest-size').val() + $('#forest-age').val();
   var initial_crediting = '';

    switch (val) {
    case "A1":
        initial_crediting = "0 - 10";
        break;
    case "A2":
        initial_crediting = "0 - 10";
        break;
    case "A3":
        initial_crediting = "not specified";
        break;
    case "B1":
        initial_crediting = "0 - 8";
        break;
    case "B2":
        initial_crediting = "10 - 18";
        break;
    case "B3":
        initial_crediting = "18 - 24";
        break;
    case "C1":
        initial_crediting = "20 - 30";
        break;
    case "C2":
        initial_crediting = "30 - 40";
        break;
    case "C3":
        initial_crediting = "40 - 50";
        break;
    default:
        initial_crediting = "please select both options";
    }

    $("#results").text(initial_crediting);
});