0

I am trying to use jquery to change the border color of an element when it is not empty. From what I've looked up everything seems right, but I still can't seem to get it to work.

Here is my JS fiddle: https://jsfiddle.net/jessica_mather123/ez3tgnvc/1/

HTML

Text <input type="text">
<button>Click Me</button>

JQuery

$("button").on("click",function(){
    if($("[type='text']").val() == null){
        $(this).css("border","2px solid red");
    } 
});
Theodore K.
  • 5,058
  • 4
  • 30
  • 46
Jessica Mather
  • 133
  • 1
  • 11

2 Answers2

1

.val() method returns a array, null will be returned only when no match is found.

So you should change if($("[type='text']").val() == null) to if($("[type='text']").val() == "")

Updated Fiddle

Pugazh
  • 9,453
  • 5
  • 33
  • 54
0
  • You didn't include jQuery (see how in How to add jQuery to JSfiddle)
  • $(this) inside on click refers to the button, not the input. So you'd better replace it with $("input[type='text']")

So, a working demo would be something like this https://jsfiddle.net/ez3tgnvc/10/

$("button").on("click",function(){
    var input = $("input[type='text']");
    if(!input.val()){
        input.css("border","2px solid red");
    }
});

if(!input.val()) is true if input variable is empty, null or undefined.

Community
  • 1
  • 1
Theodore K.
  • 5,058
  • 4
  • 30
  • 46