JQuery and checkbox trigger

时间:2019-03-19 15:06:28

标签: javascript jquery checkbox triggers

I want to use an existing checkbox in my form that invoke this function when it's checked (or clicked).

$(function() {
  var $residenza = $('#residenza');
  var $domicilio = $('#domicilio');
  var $capResidenza = $('#capResidenza');
  var $capDomicilio = $('#capDomicilio');

  function onChange() {
    $domicilio.val($residenza.val());
    $capDomicilio.val($capResidenza.val());
  };
  $('#residenza')
    .change(onChange)
    .keyup(onChange);
  $('#capResidenza')
    .change(onChange)
    .keyup(onChange);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

2 个答案:

答案 0 :(得分:0)

您可以这样做

// Using pure Javascript
function checkBoxClicked(check_box) {
    if (check_box.checked) {
        // Checkbox is checked, do something. Example call func sayHello()
        // sayHello();

    } else {
        // Checkbox is not checked do this instead
    }
}


// Using Jquery
var check_box = $("#check_box");

if (check_box.is(':checked')) {
    // Checkbox is checked, do something. Example call func sayHello()
    // sayHello();

} else {
    // Checkbox is not checked do this instead
}

function sayHello() {
    alert("Hello World!");
}

答案 1 :(得分:0)

你是说

$(function() {
  var $residenza = $('#residenza'),
      $domicilio = $('#domicilio'),
      $capResidenza = $('#capResidenza'),
      $capDomicilio = $('#capDomicilio'),
      onChange = function() {
       $domicilio.val($residenza.val());
       $capDomicilio.val($capResidenza.val());
      };


//  $('#residenza, #capResidenza').on("input", onChange);
  $(".address").on("input", onChange);
  $('#copy').on("click", onChange);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Residenza: <input type="text" id="residenza" class="address" /><br/> 
Domicilio: <input type="text" id="domicilio" class="address" /><br/>

<input type="checkbox" id="copy" /><br/> 
Cap Domicilio: <input type="text" id="capDomicilio" class="address" /><br/> 
Cap Residenza: <input type="text" id="capResidenza" class="address" /><br/>