Pedro Gámez Pedro Gámez - 5 months ago 13
Javascript Question

Click event on behind is triggered when wrap in a label

I have a problem with click event on behind element. I have an input with another element to reset it. This element is positioned absolutely before the input.

The input has a click event that I want block when I clicked in the reset element. This works fine when both elements aren't in a LABEL tag:



$(document).on('click', '.popup_selector', function(e){
alert('Input cliked, if clicked in X it is an error');
});

$('i').click(function(e){
$('input').val(''); // clear the input
});

i {
position: absolute;
right: 0.5em;
top: 0.1em;
width: 1em;
cursor: pointer;
}

i:after {
content: 'disable-click';
visibility: hidden;
overflow: hidden;
}

input {
padding-right: 2em;
}

div {
position: relative;
display: inline-block;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<i class='clear'>X</i>
<input type="text" class="popup_selector" />
</div>





The problem occurs when both elements are wrapped by a LABEL tag. When I click in the reset element, the input click event is triggered and this is a problem:



$(document).on('click', '.popup_selector', function(e){
alert('Input cliked, if clicked in X it is an error');
});

$('i').click(function(e){
$('input').val(''); // clear the input
});

i {
position: absolute;
right: 0.5em;
top: 0.1em;
width: 1em;
cursor: pointer;
}

i:after {
content: 'disable-click';
visibility: hidden;
overflow: hidden;
}

input {
padding-right: 2em;
}

div {
position: relative;
display: inline-block;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<div>
<i class='clear'>X</i>
<input type="text" class="popup_selector" />
</div>
</label>





Anybody know how to fix it?

Thanks you very much.

Tested in chrome 51.

zan zan
Answer

Try this it will work

$('i').click(function(e){
    e.preventDefault();
    $('input').val(''); // clear the input
  });