简体   繁体   中英

OnChange on textbox Event calling twice

I am adding onchange event dynamically using jQuery. When I am changing the textbox the event is firing twice and two times alert boxes are coming sometimes 3 times.

if(Country.toUpperCase().indexOf("MALAYSIA")!=-1)
{    debugger;
    if(productDesc.toUpperCase().indexOf("SV")!=-1)
    {                   
        $("#<%=txtlAxis.ClientID%>").change(function()
        {         
                if(productDesc.toUpperCase().indexOf("SV")!=-1)
                {                           
                alert('2');
                }
        });  
    }
}

Can you use unbind in this code?

if(Country.toUpperCase().indexOf("MALAYSIA")!=-1)
   {  
        if(productDesc.toUpperCase().indexOf("SV")!=-1)
        {       
            $("#<%=txtlAxis.ClientID%>").unbind();
            $("#<%=txtlAxis.ClientID%>").change(function()
            {         
                 if(productDesc.toUpperCase().indexOf("SV")!=-1)
                 {                           
                    alert('2');
                 }
            });  
        }
   }

Try below. Unbind the OnChange event and add it again on the fly.

if(Country.toUpperCase().indexOf("MALAYSIA")!=-1)
{    
    if(productDesc.toUpperCase().indexOf("SV")!=-1)
    {      
        $('.txtlAxisClass').attr("onchange", "");             
        $("#<%=txtlAxis.ClientID%>").change(function()
        {         
             if(productDesc.toUpperCase().indexOf("SV")!=-1)
             {                           
                alert('2');
             }
        });  
    }
}

You are also Downgrading the Performance by re-evaluating the below mentioned expression again. So keep it in the variable.

productDesc.toUpperCase().indexOf("SV")

Its fixed. Thank you so much for your reply. MMK unbind() is CORRECT. I used Kanavi's .attr("onchange", "") also but NO USE. Checked in IE8 and CROME.

Yes Kanavi, I will take that into one variable thx for ur suggesion. StackOverflow ROCKS.

       if(Country.toUpperCase().indexOf("MALAYSIA")!=-1)
       {    
            if(productDesc.toUpperCase().indexOf("SV")!=-1)
            {                  
                $(".clstxtlAxis").unbind("change"); 
                $(".clstxtlAxis").change(function()
                {             
                     if(productDesc.toUpperCase().indexOf("SV")!=-1)
                     {
                        alert("2");                                                   
                     }
                }); 
             }
        } 

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