Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

javascript - Clear checkboxes after form submitted

I have an HTML form with a button and some checkboxes. The values of the checkboxes are passed to the next page via GET parameters. The target of the form submission is a blank page.

<form id="myForm" method="get" action="launch.php" target="_blank">
<input type="submit">Launch</input>
<input type="checkbox" class="checkbox" name="reset" /> Reset
<input type="checkbox" class="checkbox" name="erase" /> Erase
</form>

The checkboxes allow the user to reset and/or erase files prior to launching the web app. Since they are "dangerous", I wish to uncheck them automatically after the use launches the app. This is to help prevent the user from accidentally erasing or resetting their files twice in a row.

I added an onClick action to the button that unchecks the boxes using jQuery. However, they get unchecked before the form is submitted, and therefore the values of the boxes aren't included in the GET.

<input type="submit" onClick="uncheckBoxes();" />
...
<script>
function uncheckBoxes() {
    $(".checkbox").prop("checked", false);
}
</script>

I think I want to do one of two things. Either:

  • Use the $("#myForm").submit() function to uncheck the boxes, then open a new window. However, I'd have to write code to construct the URL, which is not very scalable (what if I want to add a new checkbox?) and error-prone. Or,
  • Somehow hook into the normal form-submission process and execute the uncheckBoxes function after the new page/tab has opened. Since the page/tab with the form on it remains open, I can still run additional JS code.

What are some solutions to this?

question from:https://stackoverflow.com/questions/65855961/clear-checkboxes-after-form-submitted

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

$('#submit-button').click(function() {
  var url = "launch.php?";
  $('input[type="checkbox"]').each(function() {
    url = url + this.name + "=" + this.checked + "&"
    this.checked = false;
  });
  url = url.slice(0, -1)
  console.log(url);
  //wondow.open(url, '_blank');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<label>Option 1</label><input name="option1" type="checkbox">
<br>
<label>Option 2</label><input name="option2" type="checkbox">

<button id="submit-button">Submit</button>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...