I have an element that returns a value of either true
or false
when I run $('#myId').val()
.
Once true or false is returned, I want to have a particular div
change its background color to green for true or red for false.
if ($('#myId').val())
{
code should return a div with text and green background
}
else
{
code should return a div with text and red background
}
I'd say do a default green background class and then us an override class to add the red background. Your code would look something like this:
if ($('myId').val())
{
$('myId').addClass('falseClass');
} else {
$('myId').removeClass('falseClass');
};
Use CSS to add the background colors, like so:
.divClass{
background: green;
}
.divClass.falseClass{
background: red;
}
If you want to add a div with some specific text (say to whatever 'myId' marks), and then change the color, you can add the div first.
$('<div class="divClass">').appendTo('myId').text('foo')
if ($('myId').val())
{
$('myId').addClass('falseClass');
} else {
$('myId').removeClass('falseClass');
};
You have to convert the string to a bool to evaluate properly. I have a button in the fiddle to return the value.
HTML:
<div id="myDiv">
<input id="myID" value="false"/>
<input id="myBtn" type="button" value="submit"/>
</div>
JQuery:
$('#myBtn').on('click', function () {
$('#myDiv').css('background', (($('#myID').val() == "true") ? 'green' : 'red'));
});
<script type="text/javascript">
if ($('#myId').val()){
showDiv("green");
}else{
showDiv("red");
}
function showDiv(color){
var text = "Hello world";
return "<div class=\""+color+"\">"+text+"</div>";
}
</script>
<style>
.green{
background-color:green;
}
.red{
background-color:red;
}
</style>
This worked best for me:
if ($('#myID').val()) {
$('#SOMECLASS').text('Some Text').css('background-color', 'green');
else
$('#SOMECLASS').text('Some Text').css('background-color', 'red');
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.