SomeAnonymousPerson
SomeAnonymousPerson

Reputation: 3271

Call a function when I press a button

I'm quite new in Java script, so this question may be a bit basic. I have a web app develop on asp.net and I have a calendar. So at the moment every time I choose a date it automatically goes to the controller and to the model.

The problem is that I want to execute the event when I click on a button instead of when I click on a date. So here is my code so far:

  <div id="datePicker">
  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
  </div>
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
  <p>@Resources.Resources.Date: <input type="text" id="datepicker"></p>
  <script name="select_date" id="select_date">

  $(function selectDate() {
      intDate = Date;
      $("#datepicker").datepicker({
          defaultDate: "+1w",
          changeMonth: true,
          changeYear: true,
          numberOfMonths: 1,
          minDate: "01/01/2008",
          onClose: function (select_date) {
              //console.log(select_date);
              var date = $('#datepicker').val().toString();
              $.ajax('NewspaperDate', {
                  data: {
                      strDate: date
                  },
                  success: function (data, textStatus, jqXHR) {
                      //this will happen on success of request
                      $('#DataNewspaper').html(data);
                     // window.location = "NewspaperDate?strDate=" + date;
                  },
                  error: function () {
                      console.log("error handler when ajax request fails... ");
                  },

              });
          }
      });
  });

I know I need to change the onClose and call the function from a button, but I'm not able to make it work.

Upvotes: 0

Views: 64

Answers (1)

eisbehr
eisbehr

Reputation: 12452

No big problem. Just create a button and add a click event listener to it.

<button class="action" type="button">send</button>

You can use jQuery for it, what you actually have included in your page:

$(function() {
    // init datepicker
    $("#datepicker").datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        changeYear: true,
        numberOfMonths: 1,
        minDate: "01/01/2008"
    });

    // create a button event
    $("button.action").click(function() {
        $.ajax("NewspaperDate", {
            data: {
                strDate: $("#datepicker").val().toString()
            },
            success: function(response) {
                $("#DataNewspaper").html(response);
            }
        });
    });
});

And a hint: you should wrap your code in a jQuery ready state, like in my example above.

$(function() {
    // do your work, e.g use plugins or create event listener ...
});

Upvotes: 1

Related Questions