Using jQuery, how do I force a visitor to scroll to the bottom of a textarea to enable the submit button?

此生再无相见时 提交于 2019-11-30 00:26:38

Something like this should work:

$('#terms').scroll(function () {
    if ($(this).scrollTop() == $(this)[0].scrollHeight - $(this).height()) {
        $('#register').removeAttr('disabled');
    }
});

Simply give terms an id, and set the register button to disabled in the html. I also made a little fiddle to show it working: http://jsfiddle.net/ETLZ8/

I recommend this rather, it handles zooming better.

$('#terms').scroll(function () {
    if ($(this).scrollTop() + $(this).innerHeight() +2 >= $(this)[0].scrollHeight) {
        $('#register').removeAttr('disabled');
    }
});

The +2 handles a few scaling scenarios when scrolltop+innerheight is marginally below scrollHeight (for some reason I am too lazy to work out).

ctlockey

Christian Varga's solution is absolutely correct, and can also be applied to a div. However, if you are using a div instead of a textarea, the div MUST NOT have any padding on it or it breaks.

My workaround for this was to place a div inside my styled div (with padding, rounded corners, and a border) to detect scrolling. So:

<div class="styled-div">
     <div id="terms">
          Lorem ipsum...terms text...
     </div>
</div>
<input type="submit" id="register" value="Register"/>

The only possible drawback to this approach is if you add padding to the containing div, the scrollbar appears on the inner div, which may not look good to some users.

Other answers work perfectly, but I've put together a sample using a slightly different approach, one that doesn't tie the ability to submit to the button being disabled, so that it can be mixed with other validators and such.

$(function(){

    var terms_were_scrolled = false;

    $('#terms').scroll(function () {
        if ($(this).scrollTop() == $(this)[0].scrollHeight - $(this).height()) {
            terms_were_scrolled = true;
        }
    });

    $('#terms_agreed').click(function( event ){
        if( !terms_were_scrolled ){
            alert('you must read all the way to the bottom before agreeing');  
            event.preventDefault();               
        }            
    });

});​

HTML:

<form action="#">
  <textarea id="terms" cols="100" rows="10">
      Lorem Ipsum ....
  </textarea>
  <br />
  <input type="checkbox" id="terms_agreed"/> I agree
  <br />
  <input type="submit">
</form>​

Use something like this inside the textarea:

onscroll="if(this.scrollTop+this.offsetHeight>=this.scrollHeight){/*enable the button*/}" 

But what if JS is disabled?

I would prefer a scrollable div with the submit-button at the bottom. The user can't click the button without scrolling at the end, no matter if JS is on or off.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!