Tom Maxwell
Tom Maxwell

Reputation: 9573

Enable/disable button on contentEditable keyup

I have a couple of divs on my website that utilize the HTML5 contentEditable attribute. The goal is for the user to be able to start writing a journal entry, and have the save button change from disabled to enabled.

Here's the HTML I have so far:

<div id="entry-create-partial">
  <div id="title-create-partial" name="title" contenteditable="true" data-placeholder='Title it' style="color:black"></div>
  <div id="content-create-partial" name="content" contenteditable="true" style="color:gray">Write anything</div>
  <button type="button" id="create-entry" class="btn" disabled="true">Save</button>
</div>

And here's the jQuery:

$(document).ready(function(){
    $('#title-create-partial').keyup(function(){
        if ($(this).value == '') {
            $('#create-entry').attr('disabled', 'disabled');
        } else {
            $('#create-entry').attr('disabled', false);
        }
    });
});

While this does work, it only checks on the first keyup; if the user backspaces and deletes everything they typed, the button doesn't disable itself again. Does anyone know why?

Upvotes: 1

Views: 3169

Answers (1)

dsgriffin
dsgriffin

Reputation: 68576

It's a <div> element not an <input>, so use text() instead of val() (and be sure to trim so it isn't enabled on whitespace). Also could use prop() to set the property instead of attr().

$('#title-create-partial').keyup(function(){
    if ($.trim($(this).text()) === '') {
        $('#create-entry').prop('disabled', true);
    } else {
        $('#create-entry').prop('disabled', false);
    }
});

jsFiddle here.

Upvotes: 3

Related Questions