user6002037
user6002037

Reputation:

writing if/else statement as ternary operator

How would I write this using a ternary operator?

if (!$('#privacy_check').is(':checked')) {
  $('#privacy_check').css('outline-color', 'red');
  $('#privacy_check').css('outline-style', 'solid');
  $('#privacy_check').css('outline-width', 'thin');
} else {
  $('#privacy_check').css('outline-color', 'none');
  $('#privacy_check').css('outline-style', 'none');
  $('#privacy_check').css('outline-width', '0');
}

I have tried

!$('#privacy_check').is(':checked') ? $('#privacy_check').css('outline-color', 'red'); $('#privacy_check').css('outline-style', 'solid');$('#privacy_check').css('outline-width', 'thin') :
$('#privacy_check').css('outline-color', 'none');$('#privacy_check').css('outline-style', 'none');$('#privacy_check').css('outline-width', '0');

Upvotes: 0

Views: 90

Answers (4)

Pranav C Balan
Pranav C Balan

Reputation: 115222

You can do something like this

$('#privacy_check').change(function() {
  $(this).css({
    'outline-color': this.checked ? 'none' : 'red',
    'outline-style': this.checked ? 'none' : 'solid',
    'outline-width': this.checked ? '0' : 'thin'
  });
}).change()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="privacy_check" />


More simplified as @Rayon suggested

$('#privacy_check').change(function() {
  $(this).css("outline", this.checked ? 'none' : "thin solid red")
}).change()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="privacy_check" />

Upvotes: 0

Edward Pham
Edward Pham

Reputation: 83

Try this:

var $elem = $('#privacy_check');

if($elem.is(":checked")){
    $elem.css("outline", "thin solid red");
}
else{
   $elem.css("outline", "none");
}

Upvotes: 0

Rudolf Gr&#246;hling
Rudolf Gr&#246;hling

Reputation: 4825

var $elem = $('#privacy_check');
$elem.css($elem.is(':checked') ?
    { outlineColor: 'none', outlineStyle: 'none', outlineWidth: 0 } :
    { outlineColor: 'red', outlineStyle: 'solid', outlineWidth: 'thin' })

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

Simplify.

CSS:

#privacy_check {
    outline: thin solid red;
}
#privacy_check:checked {
    outline: none;
}

No JavaScript required.

Upvotes: 4

Related Questions