Jump to content

checking forms and submiting correctly


Jocka

Recommended Posts

I made a post in the mod_rewrite forum before realizing that it's not mod_rewrite I should be using. It's JAVASCRIPT.

What I need this code to do is check for any non-empty input fields and submit (to the same page) these fields ONLY.

Example:
[code]
<html>
<head>

// JAVASCRIPT STUFF HERE (i dont' know it) //
</head>

<body>
<form name="search" method="GET" onsubmit="check_form()">
<input type="text" name="user" value=""><br>
<input type="text" name="city" value=""><br>
<input type="text" name="state" value=""><br>
<input type="submit" name="submit" value="Search">
</form>
</body>
</html>
[/code]
then it runs the code so that the url after submitting isn't like: search.php?user=&city=Dallas&state=
I just want it to say (in this case): search.php?city=Dallas

Right now i'm using another small PHP file to do this but I'd rather have it do all this on the same page.
Link to comment
https://forums.phpfreaks.com/topic/23572-checking-forms-and-submiting-correctly/
Share on other sites

Well I know I can. What I need is some code to get me started. I used form validation codes I found online but they didn't help any. Basically I wanted it to do something like this:

PHP WAY OF DOING IT:
[code]
<?php

$link = NULL; // TO SAVE QUERY INFO

foreach($_GET as $key => $value){

  if($value !== '' && $key !== 'submit'){

    if($link == NULL){

      $link .= "?" . $key . "=" . $value;

    } else {

      $link .= "&" . $key . "=" . $value;

    }

  }

}

$link = "search.php" . $link;

header("Location: $link");

?>
[/code]

Thats what I use now for the PHP file that does what I want. But I need a JAVASCRIPT version of this that does it as soon as the page is submitted.
Sure... (untested):

[code]
function check_form() {
var links = [];
for( var el in document.forms['search'].elements ){
  if( el.type == 'text' && el.value != '' el.name != 'submit'){
    links.push( el.name . '=' . el.value );
  }
}

window.location = 'search.php?' . links.join('&');

}
[/code]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.