javascript - jQuery if/else statement to change css on click -


$('#submitbtn').on("click", function() {     $('.message-box').val();     var message = $(".message-box").val();     $('#visible-comment').html(message);     $('.message-box').hide();   return false; }); 

i want above code in if/else condition if value of .message-box empty string change border color of .message-box red.

could please guide me in right direction?

i've tried following, changes border red, doesn't fire rest of code.

    $('#submitbtn').on("click", function() {    if ($(".message-box").val("")) {     $(".message-box").css("border","2px solid red");   } else {      $('.message-box').val();     var message = $(".message-box").val();     $('#visible-comment').html(message);     $('.message-box').hide();   return false;   } }); 

sample here : https://jsfiddle.net/wf69c7uu/2/

the idea check conditions, , add or remove class based on evaluation of expression.

here working demo

the code following:

$('#submitbtn').on("click", function() {     $('.message-box').val();     var message = $(".message-box").val();     if (message === '') {         $('.message-box').addclass("invalid");     }     else {       $('.message-box').removeclass("invalid");       $('#visible-comment').html(message);       $('.message-box').hide();     }   return false; }); 

or, optionally, can check input in "real-time" user types so:

$('#submitbtn').on("click", function() {     $('.message-box').val();     var message = $(".message-box").val();     if (!$(".message-box").hasclass("invalid")) {       $('#visible-comment').html(message);       $('.message-box').hide();     }   return false; });  $(".message-box").on("input propertychange", function () {     var $this = $(this);     if (!$this.hasclass("invalid") && $this.val() === '') {     $this.addclass("invalid");   }   else if ($this.hasclass("invalid") && $this.val() !== '') {     $this.removeclass("invalid");   } }); 

Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -