简体   繁体   中英

How do I clear a value stored in a form.submit function

The issue is when I attempt to resubmit a form without refreshing the page the event handler for the form submission retains the value for the previous submission.

The form contains a select element that is populated with options from an API. The selected option is used to make a request URL and get data from the API. When the form is submitted a second time without refreshing the form. Submit event handler constructs a URL with the previous value and then it constructs a URL with the newly selected value. I have tried to a reset on the form which does reset the select element to its initial state but it does not clear the previously selected value from the submit event handler.

<form id="myform">
  <label for="input">Select dog breed!<label>
  <select class="breeds"></select>
  <input type="submit" value="Enter">
</form>
let $select = $(".breeds");

$select.append($(`<option>select breed</option>`))

for (var i=0; i<=breeds.length; i++){
  $select.append($(`<option></option>`).text(breeds[i]).html(breeds[i]))
}

$('.breeds').on('change', function(){
  console.log('on change running')
  let breed = $(".breeds :selected").text()
  console.log(`breed in on change: ${breed}`)
  watchForm(breed) 
})

function watchForm(breed) {
  console.log(`watchForm running`)
  console.log(`breed in watchform is: ${breed}`) //here breed logs as the value for first submission and then the second submission

  $('form').submit(event => {
    console.log(`breed in form submit is ${breed}`)
    event.preventDefault();
    //console.log(`num is ${num}`)
    getDogImage(breed);
    $('#myform').get(0).reset()
  });
}

Jquery selector can return one or more element, so it returns an array.

Since reset() is a Javascript function and we are forcefully using it in jquery, it requires a specific element to perform reset action.

$('#myform')[0].reset()

Best and simple solution ever Use trigger()

$('#myform').trigger("reset");

You're good to go!!

You can use something like that. $('myform').val('');

使用vanilla Javascript是最简单和最简单的一种,因为id在HTML文档中是唯一的。

document.getElementById("myForm").reset();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM