我创建了一个类似这样的表单:
<form action="#" class="header_form clearfix">
<input type="text" placeholder="Enter Your Address" id="autocomplete">
<a href="#" class="btn" onclick="document.location='/address?address='+$('#autocomplete').val();return false;">Enter Your Address</a>
</form>
&#13;
我想放置一个Javascript条件来检查文本输入中是否有文本在按钮具有onclick参数之前。如果密钥上没有文本,则onclick不在按钮上。怎么做?
答案 0 :(得分:1)
如果你使用的是jQuery,你可以这样做:
$('.btn').on('click', function() {
var email = $.trim( $('#autocomplete').val() );
if(email.length) {
window.location = '/address?address='+email;
} else {
alert('Enter your email first');
}
});
$ .trim是为了至少阻止空格触发有效提交 在任何情况下,您最好使用 EMAIL 正则表达式模式:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test
答案 1 :(得分:-1)
如果链接不是有效的电子邮件地址,也会禁用该链接
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
$( document ).ready(function() {
$('#autocomplete').bind('input', function() {
if ($(this).val().trim().length === 0) {
document.getElementById('myButton').removeAttribute('href');
} else {
if (validateEmail(document.getElementById("autocomplete").value) === true) {
document.getElementById('myButton').setAttribute("href",'/address?address=' + document.getElementById("autocomplete").value);
} else {
document.getElementById('myButton').removeAttribute('href');
}
}
});
document.getElementById('myButton').removeAttribute('href');
});
</script>
<form action="#" class="header_form clearfix">
<input type="text" placeholder="Enter Your Address" id="autocomplete" />
<a href="#" id="myButton" name="myButton" class="btn">Enter Your Address</a>
</form>
</body>
</html>