Pavillin
Pavillin

Reputation: 43

Add required attribute based on selected <select> value

I have a form with a <select> with two options and an <input>. By default the <input> isn't required to submit the form. When the selected option from <select> has a value of pizza I want to add the required attribute to the <input>. I also want it removed if the user switches to the other <select> option.

$(function() {
  var paymentType = $("#paymentType option:selected").val();
  if (paymentType == 'pizza') {
    $("firstName").prop('required', true);
  } else {
    $("firstName").prop('required', false);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <select id="paymentType" name="paymentType" required>
    <option value="" hidden>Select Payment Type</option>
    <option value="pizza">Pizza</option>
    <option value="highFive">High Five</option>
  </select>
  <input type="text" id="firstName" name="firstName" placeholder="First Name">
  <input type="submit">
</form>

Upvotes: 2

Views: 1749

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370839

You need to give the select a change handler, and also, to use the proper selector for firstName (put # in front to select the id):

$("#paymentType").on('change', function() {
  const paymentType = this.value;
  if (paymentType == 'pizza') {
    $("#firstName").prop('required', true);
  } else {
    $("#firstName").prop('required', false);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <select id="paymentType" name="paymentType" required>
    <option value="" hidden>Select Payment Type</option>
    <option value="pizza">Pizza</option>
    <option value="highFive">High Five</option>
  </select>
  <input type="text" id="firstName" name="firstName" placeholder="First Name">
  <input type="submit">
</form>

Upvotes: 2

Related Questions