0

I have a problem when I try to add a class in the catch statement.

When I click the button to confirm, javascript show me the error with the class successfully added, but when I reclick the button, without refreshing the page, the class added is no longer present.

function catchclass(){
    var result, x;
    result = document.getElementById("result");
    result.innerHTML = "";
    x = document.getElementsByTagName("input")[0].value;
    try { 
        if(x == "")  throw "is Empty";
    }
    catch(err) {
        result.innerHTML = "Input " + err;
        result.className += 'error';
    }
}
p.error {
    background: red;
    padding: 10px;
}
<input type="text" />
<button type="button" onclick="catchclass()">Test Input</button>

<p id="result"></p>

3 Answers3

2

It is appending the class error to the class that becomes 'errorerror' so CSS does not work.

result.className += 'error '; 

This should work for you or you can check before adding class that if it has the class error or not then add accordingly

Prabhat Rai
  • 799
  • 10
  • 12
0

Note: I haven't tested this

On error, you are appending the string 'error' to the className. This results in the following:

className == ''

error occurs

className == 'error'

error occurs

className == 'errorerror'

After the second error, the class name 'error' is no longer recognized. Since css classes are seperated by whitespace, you could fix this by prefixing your class name 'error' with a space:

result.className += ' error'; //note the space

Edit: I'd recommend using jQuery if you can

0

The problem is how you are adding classes. You keep adding them

result.className += 'error';

means it will be

errorerror

the second time it will run.

In modern browsers you can use element.classList.add(classnameToAdd)

result.classList.add("error");

function catchclass(){
    var result, x;
    result = document.getElementById("result");
    result.innerHTML = "";
    result.classList.remove('error');
    x = document.getElementsByTagName("input")[0].value;
    try { 
        if(x == "")  throw "is Empty";
    }
    catch(err) {
        result.innerHTML = "Input " + err;
        result.classList.add('error');
    }
}
p.error {
    background: red;
    padding: 10px;
}
<input type="text" />
<button type="button" onclick="catchclass()">Test Input</button>

<p id="result"></p>
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • Thanks man. You advise me to use `result.className = 'error';` or `result.classList.add("error");` –  Oct 13 '14 at 17:41
  • If you do `result.className = 'error'` you will override any other classes you may have added before. add() will just add it if it is not there and handles the case when there are or are not styles there. – epascarello Oct 13 '14 at 17:55