0

I have an input and a checkbox, when the input is focused it display some information under it.

The problem is : when those information are displayed if I click on the checkbox it hides the information (because my input is not focused anymore) but the checkbox is not checked.

Here is a working plunker which reproduce this behavior.

Is there a way to make the checkbox checked in this scenario ?

EDIT :

I think the problem is because the input loose the focus on the event mousedown and the checkbox is checked on the event mouseup (or maybe click) so when the mouseup event is fired the input has already lost the focus so the message under it is hidden and the checkbox moves up. So when the mouseup event is fired the cursor is not anymore on the checkbox, that's why the checkbox is not checked.

JeanJacques
  • 1,754
  • 1
  • 12
  • 25

2 Answers2

0

Nothing in pure CSS. You would need to bind focus event on JS.

Something like this:

var input = document.querySelector('#input');

input.addEventListener('focus', function() {
  this.classList.add('focus');
});

And then change your CSS from :focus to .focus

zmuci
  • 518
  • 1
  • 5
  • 21
  • I tryed your solution but it's same thing ([here is the plunker](https://plnkr.co/edit/0ciHCVsfNSdc9NgdozrN?p=preview)) – JeanJacques Mar 01 '18 at 12:50
  • @JeanJacques You are removing the class on `focusout`. – zmuci Mar 01 '18 at 15:58
  • Yes because I want to hide the span when the input is not focused anymore – JeanJacques Mar 01 '18 at 16:00
  • I don't understand what is the issue. – zmuci Mar 02 '18 at 08:59
  • What I want to do is to display the message under the input when the input is focused and to hide it when the input is not focused anymore. If you go on the plunker on my post, it's working fine, but the problem is when the message is displayed (so the input is focused) then if I click the checkbox, it hides the message (it's what I want) but the checkbox is not checked. Hope it's clearer – JeanJacques Mar 02 '18 at 12:36
  • Ok so the problem is that your `focusout` triggers as soon as you focus out and then it seems like `checkbox` is not being clicked. You can fix that by setting some timeout on `focusout` so you have the time to click it: `var _this = this; setTimeout(function() { _this.classList.remove('focus'); }, 500);` – zmuci Mar 02 '18 at 15:19
0

My solution for your question is attached here. This is a simple way. I have added JQuery code to it. You can try this code. I have written this code using JSFiddle. The link is given below:

[https://jsfiddle.net/679g9p6p/1/][1]

If you want to hide the information when focus out from the textbox, then you can try this code given below:

[https://jsfiddle.net/xxsL2e03/100/][2]

Vignesh VS
  • 921
  • 1
  • 14
  • 30
  • Your solution doesn't really fit my needs, I want the span hiden if the input is not focused not when the checkbox value change. Thank anyway ! – JeanJacques Mar 01 '18 at 12:55