본문 바로가기
IT창고/PHP

checkbox array jquery ajax html, php 코드

by 창구창고 2023. 2. 8.
반응형

사진출처: unsplash

<form>
  <label for="fruits">Select your favorite fruits:</label><br><br>
  <input type="checkbox" name="fruits" value="apple"> Apple<br>
  <input type="checkbox" name="fruits" value="banana"> Banana<br>
  <input type="checkbox" name="fruits" value="mango"> Mango<br>
  <input type="checkbox" name="fruits" value="grapes"> Grapes<br><br>
  <button type="button" id="submit-button">Submit</button>
</form>

 

$(document).ready(function() {
  $("#submit-button").click(function() {
    var selectedFruits = [];
    $("input[name='fruits']:checked").each(function() {
      selectedFruits.push($(this).val());
    });
    
    $.ajax({
      type: "POST",
      url: "process-fruits.php",
      data: {fruits: selectedFruits},
      success: function(response) {
        $("#response").html(response);
      }
    });
  });
});

 

<?php
  $fruits = $_POST['fruits'];
  echo "You selected the following fruits:<br>";
  foreach ($fruits as $fruit) {
    echo "- $fruit<br>";
  }
?>
반응형

"이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다."