最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - onSubmit makes unwanted url change - Stack Overflow

programmeradmin1浏览0评论

I'm using ReactJS. I have a form, and "onSubmit" of that form I want to get the contents of the form and then redirect to another page. This sort of works except this changes my url which I don't want. What I want it to redirect to is:

localhost:3000/somewebsite

but instead it bees:

localhost:3000/somewebsite?input-form1=hello&input-form2=hi

This is what my code looks like:

<form onSubmit={this.urlSubmit} action="/somewebsite">
  <input name="input-form1" placeholder="Enter URL" />
  <Form.Control name="input-form2" as="select" placeholder="Select language">
    <option value="XX">Select Language</option>
  </Form.Control>
  <button className="submit" type="submit">Submit</button>
</form>

I'm using ReactJS. I have a form, and "onSubmit" of that form I want to get the contents of the form and then redirect to another page. This sort of works except this changes my url which I don't want. What I want it to redirect to is:

localhost:3000/somewebsite

but instead it bees:

localhost:3000/somewebsite?input-form1=hello&input-form2=hi

This is what my code looks like:

<form onSubmit={this.urlSubmit} action="/somewebsite">
  <input name="input-form1" placeholder="Enter URL" />
  <Form.Control name="input-form2" as="select" placeholder="Select language">
    <option value="XX">Select Language</option>
  </Form.Control>
  <button className="submit" type="submit">Submit</button>
</form>
Share Improve this question edited Mar 16, 2020 at 9:07 Ken asked Mar 16, 2020 at 9:05 KenKen 1,4814 gold badges23 silver badges44 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 12

Please add event as param of urlSubmit method and add event.preventDefault(); as part of that method to avoid refresh/URL change effect on form submit.

& You don't need action="/somewebsite" as part of form

urlSubmit = (event) => {
    event.preventDefault();
    // rest of your code goes here...
}

Hope this helps.

发布评论

评论列表(0)

  1. 暂无评论