Web/JavaScript

[jQuery] 폼이란? (Forms)

돈기법 2022. 3. 28. 17:52

폼이란?

  • 서버로 데이터를 전송하기 위한 수단이다.

- .focus() | .blur() | .change() | .select()

<p>
<input type="text" />
<span></span>
</p>

<script>
    $("input").focus( function () {
    	$(this).next("span").html('focus');
    }).blur( function() {
    	$(this).next("span").html('blur');
    }).change(function(e){
    	alert('change!! '+$(e.target).val());
    }).select(function(){
    	$(this).next('span').html('select');
    });
</script>

input 엘리먼트에 focus가 갔을 떄 <span>focus</span>
input 엘리먼트에 focus가 사라졌을 때 <span>blur</span>
input 엘리먼트의 값이 변경되었을 때 alert창이 뜬다.
input 엘리먼트의 값이 선택됐을 때 <span>select</span>

 

- .submit() | .val()

<form action="javascript:alert('success!');">
    <div>
        <input type="text" />

        <input type="submit" />
    </div>
</form>
<span></span>

<script>
    $("form").submit( function() {
    	if ($("input:first").val() == "correct") {
    		$("span").text("Validated...").show();
    		return true;
    	}
    	$("span").text("Not valid!").show().fadeOut(1000);
    	return false;
    });
</script>

form 태그에 submit이 일어났을 때,

  • 만약 input 엘리먼트의 첫번째 = <input type="text" />의 값이 correct일 경우
    <span>Validated...</span>
    span 값을 변경하고 return true; 를 통해 submit이 완료된다. (form action 실행)

 

  • 만약 input 엘리먼트의 첫번째 = <input type="text" />의 값이 correct가 아닐 경우
    <span>Not valid!</span>
    span을 fadeOut()으로 보여준 후 return false; 에 의해 submit이 완료되지 않는다.