呼叫功能按下Enter或点击按钮
问题描述:
我想在输入或按下按钮时调用JavaScript函数。另外,我想让函数检索值。呼叫功能按下Enter或点击按钮
这里是我的形式:
<form>
Farm Number:<br>
<input id="fnumber" type="text" value="" onKeyDown="findfarm2(event)">
<input type="button" value="Find Farm" onclick="findfarm();"> \t
</form>
,这里是我的JavaScript函数:
function findfarm2(event) {
\t \t if (event.keyCode == 13){
\t \t cqlfilter = 'Farm =' + document.getElementById('fnumber').value; \t \t
\t \t unregistered.getSource().updateParams({'LAYERS': 'NCSPCTest:Unreported_Names','CQL_FILTER': cqlfilter}); \t \t
\t \t alert(cqlfilter)
\t \t }
\t \t }
\t \t
function findfarm() {
\t \t cqlfilter = 'Farm =' + document.getElementById('fnumber').value; \t \t
\t \t unregistered.getSource().updateParams({'LAYERS': 'NCSPCTest:Unreported_Names','CQL_FILTER': cqlfilter});
\t \t alert(cqlfilter)
\t \t } \t
的按钮B工作输入功能不是。 'findfarm2'函数可以弹出警报,但不会将值传递给'updateParams'。
答
您的功能(findfarm2)不起作用,因为当您按下ENTER按钮(keyCode = 13)时表单正在提交。
<form id="form" active="#">
<!-- get value (using parameters) -->
<input id="first" type="text" value="" onkeydown="find(event, this.value)">
<input id="last" type="button" value="Find Farm" onclick="findfarm();">
</form>
<script type="text/javascript">
document.querySelector('#form').addEventListener('submit', function(e) {
e.preventDefault(); // stop form from submitting
console.log('You need stop form from submitting!')
});
function find(e, val) {
if (e.keyCode == 13) {
console.log('enter')
}
var value = document.getElementById('first').value;
console.log('My value (using getElementById)' , value)
console.log('My value (using parameters)' , val)
// resume your code here...
}
function findfarm() {
console.log('Find Farm clicked!');
}
</script>
也许ENTER键只有在焦点位于按钮上时才会起作用。 – mariodiniz