programing tip

jQuery를 사용하여 선택한 확인란의 값을 가져옵니다.

itbloger 2020. 10. 28. 07:48
반응형

jQuery를 사용하여 선택한 확인란의 값을 가져옵니다.


확인란 그룹 'locationthemes'를 반복하고 선택한 모든 값으로 문자열을 만들고 싶습니다. 따라서 확인란 2와 4를 선택하면 결과는 "3,8"이됩니다.

<input type="checkbox" name="locationthemes" id="checkbox-1" value="2" class="custom" />
<label for="checkbox-1">Castle</label>
<input type="checkbox" name="locationthemes" id="checkbox-2" value="3" class="custom" />
<label for="checkbox-2">Barn</label>
<input type="checkbox" name="locationthemes" id="checkbox-3" value="5" class="custom" />
<label for="checkbox-3">Restaurant</label>
<input type="checkbox" name="locationthemes" id="checkbox-4" value="8" class="custom" />
<label for="checkbox-4">Bar</label>

http://api.jquery.com/checked-selector/ 확인 했지만 이름으로 확인란 그룹을 선택하는 방법에 대한 예는 없습니다.

어떻게 할 수 있습니까?


jQuery에서 다음과 같은 속성 선택기를 사용하십시오.

$('input[name="locationthemes"]:checked');

이름이 "locationthemes"인 선택된 모든 입력을 선택하려면

console.log($('input[name="locationthemes"]:checked').serialize());

//or

$('input[name="locationthemes"]:checked').each(function() {
   console.log(this.value);
});

데모


에서 VanillaJS

[].forEach.call(document.querySelectorAll('input[name="locationthemes"]:checked'), function(cb) {
   console.log(cb.value); 
});

데모


ES6 / 확산 연산자에서

[...document.querySelectorAll('input[name="locationthemes"]:checked')]
   .forEach((cb) => console.log(cb.value));

데모


$('input:checkbox[name=locationthemes]:checked').each(function() 
{
   // add $(this).val() to your array
});

작동 데모

또는

jQuery의 is()기능 사용 :

$('input:checkbox[name=locationthemes]').each(function() 
{    
    if($(this).is(':checked'))
      alert($(this).val());
});


배열 매핑이 가장 빠르고 깨끗합니다.

var array = $.map($('input[name="locationthemes"]:checked'), function(c){return c.value; })

다음과 같은 배열로 값을 반환합니다.

array => [2,3]

성과 헛간이 확인되고 나머지는 확인되지 않았다고 가정합니다.


jquery의 map기능 사용

var checkboxValues = [];
$('input[name=checkboxName]:checked').map(function() {
            checkboxValues.push($(this).val());
});

$("#locationthemes").prop("checked")


You can also use the below code
$("input:checkbox:checked").map(function()
{
return $(this).val();
}).get();

So all in one line:

var checkedItemsAsString = $('[id*="checkbox"]:checked').map(function() { return $(this).val().toString(); } ).get().join(",");

..a note about the selector [id*="checkbox"] , it will grab any item with the string "checkbox" in it. A bit clumsy here, but really good if you are trying to pull the selected values out of something like a .NET CheckBoxList. In that case "checkbox" would be the name that you gave the CheckBoxList control.


Source - More Detail

Get Selected Checkboxes Value Using jQuery

Then we write jQuery script to get selected checkbox value in an array using jQuery each(). Using this jQuery function it runs a loop to get the checked value and put it into an array.

<!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <title>Get Selected Checkboxes Value Using jQuery</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $(".btn").click(function() {
                var locationthemes = [];
                $.each($("input[name='locationthemes']:checked"), function() {
                    locationthemes.push($(this).val());
                });
                alert("My location themes colors are: " + locationthemes.join(", "));
            });
        });
    </script>
    </head>
    <body>
        <form method="POST">
        <h3>Select your location themes:</h3>
        <input type="checkbox" name="locationthemes" id="checkbox-1" value="2" class="custom" />
        <label for="checkbox-1">Castle</label>
        <input type="checkbox" name="locationthemes" id="checkbox-2" value="3" class="custom" />
        <label for="checkbox-2">Barn</label>
        <input type="checkbox" name="locationthemes" id="checkbox-3" value="5" class="custom" />
        <label for="checkbox-3">Restaurant</label>
        <input type="checkbox" name="locationthemes" id="checkbox-4" value="8" class="custom" />
        <label for="checkbox-4">Bar</label>
        <br>
        <button type="button" class="btn">Get Values</button>
    </form>
    </body>
    </html>

var voyageId = new Array(); 
$("input[name='voyageId[]']:checked:enabled").each(function () {
   voyageId.push($(this).val());
});      

var SlectedList = new Array();
$("input.yorcheckboxclass:checked").each(function() {
     SlectedList.push($(this).val());
});

참고URL : https://stackoverflow.com/questions/11292778/use-jquery-to-get-values-of-selected-checkboxes

반응형