Home > Net >  jQuery multiple events including an IF statement
jQuery multiple events including an IF statement

Time:11-11

Does anybody know how to combine these two events in jQuery?

The closest I could get was having 2 duplicate scripts that respond to 2 different events, which in my opinion is absolutely terrible. But it's the only way I could think of to do this for now. Both scripts do the exact same thing (or A LOT of things actually). I know jQuery has an option to add multiple event handlers to the same element, but how does this work if one of the events contains an if condition?

This runs when the user clicks on a radio button in a radio group:

$(document).ready(function() {

  // When radio button is clicked
  $("input[name='select']").click(function() {
    var select = $("input[name='select']:checked").val();
    $.ajax({
      type: "POST",
      url: "script.class.php",
      data: { select: select },
      cache: false,
      success: function(data) {
        // A lot of things will happen here...
      },
      error: function(xhr, status, error) {
        console.error(xhr);
      }
    });
  });     
});

This runs IF the radio group already has a radio button selected:

$(document).ready(function() {

  // If value is already present
  if ($("input[name='select']:checked").val()) {
    var select = $("input[name='select']:checked").val();
    $.ajax({
      type: "POST",
      url: "script.class.php",
      data: { select: select },
      cache: false,
      success: function(data) {
        // The same things as in the previous script will also happen here...
      },
      error: function(xhr, status, error) {
        console.error(xhr);
      }
    });
  }
});

CodePudding user response:

Put all the common code in a function and then call it

$(document).ready(function() {

  // When radio button is clicked
  $("input[name='select']").click(commonCode);
  if ($("input[name='select']:checked").val()) {
    commonCode();
  }
  function commonCode(){  
    var select = $("input[name='select']:checked").val();
    $.ajax({
      type: "POST",
      url: "script.class.php",
      data: { select: select },
      cache: false,
      success: function(data) {
        // A lot of things will happen here...
      },
      error: function(xhr, status, error) {
        console.error(xhr);
      }
    });
  }     
});
  • Related