본문 바로가기
JS, Jquery

동일한 name 속성을 가진 필드가 여러개일 때 쿼리를 보내는 방법

by Sein_ 2023. 10. 29.
728x90

1.여러개 생성되므로 여러 데이터 쿼리 전송을 위해 []배열화

쿼리는 name 값을 기준으로 보내지므로 같은 name이 여러개일 경우 name 을 배열화 시킨다.

배열화 방법은 name = "name[]" 과 같이 name 값 뒤에 [] 배열 괄호를 붙인다.

$("#billing-panel").html('');
billing_body += '<div class="form-group grip_billing_row">';
...

billing_body += '<div class="form-group">';
billing_body += '    <label class="i-checks control-label col-lg-offset-1">'
+ '<input type="checkbox" name="check_billing_create[]" value="1" checked><i></i>'
+ '빌링 자동생성'
+ '</label>'
+ '</div>'
+ '<div class="form-group">'
+ '<label class="i-checks control-label col-lg-offset-1">'
+ '<input type="checkbox" name="check_billing_complete[]" value="1" checked><i></i>'
+ '빌링 자동 결제 완료 처리(제휴사에서 결제 완료 처리를 한 경우에만 체크하세요)'
+ '</label><div class="line line-dashed b-b line-lg pull-in" style="margin-bottom: 0; padding-bottom: 10px;"></div>'
+ '</div>';

//빌링 html 추가
$("#billing-panel").append(billing_body);

 

2. 폼 요소의 데이터를 URL-encoded 문자열로 직렬화

let queryString = $("#submit_form").serialize();

 

3. Ajax 를 이용해 controller 에 전달

$.ajax({
                url: '비밀',
                type: 'POST',
                data: queryString,
                dataType: 'json',
                beforeSend: function () {
                    $("#spinner").show();
                }
            }).fail(function (request, status, error) {
                toastr.error($.parseJSON(request.responseText).message);
            }).done(function (result) {

                toastr.info(result.message);
                //window.location.href = result.url;
            }).complete(function () {
                $("#spinner").hide();
            });
        });

 

4. controller 에 전달된 결과 확인

controller 에서 해당 값을 받는 부분에 dd($request) 를 찍어본다.

크롬 브라우저의 개발자도구 > Network > Preview 에서 확인이 가능하다.

array:44 [ # app/Http/Controllers/비밀
  "booking_type" => ""
  "code_local" => ""
  "code_channel" => ""
  
  ...
  
  "billing_option_name" => array:2 [
    0 => "비밀"
    1 => "비밀"
  ]
  "billing_fee" => array:2 [
    0 => "비밀"
    1 => "비밀"
  ]
  "check_billing_create" => array:2 [
    0 => "1"
    1 => "1"
  ]
]

 

5. 배열화된 name 에 접근하는 방법

셀렉터 내에서 name 속성 값에 대괄호([])가 포함되어 있을 때는 이를 따옴표로 묶어야 합니다.

예시로 name="check_billing_create[]"를 가진 input 요소가 여러 개 있을 경우 jQuery로 해당 요소들 중 체크된 것이 있는지 확인하려면 $("input[name='check_billing_create[]']:checked") 형태의 셀렉터를 사용해야 합니다.

#javascript code

if ($("input[name='check_billing_create[]']:checked").length > 0) { 
	console.log("하나 이상의 check_billing_create[] 요소가 체크되어 있습니다."); 
}
else { 
	console.log("check_billing_create[] 요소가 체크되어 있지 않습니다."); 
    }