开发者

How to apply list filters on a dropdown lists

  <table>
  <tr>
  <td>
  <select class="dropdown" id="a">
  <option value="">Select answer</option>
  <option value="1" >Yes</option>
  <option value="2">No</option>
  <option value="3">N.A.</option>
  </select>
  </td>
  <td>
  <select class="dropdown" id="b">
  <option val开发者_开发知识库ue="">Select answer</option>
  <option value="1" >Yes</option>
  <option value="2">No</option>
  <option value="3">N.A.</option>
  </select>
  </td>
  </tr>
  </table>

Here is my jquery code..

$('#a').live('change',function()
{
Data=$(this).find("option:selected").text();
if(Data == "Yes")
{
    $('#b').find("option[value='1']").show();
    $('#b').find("option[value='2']").hide();
    $('#b').find("option[value='3']").hide();
}

if(Data == "No")
{
    $('#b').find("option[value='3']").hide();
    $('#b').find("option[value='1']").show();
    $('#b').find("option[value='2']").hide();
}

if(Data == "N.A.")
{
    $('#b').find("option[value='1']").hide();
    $('#b').find("option[value='2']").hide();
    $('#b').find("option[value='3']").show();
}
});

My requirement is to display only selected items in the first dropdown...


The other answers are right, you've typoed "Dat" instead of "Data". I would suggest something like:

  var optionStates = {
    'Yes': '1',
    'No': '1',
    'N.A.': '3'
  };

  Data=$(this).find("option:selected").text();

  $('#b')
      .find("option[value='" + optionStates[Data] + "']")
        .show()
        .siblings(':not([value=""])')
          .hide();
  });

Which cuts down on the data repetition massively, and I think makes it easier to see what's going on. You can control which option is shown by changing the value in the optionState's definition. It currently only supports showing one item, as per your example, but extending it to allow multiple items wouldn't be a massive stretch. (On the point of typo's, I suspect you want 'No': '1' to actually be 'No: '2'.

At the very least you should leverage chaining and store the reference to the dropdown's children, instead of doing a .find() every time.

Example here: jsbin example


You've assigned your variable called Dat and are then checking it's value using if(Data == "Yes")

It'd probably be easier not to assign variable at all in this case, by using a switch statement

$('#a').live('change',function()
{
switch($(this).find("option:selected").text()) {
  case "Yes":
    $('#b').find("option[value='1']").show();
    $('#b').find("option[value='2']").hide();
    $('#b').find("option[value='3']").hide();
    break;

  case "No":
    $('#b').find("option[value='3']").hide();
    $('#b').find("option[value='1']").show();
    $('#b').find("option[value='2']").hide();
    break;

  case "N.A.":
    $('#b').find("option[value='1']").hide();
    $('#b').find("option[value='2']").hide();
    $('#b').find("option[value='3']").show();
}
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜