Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable a button when an HTML select option is selected and vice-versa

I'm trying to do something. I have this in a while loop:

<tr>
<th>Order status</th>
<td>
<form class='update-status'>
<select name='status_id'class='status'>
<option selected='selected'>Order received</option>
<option value='2'>Processing</option>
</select>
<button type='submit' title='Click to update the status of this order' disabled>Update order status</button>
</form>
</td>
</tr>

What I need is that the button gets enabled only if the option with value 2 is selected and vice-versa! I think I need to use something like $('select').on('change', function() but I don't know how to get the value of the option.
I'm trying with:

$('.status').change(function()
{
    if ($('select option:selected').val() === 2)
    {
        $(this).closest('tr').find( 'button' ).prop("enabled", true);
    }
});

But this is not working. I apreciate any help, thanks!

like image 785
Dyan Avatar asked Sep 11 '25 21:09

Dyan


1 Answers

Try utilizing .next()

Description: Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.

$(".status").change(function() {
  var button = $(this).next("button");
  if (this.value == "2") {
    button.prop("disabled", false);
  } else {
    button.prop("disabled", true)
  } 
});

$(".status").change(function(e) {
  e.preventDefault();
  e.stopPropagation();
  var button = $(this).next("button");
  if (this.value == "2") {
    button.prop("disabled", false);       
  } else {
    button.prop("disabled", true)
  };
  console.log(button.prop("disabled"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
      <th>Order status</th>
      <td>
        <form class='update-status'>
          <select name='status_id' class='status'>
            <option selected='selected'>Order received</option>
            <option value='2'>Processing</option>
          </select>
          <button title='Click to update the status of this order' disabled>Update order status</button>
        </form>
      </td>
    </tr>
  </tbody>
</table>
like image 74
guest271314 Avatar answered Sep 14 '25 10:09

guest271314