Search code examples
jqueryasp.netasp.net-ajaxwebmethod

jQuery if statement inside web method


I am using a web method to autocomplete a textbox. I need some help for the jQuery to select a different url if a checkbox is checked.

The current selected url is the url: '<%=ResolveUrl("Default.aspx/GetInfo1") %>'. If chksel1 is checked it should be url: '<%=ResolveUrl("Default.aspx/GetInfo2") %>'

$(function() {
  $("[id$=txtA1]").autocomplete({
    source: function(request, response) {
      $.ajax({
        url: '<%=ResolveUrl("Default.aspx/GetInfo1") %>',
        data: "{ 'prefix': '" + request.term + "'}",
        dataType: "json",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        success: function(data) {
          response($.map(data.d, function(item) {
            return {
              label: item.split('-')[0],
              val: item.split('-')[1]
            }
          }))
        },
        error: function(response) {
          alert(response.responseText);
        },
        failure: function(response) {
          alert(response.responseText);
        }
      });
    },
    select: function(e, i) {
      $("[id$=hfA1]").val(i.item.val);
      $("[id$=hfA1]").attr("id", i.item.key);
    },
    minLength: 1
  });
});

Solution

  • Assuming chksel1 is the id of the checkbox, then you can use a ternary expression in the client-side JS to set the URL based on the state of the checked property:

    url: $('#chksel1').prop('checked') ? '<%= ResolveUrl("Default.aspx/GetInfo2") %>' : '<%= ResolveUrl("Default.aspx/GetInfo1") %>',