agiro agiro - 1 year ago 91
HTML Question

Color input's border when nothing is entered doesn't work

I have an input text that has to be something in it for the form to work.

So I wish to add some functionality to the

Confirm
button that checks if the input field is empty, and if so, recolor the border of that input.

I'm doing the following:



$(function mainListeners () {
"use strict";

var confirm = $('#addNewConfirm');
var cancel = $('#addNewCancel');
var eventBox = $('#eventname_input');
console.log("RUNS!!");
confirm.onclick = function (e) {
if (eventBox.val() == ''){
//so if we have an empty event
//recolor borders.
console.log("CHANGES!!");
eventBox.css('border-color','#d81919');
}else {

}
}


});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="yesno IFlexible">
<button id="addNewConfirm" >Confirm</button>
<button id="addNewCancel">Cancel</button>
</div>
<div >
<label>Event:</label>
<input id="eventname_input" type="text" />
</div>





Here I get no errors and I always see the
RUNS!!
message, so my script is attached. However, I never see the
CHANGES!!
message, so the condition
eventBox.val() == ''
is never true. I looked up the internet on how to check if an input text's text is empty, and this is what I found, and it clearly isn't working.

I'd like some help on sorting out this recolor of border if the input has no text.

Answer Source

Use JQuery click() function instead of onclick like so:

$(document).ready(function() {
  var confirm = $("#addNewConfirm");
  var cancel = $("#addNewCancel");
  var eventBox = $("#eventname_input");
  console.log("RUNS!!");
  confirm.click(function(e) {
    if (!eventBox.val()) {
      console.log("CHANGES!!");
      eventBox.css("border-color", "#d81919");
    } else {
      eventBox.css("border-color", 'inherit');
      // whatever you want
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="yesno IFlexible">
  <button id="addNewConfirm">Confirm</button>
  <button id="addNewCancel">Cancel</button>
</div>
<div>
  <label>Event:</label>
  <input id="eventname_input" type="text" />
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download