0

I'm not really skilled with javascript and I want to add text to a div when a variabel is 1 or 0. I'm not sure if a function is necessary. I'm trying it like this:

var alertt = document.getElementById('Alert');

if(:="OUT_MachineActive": == 1) // Value that gives 1 or 0 
{
    alertt.style.backgroundColor = 'green';
    alertt.firstChild.data = "NO ERROR";
}
if(:="OUT_MachineActive": == 0)
{
    alertt.style.backgroundColor = 'red';
    alertt.firstChild.data = "ERROR!!! Shredder1 is off!";
}


</script>

the div

It's working but the text, I would like to have the text "Shredder1 is off!" on the 2nd line. Like this: ERROR!!!!
Shredder1 is off!

I already tried something like:

  alertt.firstChild.data = "ERROR!!!" + <br /> + "Shredder1 is off!";

But that isn't working.

1
  • If you need to change the entire HTML of the div, then you may want to use .innerHTML instead of .data. Using innerHTML will correctly interprete the "<br />". Commented Mar 9, 2015 at 9:17

2 Answers 2

1

You can use jQuery and do it.

var error = 1;
$showErr = $('#show-error');
if (error === 0) {
  $showErr.css('background-color', 'green');
  $showErr.html('No Error!');
} else {
  $showErr.css('background-color', 'red');
  $showErr.html('Error!<br>Some Text');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="show-error">
</div>

While using jQuery is optional it would make your development a lot easier.

The line break works here because I am passing it as a html string and that gets inserted into the DOM.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks fo the help Prathik! I already had the jquery in. But I didn't use it before. Do you maybe have a tip for a good javascript guide ?
Hi Bart, This is a pretty popular source for Javascript developer.mozilla.org/en-US/docs/Web/JavaScript/Guide and you can use learn.jquery.com for jQuery
0

var error = 1;
$showErr = $('#show-error');
if (error === 0) {
  $showErr.css('background-color', 'green');
  $showErr.html('No Error!');
} else {
  $showErr.css('background-color', 'red');
  $showErr.html('Error!<br>Some Text');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="show-error">
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.