2014-09-26 5 views
0

JQuery와 쇼/숨기기 버튼 부양

function countChar(val) { 
 
    var len = val.value.length; 
 
    if (len == 0 || len == null) { 
 
     $('#sending').hide(); 
 
    } else if (len >= 500) { 
 
     val.value = val.value.substring(0, 500); 
 
    } else { 
 
     $('#char_no').text(len + "/500"); 
 
    } 
 
    };
<textarea id="txt" rows="10" cols="40" onkeyup="countChar(this)"></textarea> 
 
<div id="char_no">0/500</div> 
 
<input id="sending" type="submit" value="POST">

위, 그것은 TextArea를 포함 얼마나 많은 문자를 계산할 수 있습니다 내 자바 스크립트와 HTML하지만 나는이 경우 제출 '버튼을 숨기려면 사용자가 아무 것도 입력하지 않았거나 사용자가 뭔가를 입력했지만 모두 지웠습니다. 어떤 아이디어?

답변

1

toggle을 사용하여 버튼을 표시하거나 숨길 수 있습니다. 또한 마크 업 대신 자바 스크립트에서 이벤트를 추가하는 것이 좋습니다.

function countChar() { 
    if (this.value.length > 500) { 
     this.value = this.value.substring(0, 500); 
    } 
    var len = this.value.length; 
    $('#sending').toggle(!!len); // !! casts a boolean 
    $('#char_no').text(len + "/500"); 
}; 

$('#txt').on('input', countChar); 

함수 내에있는 this은 요소를 나타냅니다.

DEMO :http://jsfiddle.net/19sLaw7w/1/

0
<!-- HTML --> 
<textarea id = "myinput"></textarea> 
<button style = "display: none" id = "mybutton">Submit</button> 

이벤트 깔끔한 있습니다

// Pure JS 
var myinput = document.getElementById('myinput'); 
var mybutton = document.getElementById('mybutton'); 

myinput.onchange = function() 
{ 
    var charcount = myinput.value.length; 

    if(charcount == 0) 
    { 
     mybutton.style.display = 'none'; 
    }else{ 
     mybutton.style.display = 'inherit'; 
    } 
} 

// jQuery 
$('#myinput').on('change', function(){ 
    var charcount = $(this).val().length; 

    if(charcount == 0) 
    { 
     $('#mybutton').hide(); 
    }else{ 
     $('#mybutton').show(); 
    } 
});