Pergunta

I want to check some condition when a particular button is clicked how to do this?

 $(document).ready(function () {
         var prm = Sys.WebForms.PageRequestManager.getInstance();
         prm.add_initializeRequest(InitializeRequest);
         prm.add_endRequest(EndRequest);
         Search("Other");


     });

     function InitializeRequest(sender, args) {
     }

     function EndRequest(sender, args) {
         alert(sender._postBackSettings.sourceElement.id)
         var str1 = new String(sender._postBackSettings.sourceElement.id);
         if (sender._postBackSettings.sourceElement.id == ContentPlaceHolder1_btnNew) {
             alert("You have clicked new")
             Search("NEW"); 
         }

         else {
         alert("OTHERS")
             Search("Other");
          }


     }
Foi útil?

Solução

I got the solution by assigning it to a string value and checking in if condition as string.

 $(document).ready(function () {
         var prm = Sys.WebForms.PageRequestManager.getInstance();
         prm.add_initializeRequest(InitializeRequest);
         prm.add_endRequest(EndRequest);
         Search("Other");


     });

     function InitializeRequest(sender, args) {

     }

   function EndRequest(sender, args) {

         var str1 = new String(sender._postBackSettings.sourceElement.id);

         if (str1 == "ContentPlaceHolder1_btnNew") {                
            alert("You have clicked new")
         }

         else {
          alert("You have clicked others")
         }

     }

Outras dicas

If you have plenty of buttons, give them a same class name. Eg : class="myButton" The information regarding the particular button can be kept in its attribute. Eg : objectId="12345" then your code can come as follows :

$(".myButton").click(function(){
       console.log($(this)); // this gives you the DOM Object of the button which is clicked
       // now to get the attribute of the button i.e objectId you can do this
       $(this).attr("objectId");
       /* Depending on this you can handle your condition */
    });

If your buttons are being dynamically created, you can use this

$(".myButton").live('click', function(){
           console.log($(this)); // this gives you the DOM Object of the button which is clicked
           // now to get the attribute of the button i.e objectId you can do this
           $(this).attr("objectId");
           /* Depending on this you can handle your condition */
        });

live is deprecated for versions above Jquery 1.7.2.

You can use "on" instead of it.

Try this code :

$(document).ready(function() {

    $("#btnSubmit").click(function(){
        // Call here that function which you want to call
    }); 
});

Read this link: http://api.jquery.com/click/

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top