How to implement conditional render in JS?
Below is the JS (jQuery) code of autocomplete's result function. You can see there's some lines where I print out <li>
s containing some data
properties (that come in as a result of automcomplete's AJAX call).
How could I rewrite this so that <li>
would be conditionally rendered based on whether the property contains any value being either int
or string
(not empty string or whitespace) or something else that can be represented as string
?
$(".clients-dropdown").result(function (event, data, formatted) {
if (data) {
// set the hidden input that we need for Client entity rematerialize
$(".client-id").val(data.client_id);
if (data.ClientName && data.Address1 && data.postalcode && data.postname) {
$(".client-address").html(
"<li>" + data.ClientName + "</li>" +
"<li>" + data.Address1 + "</li>" +
"<li>" + data.postalcode + " " + data.postname + "</li>"
);
$(".client-details").html(
"<li>" + data.PrettyId + "</li>" +
"<li>" + data.VatNo + "</li>" +
"<li>" + data.Phone + "</li>" +
"<li>" + data.Mobile + "</li>" +
开发者_如何学JAVA "<li>" + data.Email1 + "</li>" +
"<li>" + data.Contact + "</li>"
);
}
}
Also, for the AJAX call, should my server side action return null
when there's a null
for a property in the database or empty string?
Note sure if that's what you want.
$(".clients-dropdown").result(function (event, data, formatted) {
var new_li = function(data) {
$.trim(data) != "" ? "<li>" + data + "</li>" : ''
}
if (data) {
$(".client-id").val(data.client_id);
if (data.ClientName && data.Address1 && data.postalcode && data.postname) {
$(".client-address").html(
new_li(data.clientName) +
new_li(Address1) + ... // you get the idea
);
}
}
Make a function that will test the property for whitespace.
var getListItem = function(prop){
if(!!$.trim(prop))
return '<li>' + prop + '</li>';
return '';
};
$(".clients-dropdown").result(function (event, data, formatted) {
if (data) {
// set the hidden input that we need for Client entity rematerialize
$(".client-id").val(data.client_id);
if (data.ClientName && data.Address1 && data.postalcode && data.postname) {
$(".client-address").html(
getListItem(data.ClientName) +
getListItem(data.Address1) +
getListItem(data.postalcode + ' ' data.postname)
);
$(".client-details").html(
getListItem(data.PrettyId) +
getListItem(data.VatNo) +
getListItem(data.Phone) +
getListItem(data.Mobile) +
getListItem(data.Email1) +
getListItem(data.Contact)
);
}
}
精彩评论