简体   繁体   English

HTML表单-如果未输入任何内容,则用值填充输入

[英]HTML Form - Fill input with value if nothing is entered

I'm creating a basic subscribe form for a system that requires both email address and last name (SugarCRM in case anyone is interested). 我正在为同时需要电子邮件地址和姓氏的系统创建一个基本的订阅表单(如果有人有兴趣,请使用SugarCRM)。

I need to populate the last name input value with something (anything, it doesn't matter) only if the visitor doesn't put their own last name in. 当访问者未输入自己的姓氏时,我才需要使用某些内容 (任何内容都没有关系)填充姓氏输入值。

As the subscribe action is hosted (Mail Chimp) I don't have access to it to pre-validate, unless this can happen before it's passed on. 由于托管了订阅操作(Mail Chimp),因此我无权对其进行预验证,除非可以在传递之前进行此操作。 I'm wading into deeper PHP waters than I'm comfortable with! 我正在涉足比自己更满意的PHP深处! Is this possible with jQuery ? jQuery有可能吗?

So basically I'm getting around the required last name by filling the value with something. 所以基本上我通过在值中填充一些东西来解决所需的姓氏。

Check the lastname on submit of the form, if it doesn't have value, put "foo" in it: 检查表单提交时的姓氏,如果没有值,请在其中输入"foo"

$('#formId').submit(function() { // attach submit handler to the form.
    var $lastName = $('#lastName'); // get the last name element.
    if (!$lastName.val())   // if it doesn't have value.
        $lastName.val('foo'); // put foo as a value.
});​

You should replace formId and lastName to the actual ids of the form and last name element. 您应该将formIdlastName替换为表单和姓氏元素的实际ID。

Yes, this is for sure possible with jQuery. 是的,这肯定可以用jQuery实现。 Just look at the jQuery API and then register an event to the submit button, so, that the event is executed before the submit action. 只需查看jQuery API,然后将一个事件注册到Submit按钮,就可以在Submit操作之前执行该事件。 There are several possibilities. 有几种可能性。

Using selectors you can search your last name input field and read and compare the entered value. 使用选择器,您可以搜索您的姓氏输入字段,并读取和比较输入的值。 If needed you can then change the value of your input field. 如果需要,您可以更改输入字段的值。

Just take a look at http://api.jquery.com/ . 只需看看http://api.jquery.com/即可 Study there the events, selectors and manipulation values. 在那里研究事件,选择器和操作值。 Examples are pretty well self explaining. 例子很好地自我解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM