我有一个有很多字段的表单,当我点击按钮时(最好使用jQuery),我想清除输入[type=text]的所有默认值(未更改的值)。我使用按钮而不是提交,因为我将使用相同的按钮将表单提交到本地脚本,然后提交到第三部分进行处理。但我的剧本似乎不起作用。
表格的简化版本:
<form name="cpdonate" id="cpdonate" method="post" action="" >
<input type="text" value="First Name" id="BillingFirstName" name="BillingFirstName" onFocus="clearField(this)" onBlur="setField(this)" />
<input type="text" value="Last Name" id="BillingLastName" name="BillingLastName" onFocus="clearField(this)" onBlur="setField(this)" />
<input type="hidden" name="Submit" value="Submit" />
<button id="cpbutton">Submit</button>
</form>
以及我正在使用的脚本:
<script type="text/javascript">
$(document).ready(function(){
// default values will live here
var defaults = {};
// Set the default value of each input
$('input[type=text]').each(function(){
defaults[$(this).attr('value')] = $(this).text();
});
// Functions to perform on click
$('#cpbutton').click(function(){
// clear unchanged values
$('input[type=text]').each(function(){
if (defaults[$(this).attr('value')] === $(this).text())
$(this).text('');
});
});
});
</script>
input
没有文本,它有值,一旦用户更改了属性,就不能依赖它,需要从value属性中获取它。此外,如果值发生更改,defaults
对象将找不到该值。
我将使用data()
将每个值存储在元素本身
使用val()
$(document).ready(function(){
// Set the default value of each input
$('input[type=text]').each(function(){
$(this).data('val', $(this).val());
});
// Functions to perform on click
$('#cpbutton').click(function(){
// clear unchanged values
$('input[type=text]').each(function(){
if ($(this).data('val') === $(this).val())
$(this).val('');
});
});
});
您应该使用defaults[$(this).attr('name')]而不是defaults[$[(this).attr('value')],因为当用户更改值时,属性"values"值也会更改
您可以尝试这个(示例)
// clear unchanged values
$('input[type=text]').each(function(){
if ($(this).val() == this.defaultValue) $(this).val('');
});
input type=text
具有.val()
jQuery方法,而不是text()
,并使用this.defaultValue
检查初始默认值。