开发者

how to get form elements values in javascript and create a url with thoese values

开发者 https://www.devze.com 2023-04-08 12:05 出处:网络
For example I have a form: <form name=\'myfor开发者_Go百科m\' id=\'myformid\'> <input type=\'text\' name=\'name\' id=\'name\'>

For example I have a form:

<form name='myfor开发者_Go百科m' id='myformid'>

  <input type='text' name='name' id='name'>
  <input type='text' name='color' id='color'>
  <input type='text' name='made' id='made'>

  <input type='submit' name='submit'>

</form>

Now I want to call a javascript function on above form submit. This function will get all form elements values and create a URL to redirect.

For example:

example.com/search.php?name=toyota&color=white&made=abc

How can I create this JS function?

Thanks


function getValues(){
  var form = document.getElementById('myformid');
  var url  = 'example.com/search.php?';

  for(var i=0; i<form.elements.length; i++) {
     var element = form.elements[i];
     //url += (i>0 ? '&' : '') + element.name + '=' + element.value;
     //UPDATE
     url += (i>0 ? '&' : '') + encodeURIComponent(element.name) + '=' + encodeURIComponent(element.value);
  }
  return url;
}


With the MochiKit library you could use:

http://mochi.github.com/mochikit/doc/html/MochiKit/DOM.html#fn-formcontents

Source here:

https://github.com/mochi/mochikit/blob/master/MochiKit/DOM.js#L45

This along with the 'querystring' function from the same library:

http://mochi.github.com/mochikit/doc/html/MochiKit/Base.html#fn-querystring

https://github.com/mochi/mochikit/blob/master/MochiKit/Base.js#L1184

And you can have a simple solution:

window.location.href = 'example.com/search.php?' + queryString(formContents(getElement('myformid')))


I know you want a javascript function, but this way maybe better if you want to send your request after submit:

<form name='myform' action='search.php' method='get'>
  <input type='text' name='name' />
  <input type='text' name='color' />
  <input type='text' name='made' />
  <input type='submit' />
</form>


<script>

function myFunction() {
    var name=document.myform.name.value;
    var color=document.myform.color.value;
    var made=document.myform.made.value;

    alert('example.com/search.php?name='+name+'&color='+color+'&made='+made);

}

</script>

<form name='myform' id='myformid' onSubmit='javascript:myFunction()'>

  <input type='text' name='name' id='name'>
  <input type='text' name='color' id='color'>
  <input type='text' name='made' id='made'>

  <input type='submit' name='submit'>

</form>
0

精彩评论

暂无评论...
验证码 换一张
取 消