问题
I have this text field and button here
<input name="txtSearch" type="text" id="txtSearch" class="field" />
<input type="submit" name="btnSearch" value="" id="btnSearch" class="btn" onclick="javascript:SubmitFrm()" />
and when the user clicks on the submit button this function is suppose to run
<script type="text/javascript">
function SubmitFrm(){
var Searchtxt = document.getElementById("txtSearch").value();
window.location = "http://www.example.com/search/?Query=" + Searchtxt;
}
</script>
But nothing happens, what I expecting to happen is when the user clicks on the submit button, take the value from the search text box and redirect the user to the url + the value of the search text box...
What am I doing wrong?
回答1:
There are several issues in your code :
You are handling the
click
event of a submit button, whose default behavior is to post a request to the server and reload the page. You have to inhibit this behavior by returningfalse
from your handler:onclick="SubmitFrm(); return false;"
value
cannot be called because it is a property, not a method:var Searchtxt = document.getElementById("txtSearch").value;
The search query you are sending in the query string has to be encoded:
window.location = "http://www.mysite.com/search/?Query=" + encodeURIComponent(Searchtxt);
回答2:
Change the onclick from
onclick="javascript:SubmitFrm()"
to
onclick="SubmitFrm()"
回答3:
Just do
onclick="SubmitFrm"
The javascript:
prefix is only required for link URLs.
回答4:
Doing this fixed my issue
<script type="text/javascript">
function SubmitFrm(){
var Searchtxt = document.getElementById("txtSearch").value;
window.location = "http://www.mysite.com/search/?Query=" + Searchtxt;
}
</script>
I changed .value();
to .value;
taking out the ()
I did not change anything in my text field or submit button
<input name="txtSearch" type="text" id="txtSearch" class="field" />
<input type="submit" name="btnSearch" value="" id="btnSearch" class="btn" onclick="javascript:SubmitFrm()" />
Works like a charm.
回答5:
Remove 'javascript:' from your code and it should work.
Do you happen to use FireFox? I have learned from someone else that FireFox no longer accepts the 'javascript:' string. However, for the life of me, I cannot find the original source (though I believe it was somewhere in FF update notes).
来源:https://stackoverflow.com/questions/12802482/javascript-onclick-redirect