Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

input field clear button causing blur event - how to avoid

I'm building a form field with a "clear value" button - like on iOS there's a little "X" icon you can tap to clear your search string.

My problem is: I use the field's blur event to do error checks on the input format, and my implementation of the "X" icon always triggers the blur event.

I'm stumped: if I place the icon as a background image in the input field, I no longer have a click target, and if I use a standard div or img layered on top of the field, of course the blur triggers.

I'm using jQuery but this might be a generic CSS/javascript issue.

for example the accepted solution here: Clear icon inside input text that's a fine example of the original intent but this also will trigger the blur event as soon as you attach one.

UPDATE: It seems like the best way is to use the error checking function - but I don't like it so I kept looking... turns out I was unaware of the contenteditable attribute in HTML5.

Aside from the obvious accessibility concerns over not using form fields for form data, and forgetting about oldfashioned browsers that can't do HTML5, any reason why NOT to recreate input fields with contenteditable div tags?

like image 275
tim Avatar asked Apr 22 '26 10:04

tim


2 Answers

Instead of trying to avoid the blur event, why don't you just exclude this case (X click) from your input validation function? There are a couple of ways that you could do this, for example, on hover you can have a var doExclude set to true. In you validation function, when the blur event fires, it can first check this before the rest of the function:

if (exclude) return;

After the X is done you can return focus to your input if you want $('input').focus();

like image 175
Vexter Avatar answered Apr 25 '26 00:04

Vexter


many options here

  • You may change trigger to validate on 'keyup' or check error on 'submit'
  • use jquery validate plugins
  • in the $('#X-icon').click(fn) you can clear/hide error message as well. so user will not see error message.
like image 38
aifarfa Avatar answered Apr 24 '26 22:04

aifarfa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!