1

I have a html element on which I should do multiple things on if condition. My present code:

<div>
  <label for="myInput">Add Number</label>
  <input id="myInput" type="number" required>
</div>

<script>
  if (someCondition) {
    $("#myInput").removeAttr("required");
    $("#myInput").prop("disabled", true);
    $("#myInput").val() = "";
  }
</script>

My question is, is it possible to condense the jquery code? If yes then how?

user001
  • 425
  • 4
  • 21
  • 1
    The term you're looking for is "chaining" or, specifically, [jquery chaining](https://stackoverflow.com/questions/7475336/how-does-jquery-chaining-work). Found a small note on it in learn.jquery.com: https://learn.jquery.com/using-jquery-core/working-with-selections/#chaining – freedomn-m Mar 05 '21 at 08:08

1 Answers1

3

If you want to do it in a single line then you can do

$("#myInput").removeAttr("required").prop("disabled", true).val("");

Also $("#myInput").val() = ""; is not valid, it should be $("#myInput").val("");

Also as Roko pointed out it should be disabled and not diabled

Demo

if (true) {
  $("#myInput").removeAttr("required").prop("disabled", true).val("");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <label for="myInput">Add Number</label>
  <input id="myInput" type="number" required value="2">
</div>
freedomn-m
  • 27,664
  • 8
  • 35
  • 57
Carsten Løvbo Andersen
  • 26,637
  • 10
  • 47
  • 77