重置选择框的值
我正在尝试重置两个选择字段的值,结构如下,
jQuery的,
$('select').each(function(idx, sel) { $(sel).find('option :eq(0)').attr('selected', true); });
不幸的是,无论我尝试多少种方式,它都不会发生。 控制台中没有任何东西。 我不知道是怎么回事? 我知道必须有一种方法可以做到这一点,你可以用JS做任何事情
编辑:
我发现问题只发生在我尝试在点击dom元素时触发代码时,但是,我知道代码应该正常工作,因为当我有
$('p').click(function(){ console.log('test'); });
它将’test’输出到控制台,但是当我在此函数中包含代码时,没有任何反应。 为什么是这样?
我认为你只想重置一个元素。 重置整个表单很简单:调用其reset方法。
“重置”select元素的最简单方法是将selectedIndex
属性设置为默认值。 如果您知道没有选项是默认选择的选项,只需将select elemen’ts selectedIndex属性设置为适当的值:
function resetSelectElement(selectElement) { selecElement.selectedIndex = 0; // first option is selected, or // -1 for no option selected }
但是,由于一个选项可能具有所选的属性或以其他方式设置为默认选择的选项,您可能需要执行以下操作:
function resetSelectElement(selectElement) { var options = selectElement.options; // Look for a default selected option for (var i=0, iLen=options.length; i
并且要注意设置属性而不是属性,它们在不同的浏览器中具有不同的效果。
这对我有用:
$('select').prop('selectedIndex', 0);
小提琴
继@ RobG的纯/ vanilla javascript答案,你可以重置为’默认’值
selectElement.selectedIndex = null;
似乎-1取消选择所有项目,null选择默认项目,0或正数选择相应的索引选项。
select对象中的选项按照它们的定义顺序编制索引,从索引0开始。
资源
对我有用的是:
$('select option').each(function(){$(this).removeAttr('selected');});
neRok触及了上面这个答案,我只是在扩展它。
根据稍微过时,但方便的O’Reilly参考书, Javascript:The Definitive Guide :
Select对象的selectedIndex属性是一个整数,它指定Select对象中所选选项的索引。 如果未选择任何选项,则selectedIndex为-1。
因此,以下javascript代码将“重置”Select对象为没有选择的选项:
select_box = document.getElementById("myselectbox"); select_box.selectedIndex = -1;
请注意,以这种方式更改选择不会触发onchange()事件处理程序。
使用.val('')
setter
jsfiddle的例子
$('select').val('1');
我一段时间后发现了一个小实用function,从那时起我一直用它来重置我的表单元素(来源: http : //www.learningjquery.com/2007/08/clearing-form-data ):
function clearForm(form) { // iterate over all of the inputs for the given form element $(':input', form).each(function() { var type = this.type; var tag = this.tagName.toLowerCase(); // normalize case // it's ok to reset the value attr of text inputs, // password inputs, and textareas if (type == 'text' || type == 'password' || tag == 'textarea') this.value = ""; // checkboxes and radios need to have their checked state cleared // but should *not* have their 'value' changed else if (type == 'checkbox' || type == 'radio') this.checked = false; // select elements need to have their 'selectedIndex' property set to -1 // (this works for both single and multiple select elements) else if (tag == 'select') this.selectedIndex = -1; }); };
…或者作为jQuery插件……
$.fn.clearForm = function() { return this.each(function() { var type = this.type, tag = this.tagName.toLowerCase(); if (tag == 'form') return $(':input',this).clearForm(); if (type == 'text' || type == 'password' || tag == 'textarea') this.value = ''; else if (type == 'checkbox' || type == 'radio') this.checked = false; else if (tag == 'select') this.selectedIndex = -1; }); };