Kristin Vernon
Kristin Vernon

Reputation: 155

Applying a CSS style using JavaScript if text field is empty

I have this function in JavaScript which I called using an onclick event in my HTML code:

function checkTextField(field) {
if (field.value == '') {
    sheet.insertRule("input:focus {background: #fc9fff;}", 1);
  }
}

I've checked that the if statement works by using an alert statement within it instead of the insertrule, but it seems that the css is applied even though the value of the field is not empty. Is there anything else I can use?

Upvotes: 2

Views: 2910

Answers (4)

Christiaan Westerbeek
Christiaan Westerbeek

Reputation: 11157

You can go pure CSS using the :required and :invalid selector and setting the required attribute on the field.

<style>
   input:required:invalid { background: #fc9fff; }      
</style>

<input name="email" required />

Live version here: http://jsfiddle.net/devotis/z319pp1f/

I admit it's a bit hostile to start all required fields red.

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388406

The problem is when the check method is executed with an empty element, you are inserting a general rule for input:focus which is not removed when focus from the current element is removed.

A better option would be to use a class like

function checkTextField(field) {
    if (field.value == '') {
        field.classList.add('empty')
    } else {
        field.classList.remove('empty')
    }
}

then in your stylesheet

input.empty:focus {
    background: #fc9fff;
}

Upvotes: 3

Ondřej Doněk
Ondřej Doněk

Reputation: 529

I'm not sure if I fully understand your question but I've created test HTML file and that test works:

<html>
<head>
    <meta charset="UTF-8">
    <title>test</title>
    <style></style>
    <script>
var styleAlreadyAppended = false;
function checkTextField(field) {
    var sheet = document.styleSheets[0];
    if (field.value == '' && styleAlreadyAppended !== true) {
        sheet.insertRule("input:focus {background: #f30;}", 0);
        styleAlreadyAppended = true;
    }
    else if (field.value != '' && styleAlreadyAppended === true) {
        sheet.deleteRule(0);
    }
}
    </script>
</head>
<body>
    <div>
        <input id="testinput" type="text" value="">
        <button onclick="checkTextField(document.getElementById('testinput'))">test</button>
    </div>
</body>
</html>

Tested on FF36.

Upvotes: 0

Charbz
Charbz

Reputation: 536

maybe a better approach is to attach your function to onchange event like this

<input type="text" onchange="checkTextField" />

Upvotes: 0

Related Questions