vlad
vlad

Reputation: 855

How to choose the correct child element?

I have the next html code:

<fieldset id="q1">
  <legend>Quest 1</legend>
  <div class="a1">
    <label for="q2a1">Some text 1</label>
    <select id="q2a1" name="q2a1">
      <option value="0">0</option>
      <option value="1">1</option>
      <option value="2">2</option>
    </select>
  </div>
  <div class="a2">
    <select id="q2a2" name="q2a2">
      <option value="0">0</option>
      <option value="1">1</option>
      <option value="2">2</option>
    </select>
    <label for="q2a2">Some text 2</label>
  </div>
</fieldset>

The basic idea: the sum of the two selectors must be equal to 2.

Example: If I choose the in the first selector number 2, the second selector must be avaible the 0 only. If I choose in the first selector number 1, the second selector must must have only 1. And vice versa. As you can see the tag label can be located before and after select. I started writing code, but it stuck on choosing a necessary child. Also likely not be able to use elements by the id, because the form a very large.

js:

$('select').change(function(event) {
  var c;
  c = 3 - $(this).val();
  options = '';
  for (var i = 0; i <= c; i++) {
    options += '<option value="' + i + '">' + i + '</option>';
  }
        alert($(this).parent().parent().html());
});

Any ideas? Thanks.

Upvotes: 3

Views: 99

Answers (1)

Kobi
Kobi

Reputation: 138007

You don't have to look for the element, you can simply use .val(value), and jQuery does the hard work for you:

$('select').bind('change keyup click', function(){
   var $this = $(this);
   var $other = $this.closest('fieldset').find('select').not(this);
   var selectedValue = parseInt($this.val(), 10);
   $other.val(2 - selectedValue);
});

I've added the keyup and click events so it plays nicely with the mouse and keyboard.

Working example: http://jsfiddle.net/7TX86/1

Upvotes: 2

Related Questions