简体   繁体   中英

Event Called twice on button click in jquery

I have a Submit button on click of which i am calling the click function inside javascript first.

var id = $('input[id$=chkSubcontracting]').attr("id");
var indexserverIdPrefix = id.indexOf("chkSubcontracting");
var serverId= id.substring(0,indexserverIdPrefix);
$('#'+ serverId +'historyControl_historySubmitButton').click(function() {

//other part of code
//if error is there then add the error message to message

 if (message != "") {    
        $('#'+ serverId +'ErrorMessagePanelHiddenField').val("1");
        $(this.ErrorMessagePanelHiddenField).val("1");
        $("[id*='ErrorMessagePanelHiddenField']").val("1");
        this.IsValid = 1;
          alert(message);
         } 
else
 { 
         $("[id*='ErrorMessagePanelHiddenField']").val("0");
}

My Aspx Page code is here

<asp:Panel ID="ErrorMessagePanel" CssClass="ErrorPanel" Visible="true" runat="server">
                    <asp:HiddenField ID="ErrorMessagePanelHiddenField" runat="server" />
                    <div class="ErrorDiv" id="ErrorMessageDiv">
                        <asp:BulletedList CssClass="ErrorMessage" ID="ErrorMessageBulletedList" runat="server">
                        </asp:BulletedList>
                    </div>
                </asp:Panel>

Sometimes on button click this event is fired twice. Also I am able set 'ErrorMessagePanelHiddenField' value first time. but not at subsequent time.

If you call jQuery .click() on an element more than once, the event handler will be attached multiple times. Ensure that the script you posted where the click event handler is attached is not being executed more than once in your page. See click() event is calling twice in jquery

Another approach is to use jQuery's .off() and .on() methods, as explained in Using Jquery off().on() or just on() . Essentially, the .off() method will remove any attached event handlers, so you can be sure that when you call .on() to attach your click handler, it will be the only one attached.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM