Roberts Ĺ ensters Roberts Ĺ ensters - 1 year ago 52
CSS Question

Input icon disappears after validating

Basically i know my issue , but I don't know how to re-write it to make it work.

I have icon on the left side of the input field. Icon is created with background-image.

Also i have a validation for the input field. When validation is wrong, then input field change the background to red. It also removes the icon. How can I rewrite the code so the background changes , but also the icon stay there?

I want the icon the stay where it is.

Here is the

jfiddle
LINK

Answer Source

This is actually quite easy to fix. Instead of setting 'background' in your jquery, set 'background-color' like this:

$('#fname').blur(function(e) {
        if (validatefname('fname')) {
  $('#fname').css('background-color', '#e6f3d1');
        }
        else {
            $('#fname').css('background-color', '#ffa5a5');
        }
    });
    
    function validatefname(fname) {
    var a = document.getElementById(fname).value;
 var filter = (/^([a-zA-Z-+ ]+){3,}$/);
    if (filter.test(a)) {
        return true;
    }
    else {
        return false;
    }
}
div#first {
	max-width: 400px;
	height:auto;
	margin: 50px auto 0; 
	padding: 20px 25px; 
	background-color: #FFF;
	color: 	#333333;
	border: 2px solid #EEE; 
	border-radius: 5px; 
}

.form {
	text-align: center;
}

input#fname { 
	background-image: url('https://upload.wikimedia.org/wikipedia/commons/4/4d/8ball_20x20px.jpg');
	background-repeat: no-repeat;
	background-position: 6px;
	border: 1px solid #DADADA;
	margin: 5px 0;
	padding-left: 35px;
	width: 80%;
	height: 30px; 
	font-size: 14px;
    border-radius: 5px;
	-webkit-border-radius: 5px;	/* for I.E */
	-moz-border-radius: 5px; 	/* for Mozilla web browser*/
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="first">

			<div class="form">
			  
				  <input type="text" placeholder="First Name" id="fname" name="name" required="required" maxlength="45">

			</div>

</div>