What is a good way to ignore the tags/variables in a jQuery HTML method?
For instance, if there was no value for company, it would not be included in the HTML.
$('.modal-body').html(`
<p><span style="font-weight:bold;">Name:</span> ${name}</p>
<p><span style="font-weight:bold;">Company:</span> ${company}</p>
<p><span style="font-weight:bold;">Job:</span> ${job}</p>
<p><span style="font-weight:bold;">Title:</span> ${title}</p>
<p><span style="font-weight:bold;">Phone:</span> ${phone}</p>
<p><span style="font-weight:bold;">Email:</span> ${email}</p>
<p><span style="font-weight:bold;">Event Loc:</span> ${addressResult}</p>
`)
CodePudding user response:
While I frown on using ternary operators for major control flow, inline conditionals are very useful for situations like this.
const name = "John Smith",
company = "1-800-Flowers",
job = "Software Developer",
title = undefined,
phone = "(123)-456-7890",
email = "[email protected]",
addressResult = "123 Big Street, Town, MA"
$('.modal-body').html(`
${name ? `<p><span style="font-weight:bold;">Name:</span> ${name}</p>` : ""}
${company ? `<p><span style="font-weight:bold;">Company:</span> ${company}</p>` : ""}
${job ? `<p><span style="font-weight:bold;">Job:</span> ${job}</p>` : ""}
${title ? `<p><span style="font-weight:bold;">Title:</span> ${title}</p>` : ""}
${phone ? `<p><span style="font-weight:bold;">Phone:</span> ${phone}</p>` : ""}
${email ? `<p><span style="font-weight:bold;">Email:</span> ${email}</p>` : ""}
${addressResult ? `<p><span style="font-weight:bold;">Event Loc:</span> ${addressResult}</p>` : ""}
`)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div ></div>
CodePudding user response:
You can use if statement like this:
let htmlContent = `<p><span style="font-weight:bold;">Job:</span> ${job}</p>`;
if(company) {
htmlContent = `<p><span style="font-weight:bold;">Company:</span> ${company}</p>`;
}
$('.modal-body').html(htmlContent);
Or using ternary operators like this:
$('.modal-body').html(`
${job ? `<p><span style="font-weight:bold;">Job:</span> ${job}</p>` : ''}
${company ? `<p><span style="font-weight:bold;">Company:</span> ${company}</p>` : ''}
`);
And also please change ${name} because it's a global variable.
CodePudding user response:
Not 100% sure where the customer info is coming from but if its an array of object, you can do something like the following.
const customers = [{
name: 'John Doe',
company: null,
job: 'Front-End Developer',
title: 'manager',
phone: '555-555-5555',
email: '[email protected]',
addressResult: null
}]
function getInfo(k, v){
return v !== null ? $('.modal-body').append(`<p><span style="font-weight:bold;">${k}:</span> ${v}</p>`) : null
}
$.each(customers, function(index, value){
$.each(value, function(i,v){
getInfo(i,v)
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div ></div>
CodePudding user response:
If your data is in the form of an array of objects (like a common JSON) and you need to display the data of a single object on a modal, you'll need to be able to select an object and extract the keys and values of said object (See Figure I)
Figure I
HTML
<!-- Simple modal with a unordered list. The <ul> will be the targeted element -->
<dialog>
<ul></ul>
</dialog>
jQuery/JavaScript
// Data source as an array of objects (simular to JSON)
const data = [
{ "keyA": "value1", "keyB": "value2" },
{ "keyA": "value3", "keyB": "" },
{ "keyA": "value5", "keyB": "value6" }
];
// Select object by index number and extract data
let index = 1; // Second object
function displayData(data, index) {
// Clear <ul>
$("ul").html("");
/* Convert object into an array of key/value pairs
|| keyValuePairs = [["keyA": "value3"], ["keyB", ""]];
*/
const keyValuePairs = Object.entries(data[index]);
// Add and format each key/value pair into <ul>
keyValuePairs.forEach(([key, value]) => {
// IF value exists...
if (value) {
$("ul").append(
`<li>
<b> // Same as <span style="font-weight: bold">
${key.charAt(0).toUpperCase() key.slice(1)}: // Capitalize key
</b>
${value}
</li>`
);
}
});
}
Result
<!--
Result is the data of the second object is displayed in <ul>
Note, keyB is excluded since it had no value
-->
<dialog>
<ul>
<li><b>KeyA:</b> value3</li>
</ul>
</dialog>
The following example is a live version of the code above with a <select>
that will allow you to change profiles.
Example
const profiles = [{
"name": "Lucille Blay",
"company": "Tambee",
"title": "Technical Writer",
"phone": "",
"email": "[email protected]",
"address": ""
}, {
"name": "Baudoin Macauley",
"company": "",
"title": "",
"phone": "877-812-9835",
"email": "[email protected]",
"address": "415 David Way"
}, {
"name": "Aurora Garside",
"company": "",
"title": "Nuclear Power Engineer",
"phone": "823-514-0402",
"email": "[email protected]",
"address": ""
}];
function displayProfile(profiles, index) {
$("ul").html("");
let data = Object.entries(profiles[index]);
data.forEach(([key, value]) => {
if (value) {
$("ul").append(
`<li>
<b>
${key.charAt(0).toUpperCase() key.slice(1)}:
</b>
${value}
</li>`);
}
});
}
/**
* For Demo Purposes Only [START]
*/
$("select").on("input", function(e) {
displayProfile(profiles, this.value);
this.value = "Pick Index Number";
$("dialog")[0].showModal();
});
$("button").on("click", function(e) {
$("dialog")[0].close();
});
// [END]
:root {
font: 300 2ch/1.2 "Segoe UI"
}
select {
padding: 4px;
font: inherit;
text-align: center;
}
dialog {
padding-top: 15px;
padding-right: 25px;
}
dialog::backdrop {
background: rgba(0, 0, 0, 0.4);
}
button {
position: relative;
top: -6px;
left: 16px;
float: right;
height: 1.2rem;
padding-bottom: 4px;
line-height: 1.1;
vertical-align: top;
cursor: pointer;
}
ul {
list-style: none;
margin-left: -30px;
}
<!-- For Demo Purposes Only [START] -->
<select>
<option selected>Pick Index Number</option>
<option>0</option>
<option>1</option>
<option>2</option>
</select>
<!-- [END] -->
<dialog>
<button>X</button>
<ul></ul>
</dialog>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>