Why required option is not working in text field?

340 views Asked by At

I added a required option in the form, but it seems not to be working except email type.

<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

There are 2 answers

0
tewathia On BEST ANSWER

Because you have already given them Value attributes. Try using placeholder instead.

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>

Edit: This would still not work perfectly because you're setting the value in onblur. I've updated the fiddle, removing the onblur and onfocus events. That functionality is provided by default by the placeholder.

<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
Shuhel Ahmed On

Becasue onblur you are setting the value of the inputs by your javascript code.

Email is working because what onblur is setting is not a valid email address.