简体   繁体   中英

Add parameters to url with onSubmit using a Javascript function

I want to add html parameters to the url with onsubmit. I have 2 forms(1 GET, 1 POST), want to use 1 button to submit them both(Using the POST form button) When the submit button is pressed use onSubmit to call a javascript function, where parameters are "appended" to the url.

I was thinking about doing something like this:

function onSubmitForm() {
    url = "localhost:8080/test/index.php?Title=document.getElementsByName('title')[0].value";
    //I don't know how to actually call the url.
}

EDIT

I got what I wanted: Appending form input value to action url as path

First, you have to concatenate the string's static and dynamic parts. Then, you can redirect.

function onSubmitForm() {
  window.location = "localhost:8080/test/index.php?Title=" + 
    document.querySelector('title').textContent;
}

NOTES:

  • Only form fields have a .value property. If you are trying to get the text within an element, you can use .textContent .
  • .getElementsByName() scans the entire document and makes a collection of all the matching elements. That's wasteful when you know you want only the first one and, in the case of <title> , there is only ever going to be one of those in a document anyway. Use .querySelector() to locate just the first matching element.

ES6

NOTES :

  • Don't forget to use Babel for converting your code in ES5.

I purpose to you this solution :

 function onSubmitForm() { window.location = `localhost:8080/test/index.php? Title=${document.querySelector('title').textContent}` } 

This way of doing with backtick is even simpler than in ES5, let me explain, before we had to concatenate with the sign + ourVariable + the continuation of our string of character.

Here we have more of that. And we can write on several lines as well. Then ${} is used to pass a variable inside

Documentation if you want : Literal template string

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