为什么必需选项在文本字段中不起作用?

时间:2013-12-04 20:06:02

标签: html5 forms textfield required-field

我在表单中添加了一个必需的选项,但除了电子邮件类型外似乎没有工作。

<input type="text" value="Your name" name="name" onblur="if (this.value == '') {this.value = 'Your name';}" onfocus="if (this.value == 'Your name') {this.value = '';}" required>
<input type="email" value="E-mail" name="email" onblur="if (this.value == '') {this.value = 'E-mail';}" onfocus="if (this.value == 'E-mail') {this.value = '';}" required>
<input type="tel" value="Phone number" name="phone" onblur="if (this.value == '') {this.value = 'Phone number';}" onfocus="if (this.value == 'Phone number') {this.value = '';}" required>
<input type="text" value="Your address" name="address" onblur="if (this.value == '') {this.value = 'Your address';}" onfocus="if (this.value == 'Your address') {this.value = '';}" required>                 
<input type="text" value="Coupon code" name="coupon" onblur="if (this.value == '') {this.value = 'Coupon code';}" onfocus="if (this.value == 'Coupon code') {this.value = '';}" required>

2 个答案:

答案 0 :(得分:1)

因为您已经为他们提供了Value个属性。请尝试使用placeholder

Demo

<input type="text" placeholder="Your name" name="name" onblur="if (this.value == '') {this.value = 'Your name';}" onfocus="if (this.value == 'Your name') {this.value = '';}" required>
<input type="email" placeholder="E-mail" name="email" onblur="if (this.value == '') {this.value = 'E-mail';}" onfocus="if (this.value == 'E-mail') {this.value = '';}" required>
<input type="tel" placeholder="Phone number" name="phone" onblur="if (this.value == '') {this.value = 'Phone number';}" onfocus="if (this.value == 'Phone number') {this.value = '';}" required>
<input type="text" placeholder="Your address" name="address" onblur="if (this.value == '') {this.value = 'Your address';}" onfocus="if (this.value == 'Your address') {this.value = '';}" required>                 
<input type="text" placeholder="Coupon code" name="coupon" onblur="if (this.value == '') {this.value = 'Coupon code';}" onfocus="if (this.value == 'Coupon code') {this.value = '';}" required>

编辑:由于您在onblur中设置了值,因此仍然无法正常工作。我已经更新了小提琴,删除了onblur和onfocus事件。该功能由占位符默认提供。

<input type="text" placeholder="Your name" name="name" required>
<input type="email" placeholder="E-mail" name="email" required>
<input type="tel" placeholder="Phone number" name="phone" required>
<input type="text" placeholder="Your address" name="address" required>                 
<input type="text" placeholder="Coupon code" name="coupon" required>

答案 1 :(得分:0)

Becasue onblur您正在设置javascript代码的输入值。

电子邮件正在运行,因为onblur设置的内容不是有效的电子邮件地址。