Billy
Billy

Reputation: 905

Two button click events in Jquery

HTML

<input type="Submit" value="Add" id="btn1"/>
<input type="Submit" value="Add2" id="btn2"/>

Jquery

$("#btn1").click(function () {
    $("[id*=btn2]").click();
});

Controller

[httpPost]
Public ActionResult MyAction(){
    //some code
    return view();
}

Here, how can I differentiate, whether I have directly clicked the btn2 or it is coming from btn1?

Upvotes: 1

Views: 410

Answers (3)

Karthik M R
Karthik M R

Reputation: 990

Keep an hidden html tag for keeping track. Here, get the value from @ViewBag.hdnIsButton1Clicked for [HtpGet]/initial request for the View.

<input type="hidden" value="@ViewBag.hdnIsButton1Clicked" id="hdnIsButton1Clicked" name="hdnIsButton1Clicked" />

Set the value of the hidden field and also prevent the default behaviour of submit action. Jquery

$("#btn1").click(function (event) {
    $("#hdnIsButton1Clicked").val("1");
    event.preventDefault()
    $("[id*=btn2]").click();
})

Add a parameter to get the hidden value and set the viewbag data to be 0 again Controller

[httpPost]
Public ActionResult MyAction(string hdnIsButton1Clicked){
   if(hdnIsButton1Clicked == "1")
   { 
      //user clicked button 1
   }
   @ViewBag.hdnIsButton1Clicked = "0";
    return view();
}

Note - you can set the hidden value true/false. I have given the idea to solve it.

Upvotes: 1

Krupesh Kotecha
Krupesh Kotecha

Reputation: 2412

Try this

var flag = 0;
$("#btn1").click(function() {
  flag = 1;
  $("[id*=btn2]").click();
});

$("#btn2").click(function(e) {
  if (flag == 1) {
    flag = 0;
    alert("from btn1");
  } else {
    alert("from btn2");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="Submit" value="Add" id="btn1" />
<input type="Submit" value="Add2" id="btn2" />

Upvotes: 0

Aju John
Aju John

Reputation: 2234

Use code like this : Changed the button from submit to button. Now HTML will look like this:

<form id="myForm">
    ....
    ....
    <input type="button" value="Add" id="btn1"/>
    <input type="button" value="Add2" id="btn2"/>
</form>

Then the script:

var btn1_cliked = false;
$("#btn1").click(function () {
               $(this).attr("name","btn1");
               btn1_cliked = true;
               $("[id*=btn2]").click();
  });
$("#btn2").click(function () {
               if(btn1_clicked)
                   $("button[name='btn1']").removeAttr("name","btn1");
               $(this).attr("name","btn2");
               $("#myForm").submit();
  });

In controller:

Check if $_POST['btn1'] //then btn1 clicked
          else          // then btn2 clicked

Upvotes: 0

Related Questions