开发者

Jquery event triggering twice for no reason

开发者 https://www.devze.com 2022-12-23 01:32 出处:网络
I\'m having a problem with a simple form where i\'m attempting to fire an ajax request when someone types something. After debugging I\'m left with an alert when the event is fired but it shows up twi

I'm having a problem with a simple form where i'm attempting to fire an ajax request when someone types something. After debugging I'm left with an alert when the event is fired but it shows up twice, irrespective of the browser. (Ignore the 'rel' attribute in the input tags, that's for something else, unless you think its the rel attribute causing the issue).

<form class="formBig" name="formRegister" id="formRegister" method="post" action="">
    <label class="label" id="locationLabel" for="location">Location</label>
    <input class="input" name="location" id="location" type="text" rel="locationLabel" value="" />
</form>

<script type="text/javascript">
$("#location").click(function() {
    alert($(this).attr('开发者_运维技巧id'));
});
</script>


You are binding a click event handler to a text input field meaning that it will be invoked when you click and not when you type. Try using the keyup event.


I ended up figuring it out, it was because (for some unknown-to-me-reason) the jquery I was including was put in after the form.

However, if I included it within the document.ready, it worked fine. I assume this has something to do with DOM. I dunno, I'm still fairly n00bish when it comes to jquery.

And the document ready is called from within the head-tags via a script include.


Basically, it triggers twice because there is a label associated with that event which will cause the event to be triggerd twice one on the input and the other on associated label.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号