A method for changing the background of a textbox based on a specific condition

I have an input text field below.

<label>User Type</label>
<input name="user_type" id="user_type" class="form-control" readonly/>

I am trying to change the background color of this textbox based on the text inside. The following code helps achieve this functionality 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");
  });
}

Below is the CSS class used for styling.

.focused {
  border: solid 1px red;
}

However, I want the red border and background color change to be visible without requiring a click. This textbox is inside a popup window, and I need it to be highlighted in red when the popup is opened.

If anyone can assist me in enhancing my code, I would greatly appreciate it.

update:

Here is the button 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 part of the script

$(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);      
                }   
           });  
      });  

Answer №1

To optimize this code snippet, we can streamline the process by moving the

$(this).addClass("focused");
command outside of the
$("#user_status").focus(function(){
event handler. By doing so, we eliminate the need to wait for the textbox to be focused before adding the class. The same applies to removing the class - it can also be moved outside of the event handlers. This adjustment eliminates the necessity for the "focus" and "blur" event handlers entirely:

if (data.userstatus == 'Active') {
  $('#user_status').val(data.userstatus);
  $(this).addClass("focused");
}
else {
  $('#user_status').val(data.userstatus);
  $(this).removeClass("focused");
}

Answer №2

Shift attention once the popup appears.

$( "#user_status" ).focus();

Answer №3

Do you want to make changes to the CSS of this element:

#user_type {
    border: solid 1px red;
}

#user_type.focused {
    background: red;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Background image animation with timed CSS3 transitions

Just dipping my toes into the world of CSS and HTML, but I'm getting the hang of it. Currently, I have a background image on my header section and I want to transform it into a slideshow featuring 3-4 images that rotate automatically. I've come ...

Tips for aligning a mesh on the X and Y axes in three.js

Currently, I am aligning objects/models (mesh) in my scene by using the mesh.geometry.center() function. This method helps position the object in the center based on its bounding box. For static objects with a fixed size, like a cardboard box for example ...

What is the best way to receive a user's input date in Dynamics 365 using HTML/JavaScript?

My HTML webform is set up to capture user input like address, card number, city, and state in text format. However, within Microsoft Dynamics 365, I have a custom entity with fields for this information. When a user completes the webform and submits it, a ...

It seems that the Bootstrap 4 Modal Pop up window is having difficulty closing

I recently completed a project on creating a matching game. After all the cards are successfully matched and the game finishes, a congratulatory modal pops up. However, I encountered an issue where the modal would not close after clicking the "Play Again" ...

The dimensions of the bottom border on left floating divs are inconsistent

One of my designers frequently uses a particular technique in various designs, and I'm struggling to determine the most effective way to style it with CSS so that it fluidly adapts (as it will be incorporated into a CMS). Essentially, when implementi ...

Understanding the ins and outs of utilizing the require function in React.js charts

I tried to test out this demo https://github.com/reactjs/react-chartjs Setup (I managed to complete this part) This component is designed for use with CommonJS only (like Webpack or Browserify) npm install --save react-chartjs You also need to have chart ...

What is the process for displaying a hidden div using a button?

I'm running into a problem with my project. Here is the code I've been using to hide my div element : @keyframes hideAnimation { to { visibility: hidden; } } To trigger the animation and hide the div after 6 seconds, I have implemented ...

Adjusting the height of one div to match the height of another div

I am facing a challenge in making a div (overlay) float over 3 other divs. It slightly overlaps the 1st (horsebanner) and 3rd (footer) divs while completely covering the 2nd (midbackground). My goal is to make the 2nd div automatically expand as the floati ...

Is it possible to implement a modal within my API services?

Hello, I am in need of assistance. I am looking to display a modal every time my API returns an error. Can someone please help me figure out how to achieve this? I am currently using React hooks. const restService = (path, responseType = 'json') ...

The 'background-size:cover' property does not function properly on iPad devices

Greetings! I have been working on developing a parallax website, and everything seems to be running smoothly across all browsers except for iPad. It appears that the background-size: cover property is not functioning properly on this device. Below is the ...

When using Bcrypt compare(), the result is consistently incorrect

After implementing this code for comparison, I encountered an issue with the compare password functionality. UserSchema.pre('save', async function() { const salt = await bcrypt.genSalt(10) this.password = await bcrypt.hash(this.password, ...

Preventing the mysql server called by php from running when the website is refreshed

My local website runs by querying a mysql database using inputs from an html form. The form values are passed to php via jQuery to execute the query. Is there a way to send a command to the mysql server to terminate the query if the web page is refreshed? ...

What steps do I need to take to ensure my app shows an error message instead of the broken image link?

function getDogImage(breed) { fetch(`https://dog.ceo/api/breed/${breed}/images/random`) .then(response => response.json()) .then(responseJson => displayResults(responseJson)) .catch(error => alert('Something went wrong. T ...

Entity Framework AJAX Delete Functionality Fails to Operate

I'm puzzled as to why this isn't working. Here's the code: View <input type="button" value="Delete" onclick="deletefunction(@item.PhotoId)"/> Controller [HttpPost] public ActionResult Delete(int photoid) { var imgDelete = db.Ph ...

Vue and axios join forces to send requests and showcase the outcomes

I am in the process of setting up a Vue application that will send a request to a backend and then showcase the response on the webpage. I created this example: new Vue({ data: { message: '{}' }, el: '.login-app', } ...

Change every occurrence of multiple forward slashes to only two forward slashes

Currently, I am working with Angular 2 using TypeScript. I have an input box in HTML that allows users to enter search terms, including REST resources like employee/getDetail. I need to replace / with // to prevent my service from failing. Additionally, e ...

Retrieving images from a PHP file using AJAX

My PHP page has links, and when a user clicks on the "gallery" link, I want the main div to display a grid of images. This is the code snippet of what I am currently attempting: let myRequest = new XMLHttpRequest(); myRequest.open("GET", "gallery.php", ...

jquery AJAX response displayed in plain text characters

After sending a pair of Chinese characters to my server: 忠孝 The web server then converts them into Pinyin: Zhōngxiào I confirmed that this conversion is working correctly by directly accessing the AJAX handler. The server is encoding everythi ...

Ways to create a unique animation for reducing the width of a div in a specific direction?

Currently, I have managed to animate the decrease in width of a div element. However, it is currently decreasing from right to left, and I would like it to decrease from left to right instead. Can someone please provide guidance on how to achieve this? ...

I am currently studying react.js and struggling to comprehend how the deployment process for a react app functions

Will the server only serve the index.html file or is there a way for the client to run that html file as it's not a regular html file? Do I need a backend node to make it work? I'm having trouble understanding the entire process. Normally, a cli ...