Altering the color of a div based on a specified value condition

I am in need of assistance with a div structure similar to this:

<div id="namacoc" tabindex="1" class="filled-text" placeholder="Input your name" contenteditable ></div>
<div id="position" tabindex="1" class="filled-text" placeholder="Input your position" contenteditable></div>    
<button type="button" id="btncontinue" class="btn btn-wide btn-blue">Continue</button>

My issue revolves around validating the div elements. For example: If the namecoc div does not have a value, I want it to change color to red. Once a value is inputted, the color should return to its normal state (black) when the user selects another div or presses a button.

NOTE: I opted for a div instead of an input form because Bootstrap was not changing the text background color on active states. Therefore, I decided to use a div element. Please excuse any language errors as English is not my primary language.

Answer №1

My recommendation is to stick with using input only, as content editable can present compatibility issues across various browsers.

Here's a suggested approach.

$("#btncontinue").click(function() {
  $("input").each(function() {
    $.trim($(this).val()) == "" ?
      $(this).addClass("invalid") : $(this).removeClass("invalid");
  });
});

$("input").on("blur", function() {
  $.trim($(this).val()) == "" ?
    $(this).addClass("invalid") : $(this).removeClass("invalid");
});
.invalid {
  border: red 1px solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="namacoc" tabindex="1" class="filled-text" placeholder="Input your name" contenteditable></input>
<input id="position" tabindex="1" class="filled-text" placeholder="Input your position" contenteditable></input>
<button type="button" id="btncontinue" class="btn btn-wide btn-blue">Continue</button>

Answer №2

Array.prototype.forEach.call(document.querySelectorAll(".filled-text"), function (node) {
  node.onfocus = function () {
    this.className += " active";

    var text = this.innerHTML;

    if ((this.id === "namacoc"  && text === "Enter your name") ||
        (this.id === "position" && text === "Enter your position")) {

      this.innerHTML = "";
    }
  };

  node.onblur = function () {
    this.className = this.className.replace(" active", "");

    if (this.innerHTML === "") {
      if (this.id === "namacoc") {
        this.innerHTML = "Enter your name";
      } else {
        this.innerHTML = "Enter your position";
      }

      this.className = this.className.replace(" normal", "") + " empty";
    } else {
      this.className = this.className.replace(" empty", "") + " normal";
    }
  };
});
.filled-text {
  width: 200px;
  padding: 8px;
  margin: 24px 0;
  border: 1px solid #000;
}

.filled-text.placeholder {
  color: #d0d0d0;
}

.filled-text.empty {
  color: red;
}

.filled-text.active,
.filled-text.normal {
  color: #000;
}
<div id="namacoc"  class="filled-text placeholder" contenteditable>Enter your name</div>
<div id="position" class="filled-text placeholder" contenteditable>Enter your position</div>

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

While attempting to import modules in Visual Studio Code, an error message appears stating "Unexpected token {"

Greetings! I am currently using Visual Code to run my project and would like to share my code with you. In the file external.js: export let keyValue=1000; In the file script.js: import {keyValue} from './external.js'; console.log(keyValue); ...

Show and hide menu items without automatically scrolling the user back to the top of the page

I am currently working on a project where I have an image button that toggles between expanding and collapsing a menu using JavaScript. The issue I am facing is that every time the button is clicked, it takes the user back to the top of the page. My goal ...

Slide up using jQuery to the left direction

I am looking to design a weekly calendar that slides the old week left or right when switching to a new week. Does anyone have any suggestions on how I can implement this feature? I'm currently struggling to come up with a good solution. Any help is ...

Div with sidebar that sticks

I am currently working on setting up a website with a sticky sidebar. If you would like to see the page, click this link: On a specific subpage of the site, I am attempting to make an image Validator sticky, but unfortunately, it's not functioning a ...

The resource being requested is missing the 'Access-Control-Allow-Origin' header - Issue with Pinterest OAuth implementation

While working on implementing OAuth for Pinterest, I successfully retrieved the access code. However, when attempting to perform a GET /v1/me/ request, I encountered an error in the Chrome console: XMLHttpRequest cannot load . No 'Access-Contro ...

This is my first experience with Flask and I am encountering an issue with the POST method

Recently, I began my journey of learning Flask and encountered a seemingly simple task: creating a button, capturing the name, and displaying it on the screen. Despite my efforts, the code doesn't seem to be working as expected. It's now been two ...

Establishing a proxy server to support the development of a Create React application

Recently, I initiated a react application with the help of create-react-app. Following that, I executed the npm run eject script to unlock access to all files. Subsequently, I incorporated express and crafted a server.js file which is located on the same l ...

Ways to widen the header to fit the entire page?

I'm having trouble stretching my header to fill the entire page. I've tried using margin-left and right, but it's not working as expected. My Header CSS: background: green; height: 70px; width: 100%; display: flex; just ...

Tips for guaranteeing blocking within a loop in Node.JS

While I usually enjoy the asynchronous nature of Node.JS and its callback-soup, I recently encountered an issue with SQLite that required a certain part of my code to be run in a blocking manner. Despite knowing that addressing the SQLite problem would mak ...

Challenge encountered while processing JSON data

I've searched through various threads and tutorials, but I'm still stuck on this issue! I have two JSON responses that need to be utilized in separate functions: 1st (single element) Need to extract "Intention_category" and "count" Data: { " ...

The Jquery AjaxStop event fails to trigger, but AjaxStart works perfectly

While I was working with APIs, I encountered a roadblock. I have a Jquery function that retrieves data from an API. To prevent a "reposition" effect, I need the function to wait until all calls are made before triggering another function to place all the ...

Challenges encountered in converting JSON objects into an HTML table

My goal is to convert a JSON object into an HTML Table using the following code: JSONSelect.forEach(selecRow, options, function (queryResult) { var sem = $.trim(JSON.stringify(queryResult, null, ' ')); console.log(sem); $.getJSON(&ap ...

Comparing Flash and jQuery for RIAs development: Which tool reigns supreme and why?

Could someone clarify which technology is more suitable for developing rich internet applications: Flash or jQuery? Consider aspects like pros and cons, time, cost, and different scenarios. Please provide detailed explanations as it can be quite confusin ...

What is the process for choosing an element that is embedded within another element?

I'm attempting to apply a red border class to an image located inside another div, using data attribute. I've completed the first part of this task, here's my code: HTML: <div class="delivery-method col-lg-5"> <div class="letter r ...

Implementing event handlers for Revolution Slider through a loop

Currently, I am working with the Revolution Slider plugin on my Wordpress site. One of the features of Rev Slider is its API that allows for changing slides or listening for events. Beneath the slider wrapper, I am dynamically inserting a link to each slid ...

Showing pictures from a database utilizing PHP and HTML

I'm looking to showcase the images stored in my database within an HTML table. The files are saved as 'BLOB' and I want them to appear under the 'Photo' column. Can anyone guide me on the code needed to display these images? ...

What is the best way to ensure a div is always scrollable?

I am currently working with Angular 4 and Bootstrap 4 (alpha 6). I have implemented ngx-infinte-scroll to fetch data from the server when the user scrolls to the top or bottom of the div. The issue I am facing is that the user can only scroll when there ar ...

What is the best way to fetch a UniqueID using document.getElementById()?

I am looking to utilize the __doPostBack JavaScript function. __doPostBack(obj.UniqueID,''); The challenge I'm facing is that I only have the ClientID of my object - ctl00_cpholder_myObjId document.getElementById("ctl00_cpholder_myOb ...

Pass a variable value as a parameter to a jQuery function using code-behind

Within my code behind, I am retrieving the [IDphoto] from an SQL database. My goal now is to pass this IDphoto as a parameter to a jQuery function upon onClick. How can I achieve this? Code behind sb.AppendFormat("<a onclick='popup()' href=& ...

Implementing Keycloak Policies to Secure a Node.js API

Hello everyone, this is my first time reaching out for help here so please bear with me if I miss out on any important information or make some mistakes. Apologies in advance for the lengthy text. Summary of My Objective (I might have misunderstood some ...