Xriuk
Xriuk

Reputation: 392

Stop form from sending and execute a function

This is my form:

<form id="search_form" method="get" action="" name="search_f">
  <input id="search_field" maxlength="100" name="query" type="text" value="" placeholder="cerca nel negozio">
  <input id="search_button" type="submit" value="" onClick="submit_f()">
</form>

This is "submit_f()":

function submit_f(){
  var v = document.search_f.query.value;
  var v_arr = v.split("?");
  alert(v_arr.join('\n'));
  var v_arr = v_arr[0].split("/");
  alert(v_arr.join('\n'));
  if((v_arr[0] == "http:" || v_arr[0] == "https:") && v_arr[2] == "store.steampowered.com")
    window.location.href = "/" + v_arr[3] + "/" + v_arr[4];
  else
    window.location.href = "/search/?query=" + v;
  return false;
}

What I'm trying to do is to redirect the user to different pages based on what he enters:
- If he enters words he'll be redirected to "/search/?query=words". - IF he enters an url (http://store.steampowered.com/app/202170/?asp=123) he'll be redirected (in this case) to "/app/202170".

But my code isn't working, any help?

Upvotes: 0

Views: 32

Answers (3)

dcodesmith
dcodesmith

Reputation: 9614

remove the onclick from your html

document.getElementById('search_button').onclick = function(){
    var v = document.search_f.query.value;
    var v_arr = v.split("?");
    alert(v_arr.join('\n'));
    var v_arr = v_arr[0].split("/");
    alert(v_arr.join('\n'));
    if((v_arr[0] == "http:" || v_arr[0] == "https:") && v_arr[2] == "store.steampowered.com")
       window.location.href = "/" + v_arr[3] + "/" + v_arr[4];
    else
       window.location.href = "/search/?query=" + v;
    return false;
}

Upvotes: 1

Quentin
Quentin

Reputation: 944530

You aren't returning anything from your event handler function:

onClick="submit_f()"

should be

onClick="return submit_f()"

Upvotes: 3

dkellner
dkellner

Reputation: 9986

You should give your form a

onsubmit="return false"

to avoid the default submitting behaviour. Also, your button could be type=button instead of type=submit, but that's not always enough (some browsers will still submit it), the sure way is onsubmit.

Upvotes: 1

Related Questions