0

So in a separate html form, I created a textarea (id: blog) and a button (id: final). I would like to disable that button when the length of the textarea is below 500, and enable it when such a length reaches at least 500. The following JS code, however, work only partially, such that the button is disabled at first (as the textarea starts off empty). It never gets enabled even after I type more than 500 characters into the textarea. Why is that?

/**
 * Enable the form button "Publish" once textarea in write.html reaches minlength="500"
 * https://stackoverflow.com/questions/13831601/disabling-and-enabling-a-html-input-button
 * https://stackoverflow.com/questions/18478336/jquery-if-certain-textboxes-are-empty-disable-button
 */
if ($("#blog").val().length < 500) {
    $("#final").attr("disabled", "disabled");
} else {
    $("final").removeAttr("disabled");
}
0

blogentry is the textarea object and does not have a length property. You probably want the length of the value property. There's a good description here.

I assume this code is in a function in a keypress or keydown event listener on the textarea element. Otherwise, how will it know when user has entered 500 characters real-time?

4
  • I revised my code a little bit as you instructed but it still is not working. The button does get disabled at first, but it is not enabled even after the length of the textarea exceeds 500. Please advise. @Dino
    – Alex Chan
    Jul 18 '17 at 5:39
  • Depends on when it runs. I assume it's in a function in a listener, as added to the answer, otherwise how does it keep track? Jul 18 '17 at 11:21
  • At first I thought some if conditions suffice. Why does it necessarily have to be some if conditions being called by a function? What are the differences between my code above (without a function) and putting my code inside a function? @Dino
    – Alex Chan
    Jul 19 '17 at 5:42
  • If the code is not in a function, it will run once. If it runs once before user has typed, length is always 0, button is always disabled. Jul 19 '17 at 11:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .