gpt4 book ai didi

javascript - 使用 onsubmit 清除默认值

转载 作者:行者123 更新时间:2023-11-28 16:38:18 24 4
gpt4 key购买 nike

我需要使用 js 清除输入字段的默认值,但到目前为止我的所有尝试都未能定位和清除字段。我希望在提交表单之前使用 onSubmit 执行一个函数来清除所有默认值(如果用户没有更改它们)。

<form method='get' class='custom_search widget custom_search_custom_fields__search' onSubmit='clearDefaults' action='http://www.example.com' >
<input name='cs-Price-2' id='cs-Price-2' class='short_form' value='Min. Price' />
<input name='cs-Price-3' id='cs-Price-3' class='short_form' value='Max Price' />
<input type='submit' name='search' class='formbutton' value=''/>
</form>

您将如何实现这一目标?

最佳答案

  • 在页面首次加载时读取所有字段的 ids+value(例如,使用 jquery 等获取所有“textarea”、“input”和“select”标签)
  • 提交时,将当前包含的值与加载页面时存储的值进行比较
  • 将未更改的替换为空值

如果仍然不清楚,请描述您遇到困难的地方,我将进行更深入的描述。

编辑:使用 jQuery 添加一些代码。它仅适用于 textarea-tag,它不会响应实际事件,但希望它能进一步解释这个想法:

// Keep default values here
var defaults = {};

// Run something like this on load
$('textarea').each(function(i, e) {
defaults[$(e).attr('id')] = $(e).text();
});

// Run something like this before submit
$('textarea').each(function(i, e){
if (defaults[$(e).attr('id')] === $(e).text())
$(e).text('');
})

编辑:添加更多代码以获得更详细的帮助。这应该是相当完整的代码(带有质量免责声明,因为我绝不是 jQuery 专家),并且只需要包含在您的页面中即可。除了为所有输入标签提供唯一的 id 和 type="text"之外,无需执行任何其他操作(但无论如何它们都应该具有):

$(document).ready(function(){
// Default values will live here
var defaults = {};

// This reads and stores all text input defaults for later use
$('input[type=text]').each(function(){
defaults[$(this).attr('id')] = $(this).text();
});

// For each of your submit buttons,
// add an event handler for the submit event
// that finds all text inputs and clears the ones not changed
$('input[type=submit]').each(function(){
$(this).submit(function(){
$('input[type=text]').each(function(){
if (defaults[$(this).attr('id')] === $(this).text())
$(this).text('');
});
});
});
});

如果这仍然没有任何意义,您应该阅读一些有关 jQuery 和/或 javascript 的教程。

关于javascript - 使用 onsubmit 清除默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2601328/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com