I have the following function in javacritps, but I want to be able to add a condition if the Order is with yes, the checkbox remainsdisable
function MuestraDatos(Valor) {
data = JSON.parse(Valor);
var indice = 0;
//alert("entra a mostrar");
$.each(data, function(index, value) {
/* Vamos agregando a nuestra tabla las filas necesarias */
indice = indice + 1;
$("#TablaCargaOP").append("<tr>" +
"<td>" + value.OP + "</td>" +
"<td>" + value.Item + "</td>" +
"<td>" + value.CodPza + "</td>" +
"<td>" + value.Desc + "</td>" +
"<td data-name='Cantidad' class='Cantidad' data-type='text'>" + value.CantPzas + "</td>" +
"<td>" + value.QueNivel + "</td>" +
"<td>" + value.Pedido + "</td>" +
"<td>" + if (value.Pedido == 'SI') {
" <div class='form-check'><input type='checkbox' disable class='form-check-input' id='Escoge"+indice+"' name='Escoge'/>" + " <label class='form-check-label' for='Escoge"+indice+"'></label></div></td>"
} else {
" <div class='form-check'><input type='checkbox' class='form-check-input' id='Escoge"+indice+"' name='Escoge'/>" + " <label class='form-check-label' for='Escoge"+indice+"'></label></div></td>"
} +
"</tr>");
});
$('#TablaCargaOP').ddTableFilter();
}
I get the following error
SyntaxError: expected expression, got keyword 'if'
you have a syntax error on the line
To solve it, you have two alternatives, one is to finish concatenating the
string
, then evaluate the condition, and then add (or not) what is missing.Otherwise, the other option would be to use a ternary operator (which I assume is the closest to what you want to do)
It would be something like this.
Cheers
Try the following, which is to define outside with
if
whichtd
corresponds to assign the string to a variable and then concatenate it.Your problem is given because in a string addition operation (concatenation) you cannot include an if statement, since it only expects an operand that can be another string, a number, a function or a variable. To solve this, if you look carefully, the only difference between the text that you include when the condition is met and when it is not met is that in the first case you add or remove the disabled attribute to the checkbox, therefore you can do the following, like this you avoid repeating unnecessary code.
The problem is that you are trying to concatenate a
if
with text strings. Your code should be as follows:The expression
(value.Pedido == 'SI' ? 'disable' : '')
refers to a ternary operator , which is used to evaluate conditionals on a single line (very useful in cases like yours).Cheers!