jQuery Puzzler for Claire!

3 posts by 2 authors in: Forums > CMS Builder
Last Post: February 20, 2015   (RSS)

By Perchpole - February 19, 2015

Hi, Claire -

Can you please help me with this jQuery puzzler?!

I am using this code to disable a submit button until the user adds a #title:

$(document).ready(function(){
    $('#title').is(function() {
      if(!$.trim(this.value).length) {
    $('#saveButton').attr("disabled", "disabled");
  }
});
$('#title').keyup(function() {
  if ($.trim($(this).text()) !== '') {
    $("#saveButton").removeAttr("disabled");
  }
}).keyup(function() {
  if (!$(this).text().length) {
    $('#saveButton').attr("disabled", "disabled");
  }
 });
});

It seems to work perfectly.

What I'd like to do is to extend this to ensure the user must also add some #content. I've tried all sorts of ways to do it but it just won't work. This what I came up with:

$(document).ready(function(){
  $('#title, #content').is(function() {
    if(!$.trim(this.value).length) {
      $('#saveButton').attr("disabled", "disabled");
    }
});
$('#title, #content').keyup(function() {
  if ($.trim($('#title').text().length > 0) && $.trim($('#content').text().length > 0)) {
    $("#saveButton").removeAttr("disabled");
  }
}).keyup(function() {
  if ($('#title').text().length == 0 || $('#content').text().length == 0) {
    $('#saveButton').attr("disabled", "disabled");
  }
 });
});

It doesn't work because the button will activate if you add either a #title or the #content. I want the button to remain disabled until the user adds both.

Can you help, please?

:0/

Perch

By Perchpole - February 20, 2015

Claire -

Thank you. This absolutely spot-on! :0)

I realised when implementing your solution that I was making a bit of an error. Both #title and #content are not input fields but contentEditable divs. For that reason I changed the top of your code to this:

var title = $('#title').text();  //not .val()
var content = $('#content').text(); //not .val()

I think this is correct. Either way it works beautifully.

Thanks, again.

:0)

Perch