I have below input text field.
<label>User Type</label>
<input name="user_type" id="user_type" class="form-control" readonly/>
I need to change the background color of this textbox according to the text. From below code, I could get this done after clicking on the box.
if (data.userstatus == 'Active') {
$('#user_status').val(data.userstatus);
$("#user_status").focus(function() {
$(this).addClass("focused");
});
}
else {
$('#user_status').val(data.userstatus);
$("#user_status").blur(function() {
$(this).removeClass("focused");
});
}
Here is my CSS class.
.focused {
border: solid 1px red;
}
But I need to show the red color border without clicking. Further I need to change the background also to red color.
This textbox is inside a popup window. I need when someone opens the popup, to show red highligheted.
Can someone help me to improve my code?
update:
Here is the button which I use to open the dialog box.
<a type="button" href="#" style=" text-decoration-line: none; font-size: 15px;" name="edit" id="<?php echo $_SESSION["id"]; ?>" class="btn btn-info btn-xs edit_data" > <img src="./assets/images/logo.png" width="45" height="45" style="vertical-align:middle;"/> <?php echo htmlspecialchars($_SESSION["username"]); ?></a>
Here is the ajax class
$(document).ready(function(){
$('#add').click(function(){
$('#insert').val("Insert");
$('#insert_form')[0].reset();
});
$(document).on('click', '.edit_data', function(){
var row_id = $(this).attr("id");
$.ajax({
url:".userdetail.php",
method:"POST",
data:{row_id:row_id},
dataType:"json",
success:function(data){
if(data.userstatus=='Active'){
$('#user_status').val(data.userstatus);
$("#user_status").focus(function(){
$(this).addClass("focused");
});
}
else{
$('#user_status').val(data.userstatus);
$("#user_status").blur(function(){
$(this).removeClass("focused");
});
}
$('#employee_id_return').val(data.row_id);
$('#insert').val("Update");
$('#add_data_Modal').modal('show');
},
error: function(req, status, error) {
alert(req.responseText);
}
});
});
Advertisement
Answer
I think all you need to change is to move $(this).addClass("focused");
outside the $("#user_status").focus(function(){
event handler, so you’re not waiting for the textbox to be focused before adding the class – and it’s the same when removing the class. Therefore you don’t need the “focus” and “blur” event handlers at all:
if (data.userstatus == 'Active') {
$('#user_status').val(data.userstatus);
$(this).addClass("focused");
}
else {
$('#user_status').val(data.userstatus);
$(this).removeClass("focused");
}