我正在尝试做一些简单的客户端验证,因为我的表单非常简单,只需要知道它的所有字段是否都已填写。
以下是模板的相关部分:
{% block content %}
<form id="location_form" action="{% url "mountain_results" %}" method="GET">
<h2>Enter your location</h2>
<input id="location_autocomplete" placeholder="Enter your address" name="address"
onFocus="geoLocate()" type="text"></input>
<h2>Enter your maximum drive time</h2>
<input name="drive_time"
placeholder="Enter your maximum drive time (hours)" type="text"></input>
<h2>Are you shredding today or tomorrow?</h2>
<select name="shred_day">
<option value="today">Today</option>
<option value="tomorrow">Tomorrow</option>
</select>
<br>
<button type="submit">Find me snow</button>
</form>
{% endblock content %}以下是JS的相关部分:
$('#location_form').on('submit', function(event) {
alert('dude you totally clicked');
event.preventDefault();
return false;
});有趣的是,警报甚至不会触发,所以感觉事件处理程序甚至没有被触发。有什么想法吗?正如您所看到的,我尝试了两种常用的方法来防止触发默认事件,但都没有效果。
发布于 2015-11-19 11:55:08
您可以使用onsubmit事件处理程序来验证表单。我已经将演示的action属性设置为空。您可以将其与onsubmit一起添加。另外,有没有什么特别的原因导致使用GET方法。这是一段代码片段。
HTML
<form id="location_form" action="" method="POST" onsubmit="return _validateForm()">
<h2>Enter your location</h2>
<input id="location_autocomplete" placeholder="Enter your address" name="address"
onFocus="geoLocate()" type="text"></input>
<h2>Enter your maximum drive time</h2>
<input name="drive_time"
placeholder="Enter your maximum drive time (hours)" type="text"></input>
<h2>Are you shredding today or tomorrow?</h2>
<select name="shred_day">
<option value="today">Today</option>
<option value="tomorrow">Tomorrow</option>
</select>
<br>
<button type="submit">Find me snow</button>
</form>JS
function _validateForm(){
alert('dude you totally clicked');
}这是一个DEMO.Hope,这将是有帮助的
发布于 2015-11-19 17:42:10
这是另一种方法。变化
<button type="submit">Find me snow</button>使用
<button id="submit_form">Find me snow</button>并添加以下JavaScript代码
$('#submit_form').click(function(){
if(for_is_valid()){
$('#location_form').submit();
}
else{
alert('Your message');
}
});希望这能行得通。
https://stackoverflow.com/questions/33794791
复制相似问题