This solution could help you. I comment on the logic that I followed point by point:
- I used
$(function()
instead of document.ready
, which is obsolete since jQuery 3
- We are going to use a class that I have called
checkBoxes
for all the checkboxes. That will allow us two things: to . Put a single listener for all checkboxes, and .b deselect any other when a different one has been selected . This will prevent having more than one checkbox selected at a time. I think it would be desirable for this case.
- The color you want to establish must be a valid color (written in English). If you want to set a color using
azul
, rojo
, etc (as you were doing), it will not work. Since I do not know if you plan to use the attribute id
of the checkboxes for something else, I have used the attribute value
in each one, which would also be the most appropriate for this use. When selecting the checkbox, the value
is recovered (written in English) and is set as the color of the text.
- The code is optimized in this way. As you can see, the previous code was repetitive. For this type of cases it is better to group the elements by classes and then use
this
, to recover any attribute / value of the element that was clicked or changed and work with it. Imagine the code savings and what you gain in clarity, if they were 10 or 20 checkboxes instead of 3!
That way the code is simplified, optimized and does what you require.
$(function() {
$('input.checkBoxes').on('change', function() {
$('input.checkBoxes').not(this).prop('checked', false);
var cssColor = this.value;
var $elDiv = $("#noticia1");
$elDiv.css("color", cssColor);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="color1" value="red" class="checkBoxes"> ROJO
<input type="checkbox" id="color2" value="blue" class="checkBoxes"> AZUL
<input type="checkbox" id="color3" value="green" class="checkBoxes"> VERDE
<div id="noticia1">"Sed ut perspiciatis unde omnis"</div>