重置表单后将焦点重新设置为输入

时间:2018-09-19 13:08:54

标签: javascript jquery html forms focus

我有一个表单,该表单的输入字段具有一个带有重置按钮的自动对焦。重置表单时,我希望输入集再次聚焦。有人有解决方案吗?

<form>
 <input type="text" name="focus" required class="search-box" autofocus="autofocus" 
placeholder="search items" />
 <a href="javascript:void(0)" class="close-icon" type="reset"></a>
 <button type="submit" class="btn btn-primary filtersearch" 
data-id="<?php echo $_POST['search']; ?>"><span class="glyphicon glyphicon-filter"></span> 
Filter items</button> 
 </form>

1 个答案:

答案 0 :(得分:0)

A)使用重置button代替锚元素,以保留浏览器的表单重置行为。

B)将reset事件处理程序绑定到表单,并集中具有autofocus属性的字段。示例:(没有jQuery)

var form = document.querySelector('form');
form.addEventListener('reset', function(event) {
    var autofocusField = form.querySelector('[autofocus]');
    if(autofocusField instanceof HTMLInputElement) {
        autofocusField.focus();
    }
});
<form>
    <input type="text" name="focus" required class="search-box" autofocus="autofocus"
           placeholder="search items" />
    <button class="close-icon" type="reset">Reset</button>
    <button type="submit" class="btn btn-primary filtersearch">Filter items</button>
</form>