Jquery 입력 배열 필드 가져 오기
여기에서 비슷한 질문을 찾았지만 아무것도 작동하지 않습니다.
다음과 같은 입력이 있습니다.
<input type="text" value="2" name="pages_title[1]">
<input type="text" value="1" name="pages_title[2]">
다음과 같은 필드를 얻으려고합니다.
$('input[name="pages_title[]"]')
그러나 빈 결과가 있습니다 :(
모든 필드를 얻는 방법? 나는 그것을 얻을 수 있습니다$('input[name="pages_title[1]"]')
선택 자로 시작 사용
$('input[name^="pages_title"]').each(function() {
alert($(this).val());
});
참고 : @epascarello와 동의하여 더 나은 솔루션은 요소에 클래스를 추가하고 해당 클래스를 참조하는 것입니다.
이것은 보통 체크 박스와 라디오 버튼에서 작동하지만 각 이름은 동일해야합니다.
<input type="text" value="2" name="pages_title[]">
<input type="text" value="1" name="pages_title[]">
var x = $('input[name="pages_title[]"]').val();
즉, 쉼표로 구분 된 값으로 모든 필드를 가져 오는 "가정"입니다. 텍스트 상자로 시도한 적이 없으므로 보장 할 수 없습니다.
@John이 언급했듯이 : 반복합니다. $('input[name="pages_title[]"]').each(function() { var aValue = $(this).val(); });
편집 : 항상 OP 질문에 답하기 위해 필요한 것은 아니며 때로는 더 나은 방법을 가르쳐야합니다. (거만하게 들리면 죄송합니다)
주석 : 입력 정의
<input type="text" value="1" name="pages_title[1]">
<input type="text" value="2" name="pages_title[2]">
배열을 깨고 각 입력에는 고유 한 이름이 있으므로 더 이상 배열이 아닙니다.
map 메소드를 사용하여 배열에 저장된 입력 값을 얻을 수 있습니다.
var values = $("input[name='pages_title[]']").map(function(){return $(this).val();}).get();
start with selector 를 사용해야합니다.
var elems = $( "[name^='pages_title']" );
그러나 더 나은 해결책은 요소에 클래스를 추가하고 클래스를 참조하는 것입니다. 더 빠른 조회 이유입니다.
괄호 가 문자열로 처리 되도록 입력 이름을 작은 따옴표로 묶습니다.[]
var multi_members="";
$("input[name='bayi[]']:checked:enabled").each(function() {
multi_members=$(this).val()+","+multi_members;
});
다음과 같이 입력 텍스트 상자에 클래스 이름을 지정할 수 있습니다.
<input type="text" value="2" name="pages_title[1]" class="pages_title">
<input type="text" value="1" name="pages_title[2]" class="pages_title">
다음과 같이 반복하십시오.
$('input.pages_title').each(function() {
alert($(this).val());
});
가장 좋은 방법은 Propper Form을 사용하고 jQuery.serializeArray 를 사용하는 것 입니다.
<!-- a form with any type of input -->
<form class="a-form">
<select name="field[something]">...</select>
<input type="checkbox" name="field[somethingelse]" ... />
<input type="radio" name="field[somethingelse2]" ... />
<input type="text" name="field[somethingelse3]" ... />
</form>
<!-- sample ajax call -->
<script>
$(document).ready(function(){
$.ajax({
url: 'submit.php',
type: 'post',
data: $('form[name="a-form"]).serializeArray(),
success: function(response){
...
}
});
});
</script>
값은 PHP에서 $_POST['field'][INDEX]
.
다음과 같이 이중 백 슬래시로 대괄호를 이스케이프 할 수 있습니다.
$('input[name="pages_title\\[\\]"]')
포함 선택기를 사용할 수 있습니다.
[name*=”value”]: selects elements that have the specified attribute with a value containing a given substring.
$( document ).on( "keyup", "input[name*='pages_title']", function() {
alert($(this).val());
});
In order to select an element by attribute having a specific characteristic you may create a new selector like in the following snippet using a regex pattern. The usage of regex is intended to make flexible the new selector as much as possible:
jQuery.extend(jQuery.expr[':'], {
nameMatch: function (ele, idx, selector) {
var rpStr = (selector[3] || '').replace(/^\/(.*)\/$/, '$1');
return (new RegExp(rpStr)).test(ele.name);
}
});
//
// use of selector
//
$('input:nameMatch(/^pages_title\\[\\d\\]$/)').each(function(idx, ele) {
console.log(ele.outerHTML);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="2" name="pages_title[1]">
<input type="text" value="1" name="pages_title[2]">
<input type="text" value="1" name="pages_title[]">
Another solution can be based on:
[name^=”value”]: selects elements that have the specified attribute with a value beginning exactly with a given string.
.filter(): reduce the set of matched elements to those that match the selector or pass the function's test.
- a regex pattern
var selectedEle = $(':input[name^="pages_title"]').filter(function(idx, ele) {
//
// test if the name attribute matches the pattern.....
//
return /^pages_title\[\d\]$/.test(ele.name);
});
selectedEle.each(function(idx, ele) {
console.log(ele.outerHTML);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="2" name="pages_title[1]">
<input type="text" value="1" name="pages_title[2]">
<input type="text" value="1" name="pages_title[]">
Most used is this:
$("input[name='varname[]']").map( function(key){
console.log(key+':'+$(this).val());
})
Whit that you get the key of the array possition and the value.
참고URL : https://stackoverflow.com/questions/19529443/jquery-get-input-array-field
'Program Tip' 카테고리의 다른 글
헤드 라인에서 굵은 글씨를 제거하는 방법? (0) | 2020.11.07 |
---|---|
배치 파일의 현재 디렉토리를 찾고 경로에 사용하려면 어떻게합니까? (0) | 2020.11.06 |
Owin Twitter 로그인-유효성 검사 절차에 따라 원격 인증서가 유효하지 않습니다. (0) | 2020.11.06 |
런타임에 하위 클래스가 클래스의 인스턴스인지 확인하는 방법은 무엇입니까? (0) | 2020.11.06 |
변수, 객체 및 참조의 차이점은 무엇입니까? (0) | 2020.11.06 |