I am trying to get the value from a data file with nested objects.
I want to create a label for each entry that i have under the EN object. So I would like to end up having a "mail" label a "quote" label and a "phone" label.
In the label I want to put the content of tabLabel and tabIcon by accessing it.
With Object.Keys() i can see the strings but when I try to console.log them I get undefined.
I did this function but is not working:
function generateLabel() {
const keys = Object.keys(TabFormData.EN);
for (let i = 0; i < keys; i += 1) {
return `
<div class="${ID}_tab-form__headerItemWrap">
<label for="taLabel-here"><i class="tabIcon-here"></i></label>
</div>
`;
}
}
This is the data:
const TabFormData = {
EN: {
mail: [
{
tabLabel: 'Email Our Team',
tabIcon: 'fa fa-envelope',
},
{
label: 'First Name',
type: 'text',
name: 'name',
required: true,
hint: 'Please, provide your Name.',
},
{
label: 'Last Name',
type: 'text',
name: 'surname',
required: true,
hint: 'Please, provide your Last Name.',
},
{
label: 'Email Address',
type: 'email',
name: 'email',
required: true,
hint: 'Please, provide a valid email.',
},
{
label: 'Your Message',
type: 'textarea',
required: true,
name: 'message',
hint: 'Write us a message.',
rows: 20,
cols: 50,
},
{
label: 'About You',
required: true,
select: [
'Home use',
'Business use',
'Freelance, professional',
],
},
],
quote: [
{
tabLabel: 'Request a Quote',
tabIcon: 'fa fa-file-invoice-dollar',
},
{
label: 'First Name',
type: 'text',
name: 'name',
required: true,
hint: 'Please, provide your Name.',
},
{
label: 'Last Name',
type: 'text',
name: 'surname',
required: true,
hint: 'Please, provide your Last Name.',
},
{
label: 'Phone Number',
type: 'number',
name: 'telephone',
required: true,
hint: 'Please, provide a valid number',
},
{
label: 'Email Address',
type: 'email',
name: 'email',
required: false,
hint: 'Please, provide a valid email.',
},
{
label: 'Your Message',
type: 'textarea',
required: false,
name: 'message',
hint: 'Write us a message.',
rows: 20,
cols: 50,
},
{
label: 'About You',
required: true,
select: [
'Home use',
'Business use',
'Freelance, professional',
],
},
],
call: [
{
tabLabel: 'Call Me Back',
tabIcon: 'fa fa-phone',
},
{
label: 'First Name',
type: 'text',
name: 'name',
required: true,
hint: 'Please, provide your Name.',
},
{
label: 'Last Name',
type: 'text',
name: 'surname',
required: true,
hint: 'Please, provide your Last Name.',
},
{
label: 'Phone Number',
type: 'number',
name: 'telephone',
required: true,
hint: 'Please, provide a valid number',
},
{
label: 'About You',
required: true,
select: [
'Home use',
'Business use',
'Freelance, professional',
],
},
],
},
IT: {
},
};
Your problem is in the loop.
for (let i = 0; i < keys; i += 1)
In here you're checking if i is less than an array object, which is not what you want.
You want to compare i against the number of items in the array.
So that would become this:
for (let i = 0; i < keys.length; i += 1)
Your string literal is also wrong, ID in this case is an undefined variable. I assume you want the name of the key. For this issue it should become:
<div class="${keys[i]}_tab-form__headerItemWrap">
Also, once you return from the for loop, it'll automatically break on the first iteration (meaning you'll always get only one item). What you could do is build your whole string first then return it.
That would make your function become:
function generateLabel() {
const keys = Object.keys(TabFormData.EN);
var str = "";
for (let i = 0; i < keys.length; i += 1) {
str +=
`<div class="${keys[i]}_tab-form__headerItemWrap">
<label for="taLabel-here"><i class="tabIcon-here"></i></label>
</div>
`;
}
return str;
}
Here's a Fiddle.
If I understand correctly, you are looking something like this:
let cb = (v) => `<div class="${v[0]}"><label for="${v[1][0]['tabLabel']}"><i class="${v[1][0]['tabIcon']}"></i></label></div>`
Object.entries(TabFormData['EN']).map(cb);
Object.keys() returns the only the keys of the object, however it seems that you want to access the values as well. So, in your case Object.entries() is preferred.
I recommend to read the link below:
https://javascript.info/keys-values-entries
As reported by #Adriani6, you have issues in the loop, but to actually answer your question, here's how to access the nested objects:
function generateLabel() {
const keys = Object.keys(TabFormData.EN);
for (let i = 0; i < keys.length; i += 1) {
let currentTabObject = TabFormData.EN[keys[i]];
console.log(currentTabObject[0].tabLabel);
console.log(currentTabObject[0].tabIcon);
}
}
Assuming you assign TabFormData.EN to a variable called data and the Object.keys result of TabFormData.EN to a variable called keys, you can use:
${keys[i]} to retrieve the name and append it to your div classname,
${data[keys[i]][0].tabLabel} to retrieve the tabLabel property value and append it to your <label> tag, and
${data[keys[i]][0].tabIcon} to retrieve the tabIcon property value and append it to your <i> tag.
You can ignore the <hr> tags, the <button> tag and the rendered <div> tags and just check the object property references in the code snippet below if you want. They are just there for illustrating the code results in the jsFiddle and the code snippet below:
/* JavaScript */
var x = document.getElementById('abc');
var btn = document.getElementById('btn');
function generateLabel() {
const data = TabFormData.EN;
const keys = Object.keys(data);
for (let i = 0; i < keys.length; i += 1) {
x.innerHTML += `
<hr>
<div class="${keys[i]}_tab-form__headerItemWrap">
<label for="${data[keys[i]][0].tabLabel}">
<i class="${data[keys[i]][0].tabIcon}-here">
class of this div is ${keys[i]}_tab-form__headerItemWrap, label for this is ${data[keys[i]][0].tabLabel} and icon is ${data[keys[i]][0].tabIcon}
</i>
</label>
</div>
<hr>`
}
}
btn.addEventListener('click', generateLabel);
const TabFormData = {
EN: {
mail: [
{
tabLabel: 'Email Our Team',
tabIcon: 'fa fa-envelope',
},
{
label: 'First Name',
type: 'text',
name: 'name',
required: true,
hint: 'Please, provide your Name.',
},
{
label: 'Last Name',
type: 'text',
name: 'surname',
required: true,
hint: 'Please, provide your Last Name.',
},
{
label: 'Email Address',
type: 'email',
name: 'email',
required: true,
hint: 'Please, provide a valid email.',
},
{
label: 'Your Message',
type: 'textarea',
required: true,
name: 'message',
hint: 'Write us a message.',
rows: 20,
cols: 50,
},
{
label: 'About You',
required: true,
select: [
'Home use',
'Business use',
'Freelance, professional',
],
},
],
quote: [
{
tabLabel: 'Request a Quote',
tabIcon: 'fa fa-file-invoice-dollar',
},
{
label: 'First Name',
type: 'text',
name: 'name',
required: true,
hint: 'Please, provide your Name.',
},
{
label: 'Last Name',
type: 'text',
name: 'surname',
required: true,
hint: 'Please, provide your Last Name.',
},
{
label: 'Phone Number',
type: 'number',
name: 'telephone',
required: true,
hint: 'Please, provide a valid number',
},
{
label: 'Email Address',
type: 'email',
name: 'email',
required: false,
hint: 'Please, provide a valid email.',
},
{
label: 'Your Message',
type: 'textarea',
required: false,
name: 'message',
hint: 'Write us a message.',
rows: 20,
cols: 50,
},
{
label: 'About You',
required: true,
select: [
'Home use',
'Business use',
'Freelance, professional',
],
},
],
call: [
{
tabLabel: 'Call Me Back',
tabIcon: 'fa fa-phone',
},
{
label: 'First Name',
type: 'text',
name: 'name',
required: true,
hint: 'Please, provide your Name.',
},
{
label: 'Last Name',
type: 'text',
name: 'surname',
required: true,
hint: 'Please, provide your Last Name.',
},
{
label: 'Phone Number',
type: 'number',
name: 'telephone',
required: true,
hint: 'Please, provide a valid number',
},
{
label: 'About You',
required: true,
select: [
'Home use',
'Business use',
'Freelance, professional',
],
},
],
},
IT: {
},
};
/* CSS */
<!-- HTML -->
<button id="btn">
Click Me
</button>
<div id="abc"></div>
I am trying to add input fields in chaining modals (queue) using sweet alerts.
Reference http://www.inetcnx.net/sweetalert/index.html#chaining-modals
Problem: I want to add validation on each input field. Lets say; to make it required field, therefore user must need to enter value in input before proceeding to next step.
Code:
$('body').on('click','.apt_action',function() {
swal.setDefaults({
input: 'text',
confirmButtonText: 'Next →',
showCancelButton: true,
animation: true,
progressSteps: ['1', '2', '3']
})
var steps = [
{
title: 'Customer Name',
inputId: "customer_name",
inputPlaceholder: "Write something"
},
{
title: 'Sales Person',
text: 'Product sold by?'
},
{
title: 'Additional Details',
text: 'Coments or additional notes'
},
]
swal.queue(steps).then(function (result) {
swal.resetDefaults()
swal({
title: 'All done!',
html:
'Your answers: <pre>' +
(result) +
'</pre>',
confirmButtonText: 'Lovely!',
showCancelButton: false
})
}, function () {
swal.resetDefaults()
})
});
Js Fiddle :https://jsfiddle.net/mvohq23z/3/
Just add a preConfirm function block at each step you want to validate and do the validation using the variable value as you wish. Call the resolve() method for success or the reject('text error description here') to display an error message and prevent the chain modal to proceed to the next step.
Here's an example using your code in order to make all the input fields required:
JSfiddle here: https://jsfiddle.net/davidtoledo/ymb38u6t/1
swal.setDefaults({
input: 'text',
confirmButtonText: 'Next →',
showCancelButton: true,
animation: true,
progressSteps: ['1', '2', '3']
});
var steps = [
{
title: 'Customer Name',
inputId: "customer_name",
inputPlaceholder: "Write something",
preConfirm: function(value)
{
return new Promise(function(resolve, reject)
{
if (value) {
resolve();
} else {
reject('Please type something in the step 1!');
}
});
}
},
{
title: 'Sales Person',
text: 'Product sold by?',
preConfirm: function(value)
{
return new Promise(function(resolve, reject)
{
if (value) {
resolve();
} else {
reject('Please type something in the step 2!');
}
});
}
},
{
title: 'Additional Details',
text: 'Coments or additional notes',
preConfirm: function(value)
{
return new Promise(function(resolve, reject)
{
if (value) {
resolve();
} else {
reject('Please type something in the step 3!');
}
});
}
},
];
swal.queue(steps).then(function (result) {
swal.resetDefaults();
swal({
title: 'All done!',
html:
'Your answers: <pre>' +
(result) +
'</pre>',
confirmButtonText: 'Lovely!',
showCancelButton: false
})
}, function () {
swal.resetDefaults()
});
Cheers,
David Costa
I would like to implement a form inside of the sweet alert. I can put just one input inside, with title and body.
There is a way to customize the alert, docs says it, but is not allowed to load class css3 from my framework (customizecss.com) or from my style.css.
I'm trying to include a input inside of the alert, this way:
swal({
title: "HTML <small>Title</small>!",
text: "<input type='text'><label class='my-label'>Name</label>",
html: true
});
And it doesn't work, only show the label... why?
I wonder if there is some way to do it...
Thanks!
Sweet Alert -> https://github.com/t4t5/sweetalert
You can use this plugin in order to achive what you want:
https://github.com/taromero/swal-forms
It creates forms inside the modal in a syntax-fiendly manner:
swal.withForm({
title: 'More complex Swal-Forms example',
text: 'This has different types of inputs',
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: 'Get form data!',
closeOnConfirm: true,
formFields: [
{ id: 'name', placeholder: 'Name Field' },
{ id: 'nickname', placeholder: 'Add a cool nickname' },
{ id: 'password', type: 'password' },
{ name: 'sex', value: 'Male', type: 'radio' },
{ name: 'sex', value: 'Female', type: 'radio' },
{ name: 'skills', value: 'JS', type: 'checkbox' },
{ name: 'skills', value: 'Ruby', type: 'checkbox' },
{ name: 'skills', value: 'Java', type: 'checkbox' },
{ id: 'select',
type: 'select',
options: [
{value: 'test1', text: 'test1'},
{value: 'test2', text: 'test2'},
{value: 'test3', text: 'test3'},
{value: 'test4', text: 'test4'},
{value: 'test5', text: 'test5'}
]}
]
}, function (isConfirm) {
// do whatever you want with the form data
console.log(this.swalForm) // { name: 'user name', nickname: 'what the user sends' }
})
I know this is old, but I'll answer the question for all the web searchers out there:
You need to give an array as an argument, using an html property:
swal({
html: "<form action='verify.php' method='post'>
<input id='user' type='email'>
<input id='pass' type='password'>
<input id='idno' type='number'>
<submit>
</form>"});
Replace verify.php with whatever page you need the data in, and replace the string after html: with whatever HTML code you need.
The only downside is that people need to hit the submit-button on the form, and not SweetAlert's own button, although there might be a way to remove SweetAlert's own button too.
It looks like you can use a Sweet Alert with a type of 'input' (as opposed to 'error' or 'warning').
$window.swal({title: 'Text Entry', text: 'Put some text here, please.', type: 'input'});
From the Github README:
A prompt modal where the user's input is logged:
sweetAlert({
title: "An input!",
text: 'Write something interesting:',
type: 'input',
showCancelButton: true,
closeOnConfirm: false,
animation: "slide-from-top"
}, function(inputValue){
console.log("You wrote", inputValue);
});