Javascript function will not activate onClick

柔情痞子 提交于 2019-12-12 05:26:58

问题


In my page head:

<script>
function formula()
{
    document.forms["inquire"]["search"].value.scrollIntoView();
}
</script>

In my page body:

<div id="nav">
<form id="inquire" name="inquire" onSubmit="return false;">
Search or inquire here: <input type="text" id="search" name="search" value="<?php search($_GET['search']) ?>" autocomplete="off"/>
<input type="button" name="btnSearch" id="btnSearch" onClick="formula();"/>
</form>
</div>

What I want to happen here is that, when btnSearch is clicked, it activates formula(), taking the value from search in form inquire, and then scrolling to the value in a separate div I have called formula. This works if I put document.getElementById(this.form.search.value).scrollIntoView(); directly into the onClick for btnSearch, however it refuses to work no matter how I set it up as a function. Does anyone here know why it might be doing this, or how I can fix it?


回答1:


It's not working because your function is erroneous:

function formula() {
  document.getElementById(document.forms.inquire.search.value).scrollIntoView();
}

That code gets the value of the search field and uses it for an "id" lookup. It'd probably be a good idea to check that there actually is an "id" with the value typed in:

function formula() {
  var element = document.getElementById(document.forms.inquire.search.value);

  if (element) element.scrollIntoView();
}


来源:https://stackoverflow.com/questions/15619627/javascript-function-will-not-activate-onclick

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!