I successfully use php implode fucnction to display drink types. Please see below code.
<?php
echo 'Type:';
$types = array();
if ($a == 1) {$types[] = 'Pepsi';}
if ($b == 1) {$types[] = 'Mirinda';}
if ($c == 1) {$types[] = '7up';}
echo implode(', ', $types);
?>
Now I need to do that with jquery i.e. create array using if statements and then join them. Could you help me to modify the code below to get the expected result.
$( "#view" ).html(
'<div>+
'Type:'+
(a == 1?"Pepsi, " :"") +
(b == 1?"Mirinda, " :"") +
(c == 1?"7up, " :"")+
'</div>');
I tried in this way but it did not work:
$( "#view" ).html(
'<div>+
'Type:'+
(a == 1?types[] = 'Pepsi' :types[] = '') + //syntax error
(b == 1?types[] = 'Mirinda':types[] = '') + //syntax error
(c == 1?types[] = '7up' :types[] = '')+ //syntax error
types.join(',');
'</div>');
To be honest I don't know what you're trying to do there, but the join function works without all the stuff around it.
var a = 1;
var b = 3;
var c = 1;
var types = [];
if (a == 1) types.push("Pepsi");
if (b == 1) types.push("Mirinda");
if (c == 1) types.push("7up");
$( "#view" ).html("Types: " + types.join(', '));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="view"></div>
</div>
Your question is not clear to me but if you want to use .join()
method then first you should have an array like below:
var a = b = c = 1, arr = [];
a = (a == 1) ? arr.push("Pepsi"):""; // push to array if true
b = (b == 1) ? arr.push("Coke"):""; // push to array if true
c = (c == 1) ? arr.push("7up"):""; // push to array if true
$('div').html('Types:'+ arr.join(', ')); // then join it here
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
</div>