Question

Currently when text area is focused on it expands it's height and the post and cancel button appear. Now I'd like to disable the submit button by default and only make it active once the text area has been typed into.

Later on I'll add opacity to the inactive submit button then take it away when the button is active just for a nice effect. But anyway I've tried applying disabled many ways and it doesn't work. I've tried various other things such as define a click function as well as submit then apply disabled using attr() to the disabled attribute of my form and it seems to have no effect.

HTML

        <div class="comment_container">
                    <%= link_to image_tag(default_photo_for_commenter(comment), :class => "commenter_photo"), commenter(comment.user_id).username %>

                    <div class="commenter_content"> <div class="userNameFontStyle"><%= link_to commenter(comment.user_id).username.capitalize, commenter(comment.user_id).username %> - <%=  simple_format h(comment.content) %> </div>
                </div><div class="comment_post_time"> <%= time_ago_in_words(comment.created_at) %> ago. </div>


           </div>


                    <% end %>
                <% end %>


            <% if logged_in? %>
            <%= form_for @comment, :remote => true do |f| %>
            <%= f.hidden_field :user_id, :value => current_user.id %>
            <%= f.hidden_field :micropost_id, :value => m.id %>
            <%= f.text_area :content, :placeholder => 'Post a comment...', :class => "comment_box", :rows => 0, :columns => 0 %>

    <div class="commentButtons">         
      <%= f.submit 'Post it', :class => "commentButton" %>
   <div class="cancelButton"> Cancel </div>
    </div>   
            <% end %>

            <% end %>

JQuery:

$(".microposts").on("focus", ".comment_box", function() {
    this.rows = 7;


    var $commentBox = $(this),
        $form = $(this).parent(),
        $cancelButton = $form.children(".commentButtons").children(".cancelButton");
       // $commentButton = $form.children(".commentButtons").children(".commentButton");
            $(this).removeClass("comment_box").addClass("comment_box_focused").autoResize();  
            $form.children(".commentButtons").addClass("displayButtons");

                $cancelButton.click(function() {
                    $commentBox.removeClass("comment_box_focused").addClass("comment_box");
                    $form.children(".commentButtons").removeClass("displayButtons");
                    $commentBox.val("");



                });

});

kind regards

Was it helpful?

Solution

Setting the disabled attribute doesn't work because if the disabled attribute is present, the field is disabled, regardless of the value of the attribute. You could use .removeAttr("disabled"), but it really makes the most sense to manipulate the disabled property which is more intuitive - it's just a boolean.

$commentButton.prop({ disabled: !$commentBox.val());

To be safe, bind to onkeyup, oninput, and onchange:

$commentBox.on("keyup input change", function () {
    $commentButton.prop({ disabled: !$commentBox.val() });
});

If you need to manually enable or disable the button, such as after clearing the form, you can pass true or false directly to a call to .prop().

$commentButton.prop({ disabled: true });




Edit: Detailed breakdown

The .prop() method

The .prop() method gets and sets property values on elements, similar to how .attr() gets and sets attribute values on elements.

Considering this jQuery:

var myBtn = $("#myBtn");
myBtn.prop("disabled", true);

We can re-write that in plain JavaScript like this:

var myBtn = document.getElementById("myBtn");
myBtn.disabled = true;

Why we don't need an if statement

The reason we don't need an if statement is that the disabled property takes a boolean value. We could put a boolean expression in an if statement, and then depending on the result, assign a different boolean expression as the value of the property:

if (someValue == true) {
    myObj.someProperty = false;
}
else {
    myObj.someProperty = true;
}

The first problem is the redundancy in the if statement: if (someValue == true) can be shortened to if (someValue). Second, the whole block can be shortened to a single statement by using the logical not operator (!):

myObj.someProperty = !someValue;

The logical not operator (!) returns the negated result of an expression - ie true for "falsey" values, and false for "truthy" values. If you aren't familier with "truthy" and "falsey" values, here's a quick primer. Any time you use a non-boolean value where a boolean is expected, the value is coerced to boolean. Values that evaluate to true are said to be "truthy" and values that evaluate to false are said to be "falsey".

 Type     Falsey values      Truthy values
 ———————— —————————————————— ——————————————————————
 Number   0, NaN             Any other number
 String   ""                 Any non-empty string
 Object   null, undefined    Any non-null object

Since an empty string evaluates to false, we can get a boolean indicating whether there is any text in the textarea by applying ! to the value:

var isEmpty = !$commentBox.val();

Or, use !! to do a double negation and effectively coerce a string value to boolean:

var hasValue = !!$commentBox.val();

We could rewrite the jQuery from above to a more verbose form in plain JavaScript:

var myBtn = document.getElementById("myBtn");
var myTextBox = document.getElementById("myTextBox");
var text = myTextBox.value;
var isEmpty = !text;
if (isEmpty) {
    myBtn.disabled = true;
}
else {
    myBtn.disabled = false;
}

Or, a little shorter, and more similar to the original:

var myBtn = document.getElementById("myBtn");
var myTextBox = document.getElementById("myTextBox");
myBtn.disabled = !myTextBox.value;

OTHER TIPS

You can try this:

var submit = $("input[type=submit]");
submit.attr("disabled","disabled");

$('textarea.comment_box').keyup(function() {
    if ( !$(this).val() ) {
       submit.attr("disabled","disabled");
    } else {
       submit.removeAttr("disabled");
    }
});

Here's a JS Fiddle so that you can try this out: http://jsfiddle.net/leniel/a2BND/

You can first disable your submit button, and if textarea has a value enable it:

<form id="yourForm">
<textarea id="ta"></textarea>
<input id="submit" type="submit" disabled="disabled">    
<form> 

$("#yourForm").change(function() {

  if ( $("#ta").val().length >= 1) {

    $("#submit").removeAttr("disabled"); 
  }

  else {

    $("input").attr("disabled", "disabled");

  }              

});

http://jsfiddle.net/dY8Bg/2/

You can achive this task using keyup event on text area. sample concept code below.

$("#textareaid").on('keyup', function (e) {
     Count_Chars(this);
});

function Count_Chars(obj) {
    var len = obj.value.length;
    if (len >= 1) {
        // do task
        // enable post button
    }
}

Added this to existing code to accomplish what I wanted. Marked answer that help me the most as winning answer and marked up others that helped.

commentButton = form.children(".commentButtons").children(".commentButton");

       commentButton.attr("disabled","disabled");

        commentBox.keyup(function() {
            if ( !$(this).val() ) {
               commentButton.attr("disabled","disabled");
            } else {
               commentButton.removeAttr("disabled");
            }
        });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top