As a beginner in Javascript and jQuery, I am struggling to understand why my code is behaving the way it does.
I have written two similar functions aimed at changing the background color of an input field. The objective is to set the background color of the input field to #00FF7F
when something is typed into the field. If nothing is typed, the background should be transparent.
Javascript Code:
$(document).ready(function () {
var $input1 = $("#logindata1");
var $input2 = $("#logindata2");
function onChangeInput1() {
$input1.css("background-color", "#00FF7F");
var value = $.trim($(".form-control").val());
if (value.length === 0) {
$input1.css("background-color", "transparent");
}
}
function onChangeInput2() {
$input2.css("background-color", "#00FF7F");
var value = $.trim($(".form-control").val());
if (value.length === 0) {
$input2.css("#background-color", "transparent");
}
}
$input1.on("keyup", onChangeInput1);
$input2.on("keyup", onChangeInput2);
});
CSS:
#loginbox {
width: 400px;
height: 200px;
margin-left: auto;
margin-right: auto;
margin-top: 25%;
}
.logindata {
margin-left: auto;
margin-right: auto;
margin-top: 20px;
height: 60px;
width: 290px;
transition: 0.25s ease;
}
.form-control {
margin-left: auto;
margin-right: auto;
height: 55px;
width: 288px;
border-style: none;
background-color: transparent;
text-align: center;
border: solid 2px #00FF7F;
transition: 0.25s ease;
font-size: 25px;
font-family: "Trebuchet MS";
}
... (additional CSS properties)
Simple HTML:
<!DOCTYPE html>
(HTML code)
To see how the Username and Password fields react differently, try typing into both on the provided jsbin link.
You can view images showing the different reactions by following this link: https://i.sstatic.net/RFHs1.jpg
I believe there might be a more efficient way to streamline my javascript/jQuery code using a single function that each input field calls, rather than having a separate function for each.