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

Creating a Nested DataTable: A Step-by-Step Guide

My data structure includes a nested dict presented as follows: var dataSet = [{"s_group": [{"range_name": null, "name": "XXXXXXXXXXXX"}], "configfile": "XXXXXXXXXXX", "src_port": ["0-65535"], ...

Using AngularJS to manage cookies along with arrays

I am passing my data in this way $cookies.putObject("currentLocation,values,allLocList", obj, vm.tempData, vm.allLocationList); The objects obj and vm.tempData are being sent as objects, while vm.allLocationList is an array that contains a JSON object. W ...

The transparency of an image is being lost when it is used in a modal

I am facing an issue when trying to append a modal that contains only a transparent gif. The problem arises when the transparent background of the gif is not displayed properly. There seems to be no issue with the transparency settings of the gifs themselv ...

Issue with Clicking on Table Rows in JQuery (Specifically in Internet Explorer)

The script functions perfectly in Firefox and Opera browsers. $(document).ready(function() { $('#mainTable tr').each(function() { $(this).on("click",( function () { ...

Potential Performance Issue with Material UI's withStyles Function

I've been given the task of optimizing the loading speed of a page in our react redux web app. When the page load action is triggered, there seems to be a slight freeze lasting about half a second. After checking the profiler, everything seems fine ...

Display a pop-up window upon clicking anywhere on the webpage using jQuery and HTML

Is it possible for me to create a pop-up window that opens a specific website when a user clicks anywhere on the page, similar to pop-up companies? Can this be achieved using HTML, JavaScript, and jQuery? Any help would be greatly appreciated. ...

Using Django, CSS, and Javascript, create a dynamic HTML form that shows or hides a text field based on the selection

How can I hide a text field in my Django form until a user selects a checkbox? I am a beginner in Django and web applications, so I don't know what to search for or where to start. Any guidance would be appreciated. Here is the solution I came up wi ...

CodeIgniter: Bootstrap disables become enabled once validation is completed

My modifuser views have a disabled input field set to hold the id value. <?php echo form_open('user/updateuser'); ?> <legend>Update User</legend> <div class="form-group"> <label for="id">ID</label> ...

Newbie React Developer Struggling to Implement Material-UI Example in React Project, State Functioning Differently from Hooks

I am currently in the early stages of learning React and trying to create a form for a project management web application. For this, I am using material-ui library. I referred to one of the select box component examples from the material-ui documentation ...

How can you save the output of console.log in JavaScript to a variable and then use that variable in HTML?

Here is the code snippet I've been working on. The first part consists of JavaScript code, and the second part includes HTML. $('#table').on('check.bs.table', function (e, row) { checkedRows.push({First: row.fname, Second: row ...

What is the process for creating a linked TreeNode in the Ant tree design?

After completing a tree design utilizing Ant Design, I encountered an issue where certain nodes within the tree needed to act as links. Despite my attempts to directly assign links, they were not functioning properly. array.map((node) => { if(node.t ...

Cross-Origin Resource Sharing (CORS) verification for WebSocket connections

I am currently utilizing expressjs and have implemented cors validation to allow all origins. const options = { origin: ['*'], credentials: true, exposedHeaders: false, preflightContinue: false, optionsSuccessStatus: 204, methods: [&a ...

Hold off on refreshing the page until all the $.get calls have finished executing

I am currently using a piece of JavaScript to execute an Ajax call which returns XML data. This XML is then processed, and another Ajax call is made for each "record" found in the XML to delete that record. However, I am facing an issue where the JavaScrip ...

What is the best way to display a variable from a function located outside of the public http folder in PHP?

I am attempting to create a registration form using Ajax. I have a script that calls a registration function located in an includes folder outside of the public html folder. The output of this function should be alerted, but when I click the button, the al ...

AngularJS has the ability to handle the value of one input based on the value of another input

How can I ensure that if one input has a value, the other must also be filled in AngularJS? I'm looking for the best approach to handle this requirement in an angular way. Any suggestions? Below is my code: <div class="form-group recipe_item" ng ...

Choosing bookmarkable views in Angular 5 without using routes

I'm currently working on a unique Angular 5 application that deviates from the standard use of routes. Instead, we have our own custom menu structure for selecting views. However, we still want to be able to provide bookmarkable URLs that open specifi ...

Prevent the routing on page reload in AngularJS

My route provider setup looks like this: app.config(function ($routeProvider, $locationProvider){ $locationProvider.hashPrefix(''); $routeProvider .when('/', { templateUrl: 'login.html', controller: 'loginCtrl&a ...

Leveraging AngularJs by binding ng-model to data from a JSON

Below is the code for a dropdown selection: <h3>Selectize theme</h3> <p>Selected: {{produk.category}}</p> <ui-select ng-model="produk.category" theme="selectize" ng-disabled="disabled" style="width: 300px;"> <ui-se ...

Using the same ng-model to show distinct values in two separate input fields

I have a form with a dropdown list that loads data using the ng-model="placeid". When a user selects an option from the dropdown, I want to display the selected place's latitude (place.lat) in an input box. Here is the dropdown list code: <select ...

Issues arise when submitting the form on a web page with an MVC 4 partial view, causing the page

Scenario: I am currently working on a C#/MVC 4 project where I have a view that includes a partial view. The main view consists of a form with a submit button, and the partial view is initially hidden but can be displayed by selecting a checkbox. Problem: ...