1

Actually I'm using Boostrap 4 and I want to reset all the inputs inside my form via JS with the function below. All text inputs are reseted correctly but the radio buttons group and checkboxes do not get deselected.

$('#new_customer')
  .find(':input')
  .not(':button, :submit, :reset, :hidden')
  .val('')
  .removeAttr('checked')
  .removeAttr('selected');
};

I know the original inputs are hidden and styles are build using ::before and ::after pseudo-elements. But in the documentation I do not see a possible way to reset those controls. How do I achieve this?

James Douglas
  • 3,328
  • 2
  • 22
  • 43
alexventuraio
  • 8,126
  • 2
  • 30
  • 35

2 Answers2

2

Use .prop() instead

$('#new_customer')
  .find(':input')
  .not(':button, :submit, :reset, :hidden')
  .val('')
  .prop('checked', false)
  .prop('selected', false);
};
Simon K
  • 1,503
  • 1
  • 8
  • 10
  • Please explain why the OP should use `.prop()` instead, and accompany it with a working example. – James Douglas Jul 31 '18 at 16:48
  • People who view this answer are less likely to be helped by it if you just have a link and some incomplete code. – James Douglas Jul 31 '18 at 16:49
  • James, when I see a question I can answer, I immediately try to get in with the first answer to get the points before someone else does. (Don't you find it annoying mid answer that someone pips you to it?) If the OP can't read the docs I provided or needs some clarification I am then happy to help – Simon K Jul 31 '18 at 16:51
  • yes, aside from the closing bracket on the last line, the code works great to clear custom bootstrap 4 input controls. – user3232196 Jan 19 '23 at 20:35
0

Your code:

$('#new_customer')
  .find(':input')
  .not(':button, :submit, :reset, :hidden')
  .val('')
  .removeAttr('checked')
  .removeAttr('selected');
};

Has an unexpected }; on the end which will be throwing an error.

If you remove it, your code works fine.

$('#new_customer')
  .find(':input')
  .not(':button, :submit, :reset, :hidden')
  .val('')
  .removeAttr('checked')
  .removeAttr('selected');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="new_customer">
  <input type="text">
  <input type="text" value="text">
  <input type="checkbox">
  <input type="checkbox" checked>
  <input type="radio">
  <input type="radio" checked>
</div>

The usual format for jQuery code is as following:

$('#new_customer').find(':input').not(':button, :submit, :reset, :hidden').val('').removeAttr('checked').removeAttr('selected');
James Douglas
  • 3,328
  • 2
  • 22
  • 43