I am trying to build a little search script, but can't seem to stop the page from re-loading when you hit submit. There is probably something wrong with my code:
function searchThat(e) {
if (!e) e = window.event;
e.preventDefault();
if (searchFor.indexOf(searchIn) != -1) {
console.log('we found it');
}
}
Thanks a bunch!
I am calling it with
if (searchFor && searchIn && searchSubmit) {
addEvent(searchSubmit, 'submit', searchThat)
}
and:
function addEvent(elem, evtType, func) {
if (elem.addEventListener) {
elem.addEventListener(evtType, func, false);
} else if (elem.attachEvent) {
elem.attachEvent("on" + evtType, func);
} else {
elem["on" + evtType] = func;
}
}
and the HTML:
<div class="container">
<form>
<p>Search for:</p>
<p class="mrm">
<input type="text" id="searchFor" name="searchFor">
</p>
<p>In:</p>
<textarea class="mrm" type="text" id="searchIn" name="searchIn"></textarea>
<p>
<input type="submit" class="clicker nmb" id="searchSubmit" name="searchSubmit">
</p>
</form>
</div>
<Input type="submit"/>
will always trigger postback and reload the page. If it works with whatever you're trying to implement change your input to <Input type="button"/>
And
addEvent(searchSubmit, 'click', searchThat)
{}
There could be more logic that your code is missing but from what you've posted you can make your life even easier by instead of doing all this complicated JScripting you can just do: <Input type="button" value="Click Me" onclick="searchThat()"/>
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.