开发者

Setting an attribute in Jquery not working

I have the following function which limits the amount of characters you can enter into a text area.

What's meant to happen is, if the text length is higher than the text limit, set an attribute of disabled="disabled" on the submit button, but it isn't getting set, my function code is as follows:

function limitChars(textid, limit, infodiv) {
        var text = $('#'+textid).val(); 
        var textlength = text.length;
        if(textlength > limit) {
            $('#' 开发者_JAVA技巧+ infodiv).html('You cannot write more then '+limit+' characters!');
            $('input#submit').attr('disabled', 'disabled');

        } else {
            $('#' + infodiv).html('You have '+ (limit - textlength) +' characters left.');

        }
    }

It's specifically the $('input#submit').attr('disabled', 'disabled'); bit that isn't working.

Any ideas?


Use $('input#submit').attr('disabled', true);. If you need to enable it again, use

.removeAttr('disabled');


I posted a demo and it appears to work with this code:

$(document).ready(function(){
 $('#test').keyup(function(){
  limitChars( this.id, 20, 'info')
 })
})

function limitChars(textid, limit, infodiv) {
 var text = $('#'+textid).val(); 
 var textlength = text.length;
 if(textlength > limit) {
  $('#' + infodiv).html('You cannot write more then '+limit+' characters!');
  $('input#submit').attr('disabled', 'disabled');
 } else {
  $('#' + infodiv).html('You have '+ (limit - textlength) +' characters left.');
  $('input#submit').removeAttr('disabled');
 }
}


Do you see your info message 'you cannot write more.....'?

Try and change your selector to ':input#submit'. Make sure the submit button's ID is "submit" and remember, IE is case sensitive.


if referencing by element id, just use $("#submit") is enough, I think


Your function works. How are you binding the textarea? You should be usign keyup:

$('#textarea').keyup(function() {
limitChars('textarea', 4, 'info');
});
limitChars('textarea', 4, 'info'); // run this initially as well
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜