在用户输入时运行javascript函数
我通常不想打扰你们,但我有点心神不宁,到处都找不到答案,希望你们能帮我 我正在构建一个web应用程序并进行设计,使其界面与iOS7匹配。 我有一个输入表单,我需要一个按钮来提交表单,只有当验证完成后,表单才会变为蓝色并可选择。我已经写了一些JS来验证输入,但这只运行一次!每次用户修改输入值时,我都需要运行该函数 这是我到目前为止为JS所做的:在用户输入时运行javascript函数,javascript,jquery,html,forms,input,Javascript,Jquery,Html,Forms,Input,我通常不想打扰你们,但我有点心神不宁,到处都找不到答案,希望你们能帮我 我正在构建一个web应用程序并进行设计,使其界面与iOS7匹配。 我有一个输入表单,我需要一个按钮来提交表单,只有当验证完成后,表单才会变为蓝色并可选择。我已经写了一些JS来验证输入,但这只运行一次!每次用户修改输入值时,我都需要运行该函数 这是我到目前为止为JS所做的: function validateInput(){ if (document.getElementById('projectname')
function validateInput(){
if (document.getElementById('projectname').value.length < 2)
document.getElementById('forwardbutton').style.color = "#c4c4c5";
else
document.getElementById('forwardbutton').style.color = "#0e81ff";
}
函数validateInput(){
if(document.getElementById('projectname').value.length<2)
document.getElementById('forwardbutton').style.color=“#C4C5”;
其他的
document.getElementById('forwardbutton').style.color=“#0e81ff”;
}
谢谢大家 添加到您的输入
onchange
侦听器:
var input = document.getElementById("myInput");
input.addEventListener('change', validateInput, false);
这将在每次值更改时触发validateInput
功能。
另外,您应该缓存您在验证函数中获得的DOM元素,因为它总是在DOM中搜索,以在函数启动时找到它们-这在一个大DOM树中可能会很重,您的意思是
function validateInput(){
if (document.getElementById('projectname').value.length < 2)
document.getElementById('forwardbutton').style.color = "#c4c4c5";
else
document.getElementById('forwardbutton').style.color = "#0e81ff";
}
更多信息可能会有所帮助。我不知道您是否反对jQuery,但我将提供jQuery的实现方法。jQuery非常简单。您将使用键盘事件处理程序,特别是 在事件处理程序中,然后检查字段的长度,并根据长度设置按钮的启用或禁用状态
$('#input-element').keyup(function () {
if (document.getElementById('projectname').value.length < 2)
document.getElementById('forwardbutton').style.color = "#c4c4c5";
else
document.getElementById('forwardbutton').style.color = "#0e81ff";
}
});
$(“#输入元素”).keyup(函数(){
if(document.getElementById('projectname').value.length<2)
document.getElementById('forwardbutton').style.color=“#C4C5”;
其他的
document.getElementById('forwardbutton').style.color=“#0e81ff”;
}
});
您还可以使用jQuery来设置颜色或启用状态,而不是使用以前的代码。由您决定。
您可以使用jquery绑定到输入事件,jquery可以同时处理几乎所有的输入事件
<input id="myInput" type="text" />
<div id="output"></div>
js
$('myInput').bind('input',function(){
如果(此.value.length<2){
document.getElementById('output').style.color=“#C4C5”;
}否则{
document.getElementById('output').style.color=“#0e81ff”;
}
$('#output').html(this.value);
});
getElementById参数中有一个输入错误这太棒了!我将使用你的答案,因为它非常适合我的需要。感谢您花时间制作演示!
<input id="myInput" type="text" />
<div id="output"></div>
$('#myInput').bind('input',function(){
if( this.value.length < 2 ){
document.getElementById('output').style.color = "#c4c4c5";
}else{
document.getElementById('output').style.color = "#0e81ff";
}
$('#output').html(this.value);
});