Web/JS&JQuery
[JQuery] 유효성 체크할 때 form 태그 submit 막기
커피맛스누피
2021. 3. 10. 22:13
stackoverflow.com/questions/30076248/jquery-each-loop-return-false-not-end-the-function
jquery each loop return false not end the function
I have a function which get a dot seperated string and parse it to array. And I want to loop these array elements and check a value is greater than 255 and return false, if not continue to function
stackoverflow.com
문제상황
- 콜백함수 안에서 false를 return해도 submit이 되어버린다.
해결
$(document).ready(function(){
$("#writeForm").submit(function(){
var rv = true;
// 유효성 검사
$.each($("input, textarea"), function(){
if($(this).val() === null || $(this).val() === ' ' || $(this).val().length === 0){
alert('입력이 유효하지 않습니다...');
return rv = false;
}
})
return rv;
});
});
콜백함수에서 변수를 갱신하고, submit 함수에서는 그 변수를 return하도록 한다.