0

I use tis code:

$(document).bind('click', function(e) {
  if(!$(e.target).is('#paybox')) {
    $('#paybox').hide();
  }
});

to hide #paybox when user click anywhere but #paybox.

But when I click on "radio" form:

<div id="paybox">
    <table width="100%">
        <tr>
            <form method="post" action="">
                <td>
                    <input type="radio" name="dauer" value="small" checked>
                </td>

                <td>
                    <input type="radio" name="dauer" value="mid">
                </td>

                <td>
                    <input type="radio" name="dauer" value="big">
                </td>
            </form>
        </tr>
    </table>
</div>

INSIDE the #payboy then #payboy get hidden!

How can I prevent this?

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
Eddy Unruh
  • 576
  • 1
  • 5
  • 18

3 Answers3

3

You should check whether or not your click is inside paybox or not. Something like this should work:

$('body').on('click', function(e) {
  if($(e.target).closest('#paybox').length === 0) {
    $('#paybox').hide();
  }
});

So this only hides the #paybox element if the click is neither on paybox nor any node that is within the #paybox element.

bummzack
  • 5,805
  • 1
  • 26
  • 45
  • 1
    you'd be better off just using `$(e.target).closest('#paybox').length` since `closest()` checks the element itself, as well as its ancestors – billyonecan Nov 26 '16 at 15:39
  • @billyonecan Yeah, the question seems to be answered here already http://stackoverflow.com/questions/152975/how-do-i-detect-a-click-outside-an-element#answer-3028037 – bummzack Nov 26 '16 at 15:41
1

You can use closest or parents to check this as below

$(document).bind('click', function(e) {
  if(!$(e.target).is('#paybox') && $(e.target).closest('#paybox').length === 0) {
    $('#paybox').hide();
  }
});
#paybox {
  background-color: gray;
  height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="paybox">
    <table width="100%">
        <tr>
            <form method="post" action="">
                <td>
                    <input type="radio" name="dauer" value="small" checked>
                </td>

                <td>
                    <input type="radio" name="dauer" value="mid">
                </td>

                <td>
                    <input type="radio" name="dauer" value="big">
                </td>
            </form>
        </tr>
    </table>
</div>
Aruna
  • 11,959
  • 3
  • 28
  • 42
0

You could check if the target is a child of your div

// if target is not paybox and is not child of paybox
$(document).bind('click', function(e) {
  if(!$(e.target).is('#paybox') && !$(e.target).parents('#paybox').length) {
    $('#paybox').hide();
  }
});
Dex Dave
  • 730
  • 1
  • 6
  • 14