-1

当按下提交按钮时,我将如何删除每个输入具有相同值的字段值,就像使用 Jquery 加载页面时一样。

逻辑示例: 在加载时将变量设置为等于每个输入值 在提交按钮的鼠标按下时,如果该值仍与该变量匹配,则删除该值。

还是 jQuery 的新手,感谢您的帮助 :)

4

3 回答 3

4

我将使用的一种方法是设置自定义 HTML 属性,例如:

<input name="foo" value="test" data-default="test" />

然后,当用户提交表单时,我们将表单的值与默认值进行比较。如果它们相同,那么我们将其重置。所以:

$(document).ready(function() {
    $('form').submit(function() {
        $(this).find('input').each(function() { 
            if($(this).val() == $(this).attr('data-default')) $(this).val('');
        });
    });
});

希望对您有所帮助。

于 2013-03-06T16:00:16.963 回答
0

将 onChange 事件添加到所有输入字段以跟踪修改了哪些字段。

在另一个属性中存储默认值会增加页面加载时间并复制所有数据。也许你的数据是大量的。如果是这样,请注意变化。

例子:

var untouched_fields = []
$(document).ready(function() {
   $('#form input').each(function() { untouched_fields.push( $(this).attr("id") ) }
   $('#form input').on("change", function() { untouched_fields.remove( $(this).attr("id") ) })
})

..然后在提交时,阅读 untouched_fields。

于 2013-03-06T16:05:26.187 回答
0

首先,如果浏览器支持占位符,请使用它们而不是您的功能。接下来,如果不支持占位符,则最初相应地更新输入,然后在提交时撤消该更改。

HTML

<input name="first-name" placeholder="First Name" />

JavaScript

// before all of your code
jQuery.support.placeholder = (function(){
    var i = document.createElement('input');
    return 'placeholder' in i;
})();

// in document ready
if (!$.support.placeholder) {
    // update value of empty inputs to the value of the placeholder attribute if set.
    $("input[placeholder]").val(function(i,val) {
        return val == "" ? $(this).attr("placeholder") || "" : val;
    }).focus(function(){
        if (this.value == $(this).attr("placeholder")) {
            this.value = "";
        }
    }).blur(function(){
        if (this.value == "") {
            this.value = $(this).attr("placeholder");
        }
    });
}


$('form').submit(function() {
    if (!$.support.placeholder) {
        $("input[placeholder]",this).val(function(i,val) {
            return val == $(this).attr("placeholder") ? "" : val;
        });
    }
});

在我自己的代码中,我实际上会在输入后面放置一个标签并显示/隐藏它,而不是触摸输入的值。

于 2013-03-06T16:13:16.913 回答