d4ne d4ne - 7 months ago 17
Javascript Question

Change icon on if else statement in jQuery

I'm storing a value inside a javascript

variable
, now I want to run a
if
statement to change the
data-icon
on a
select option
.

<script type="text/javascript">
$(document).ready(function(){
$("#fds_gender").change(function () {
var gender = $(this).val();
$.ajax({
type: "POST",
data: {
"username" : "<?php echo $user->username; ?>",
"gender" : gender
},
url: "ajax/fds_categories_ajax.php",
success: function(data){
$("#fds_categories").empty();
$.each($.parseJSON(data), function(index, element) {
if(element.p == 0){
$("#fds_categories").append(
$('<option data-icon="man"></option>').val(element.id).html(element.name + ": " + element.pb + ' Zbucks')
);
}else{
$("#fds_categories").append(
$('<option data-icon="man"></option>').val(element.id).html(element.name + ": " + element.p + ' Zcard')
);
}
});
}
});
});
});
</script>


gender
does contains one of the following values: stud or babe.




What I want to create:

In case
gender
contains stud:

$('<option data-icon="man"></option>').val(element.id).html(element.name + ": " + element.pb + ' Zbucks')


In case
gender
contains babe:

$('<option data-icon="babe"></option>').val(element.id).html(element.name + ": " + element.pb + ' Zbucks')





What I have tested:

$('<option data-icon="' + if(gender == 'stud'){}else{} + '"></option>').val(element.id).html(element.name + ": " + element.pb + ' Zbucks')


Just got no clue how to
echo
out a
value
such as man or woman. Is there such a Javascript
echo
function as in PHP?

Answer

You can use ternary operator.

$('<option data-icon="' +( (gender == 'stud')?'man':'babe')+ '"></option>').val(element.id).html(element.name + ": " + element.pb + ' Zbucks')