简体   繁体   中英

Combine 2 jquery functions

I would like to optimize this code below, but unsure how to od it, on pageload i wan't to check if my radio is true or false, and based on that result i wan't to send the corresponding postalcode to my ajax request. But if my postalcode is changed by the user i wan't to re-request the ajax, but can't it be done in a more "tidy" way?

 $("#PostalCode").live("change", function () {
    // check if change delivery is set 
    if ($('#radio-no').attr('checked')) {
        var postalCodeId = $(this).val();
        SetWebservice(postalCodeId);
    }
});

// Get delivery point from alternative location
$("#ShipPostalCode").live("change", function () {
    // check if change delivery is set 
    if ($('#radio-yes').attr('checked')) {
        var postalCodeId = $(this).val();
        SetWebservice(postalCodeId);
    }
});

// on page load run this ...
if ($('#radio-yes').attr('checked')) {
    var postalCodeId = $("#ShipPostalCode").val();
    SetWebservice(postalCodeId);
} else {
    var postalCodeId = $("#PostalCode").val();
    SetWebservice(postalCodeId);
}



function SetWebservice(postalCodeId) {
    if ($('#Webservice_1').length) {
        $.ajax({
            type: "POST",
            url: "/functions/api/postdk/controller.aspx",
            data: "postalCodeId=" + postalCodeId,
            success: function (data) {
                $('#Webservice_1').html(data);
            }
        });
    }
    if ($('#Webservice_2').length) {
        $.ajax({
            type: "POST",
            url: "/functions/api/gls/controller.aspx",
            data: "postalCodeId=" + postalCodeId,
            success: function (data) {
                $('#Webservice_1').html(data);
            }
        });
    }

}

there are numerous things you should adjust:

  1. live is deprecated -> use on instead
  2. don't check with "attr" use .is(":checked")
  3. you can have a selector in the "on" to apply an event to multiple dom elements

you can create function that does the "checking" and call it from the "on" and on load like this:

$(function(){
    var checkPostal = function() {
        if ($('#radio-yes').is(':checked')) {
            SetWebservice($("#ShipPostalCode").val());
        }
        // check if change delivery is set 
        if ($('#radio-no').is(':checked')) {
            SetWebservice($("#PostalCode").val());
        }
    }

    $(document).on("change", "#PostalCode,#ShipPostalCode", function() {
        checkPostal();
    });

    // on page load run this ...
    checkPostal();
});

Edit: You should try to avoid global event listeners like this if possible. So if the "#PostalCode" input is not "replaced" - you should rather use

$("#PostalCode,#ShipPostalCode").change(function()  ...)

Goal is to have one method examine the fields and trigger the call...

http://plnkr.co/edit/msIjZhJru0QJAr4Sh6L4

Script:

$( document ).ready(function() {
  var SetWebservice=function(postalCodeId){
    var url, resultToElId;
    if ($('#Webservice_1').length) {
      url="/functions/api/postdk/controller.aspx";
      resultToElId='Webservice_1';
    }else if ($('#Webservice_2').length) {
      url="/functions/api/postdk/controller.aspx";
      resultToElId='Webservice_2';
    }
    if(resultToElId){
      console.log('SetWebservice:',postalCodeId);
      $.ajax({
        type: "POST",
        url: "/functions/api/gls/controller.aspx",
        data: "postalCodeId=" + postalCodeId,
        success: function (data) {
            $('#'+resultToElId).html(data);
          }
      });
    }else{
     console.warn('SetWebservice: No call made for postacode:',postalCodeId);
    }
  };
  var updatePostalCode = function(el){
    // determine radio value (value is the input to get postal code from)
    var fieldId = $('input[name=rdo]:checked').val();
    var postalCodeId = $('#'+fieldId).val();
    SetWebservice(postalCodeId);
  };
  // setup listeners
  $("#PostalCode").on('change',updatePostalCode);
  $("#ShipPostalCode").on('change',updatePostalCode);
  $('input[type=radio][name=rdo]').on('change',updatePostalCode);
  // init on page load
  updatePostalCode();

});

Markup:

<div>
       PostalCode
        <input id="PostalCode" value='01234'>
     </div>
     <div>
       ShipPostalCode
        <input id="ShipPostalCode" value='98765'>
     </div>

    <div>
      radio-no:  
      <input name="rdo" type="radio" 
        id="radio-no" 
        value="PostalCode"
        checked="checked">
    </div>
    <div>
      radio-yes:  
      <input name="rdo" type="radio" 
        id="radio-yes" 
        value="ShipPostalCode">
    </div>

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