简体   繁体   中英

Using JQuery to Automatically Assign Unpicked Option in <select> tag

Newbie here. I am building a chores list app in Sinatra. Chores are only given on 2 days; Monday or Tuesday. There are only 2 options for chores: toys and dishes. If a chore has been selected on Monday I would like Tuesday to automatically select the other chore. Here is the erb:

<body>
<div class ="monday">
  <h2>Monday:</h2>
  <select class="button">
    <option value="lily">Lily</option>
    <option value="sam">Sam</option>
  </select>
  <div>
    <select id="monday_chores" class="button">
      <option value="Dishes">X</option>
      <option value="Toys">O</option>
    </select>
  </div>
</div>

<div class = "Tuesday">
  <h2>Tuesday</h2>
  <select class="button">
    <option value="lily">Lily</option>
    <option value="sam">Sam</option>
  </select>
  <div>
    <select id="tuesday_chores" class="button">
      <option value="Dishes">X</option>
      <option value="Toys">O</option>
    </select>
  </div>
</div>

<div>
  <center>
    <a href="/play"><button type=button class="start_button">Start</option>
  </center>
</div>

I would like to achieve this by using JQuery. I'm thinking something along the lines of:

$(function() {
  $('#monday_chores').on ('click', function(event){
if event == Dishes
  #tuesday_chores == Toys
else
    event == Dishes
  });
});

Thanks in advance!

This will select Toys when first select is changed to Dishes:

$(function() {
  $('#monday_chores').on ('change', function(event){
    var $this = $(this);
      if (($this).val() == 'Dishes') {
          $('#tuesday_chores').val("Toys");
      }
  });
});

尝试使用change而不是click ,并使用选定的值

$(this).val();

try this...

$(function() {
  $('#monday_chores').on ('change', function(event){
      if ($(this).val() == 'Dishes') $('#tuesday_chores').val("Toys");
        else $('#tuesday_chores').val("Dishes");   // will select the non-selected option
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM