I'm trying to preserve Javascript context from an array. Is there any way to make this work? Or a more elegant way?
EXAMPLE:
<html>
<script type="text/javascript">
var rand = Math.floor(Math.random() * 6) + 1;
var i = Math.floor(Math.random() * 6) + 1;
var arr = ["'There are ' + i + ' dogs in the yard.'","'The other day I saw ' + i + ' pigs that one lake.'","'I can't believe there were ' + i + ' birds in your yard the other day.'","'Why were there ' + i + ' cats in my front yard?'","'There are ' + i + ' rabbits in the yard.'","'There are ' + i + ' snakes in the yard.'"];
document.getElementById('fudge').innerHTML = arr[rand];
</script>
<body>
<div id='fudge'></div>
</body>
</html>
Get rid of the outer double quotes.
var arr = [
'There are ' + i + ' dogs in the yard.',
'There are ' + i + ' pigs in the yard.',
'There are ' + i + ' birds in the yard.',
'There are ' + i + ' cats in the yard.',
'There are ' + i + ' rabbits in the yard.',
'There are ' + i + ' snakes in the yard.'
];
Update: Also, place your <script> somewhere below the fudge element. Currently the script is running before fudge exists.
If you want the strings to update with future updates to the variable, that won't work. You'd need to generate a new string.
You could make a function instead.
var animals = ['dogs','pigs','birds','cats','rabbits','snakes'];
function makeString() {
var animal = animals[Math.floor(Math.random() * animals.length)],
qty = Math.floor(Math.random() * 6) + 1;
return "There are " + qty + " " + animal + " in the yard.";
}
makeString(); // "There are 3 dogs in the yard."
You could also take care of the singular/plural grammar value when the qty is 1.
var animals = ['dog','pig','bird','cat','rabbit','snake'];
function makeString() {
var animal = animals[Math.floor(Math.random() * animals.length)],
verb = 'is',
qty = Math.floor(Math.random() * 6) + 1;
if (qty !== 1) {
animal += 's';
verb = 'are';
}
return "There " + verb + " " + qty + " " + animal + " in the yard.";
}
makeString(); // "There is 1 dog in the yard."
I assume that you want to use the variable i to create the strings, not just the letter i. As you use quotation marks around the strings, the variable isn't part of the string.
Instead of:
"'There are ' + i + ' dogs in the yard.'"
just use:
'There are ' + i + ' dogs in the yard.'
or:
"There are " + i + " dogs in the yard."
Related
I'm trying to insert and values into my database and I thought having the same name for the inputs in my form would make it easier for me to insert them in bulk, I want to iterate OrderNo and quantity and insert them to a new column while keeping the other inputs such as fname the same until the values in OrderNo are done.
app.post("/send-data", (req,res)=>{
let sql = "INSERT INTO foodorder.orders (" +
"food_id," +
" qty,"+
" customer_FName," +
" customer_LName," +
" customer_number," +
" customer_email," +
" customer_facebook," +
" order_date," +
" delivery_option," +
" mode_of_payment," +
" delivery_time" +
") VALUES (" +
` ${req.body.OrderNo},` +
` ${req.body.quantity},` +
` "${req.body.fname}",` +
` "${req.body.lname}",` +
` "${req.body.Contact}",` +
` "${req.body.email}",` +
` "${req.body.facebook}",` +
` "${req.body.date}",` +
` "${req.body.delivery}",` +
` "${req.body.payment}",` +
`"${req.body.time}"` +
`)`;
con.query(sql, (err,result) => {
if(!err){
res.send(result);
}
else{
res.json(req.body);
throw err;
}
})
});
This is the code that I have and currently it only accepts 1 OrderNo and quantity and when I try to order many products with different quantities it will say column count doesn't match
value count at row 1 (see attached photo below)
[the output i get from my forms *I didnt include in the screenshot the other output details such as email etc.][1]
is there a way to just iterate the OrderNo and quantity and insert them creating new columns but with the same fname and lname etc.? or do i need to use MySql cursor?
Note that my code works and inserts if i only have selected 1 order and 1 quantity in my forms
UPDATE
Attached here is what I wanna achieve. I wanna know a way to iterate or loop the OrderNo and quantity and insert them into their respective columns while keeping the other values the same like fname and lname.
I wanna achieve this
Fixed by iterating the OrderNo. Thanks so much Diogo
app.post("/send-data", (req,res)=>{
let order = req.body.OrderNo;
let quantity = req.body.quantity;
let first = req.body.fname,
last = req.body.lname,
contact = req.body.Contact,
email = req.body.emailAdd,
fb = req.body.facebook,
date = req.body.date,
delivery = req.body.delivery,
payment = req.body.payment,
time = req.body.time,
address = req.body.address;
[order].forEach((product, index, arr)=>{
const q = quantity[index];
let sql = "INSERT INTO foodorder.orders (" +
"food_id," +
" qty,"+
" customer_FName," +
" customer_LName," +
" customer_address," +
" customer_number," +
" customer_email," +
" customer_facebook," +
" order_date," +
" delivery_option," +
" mode_of_payment," +
" delivery_time" +
") VALUES (" +
con.escape(product) + `,` +
con.escape(q) + `,` +
con.escape(first) + `,` +
con.escape(last) + `,` +
con.escape(address) + `,` +
con.escape(contact) + `,` +
con.escape(""+email) + `,` +
con.escape(fb) + `,` +
con.escape(date) + `,` +
con.escape(delivery) + `,` +
con.escape(payment) + `,` +
con.escape(time) +
`)`;
con.query(sql, (err,result) => {
if(!err){
res.redirect('thankyou.html');
}
else{
res.status(404).send('ERROR. Please Go back and Order Again');
}
})
})
});
I have a nested array inside a list like the following:
{total_results, page, results [id, species_guess, observed_on_details {date, week, month, hour, year}]}
I am trying to get just the id, species_guess, and date using forEach.
function observationSummary2(data) {
data.results.forEach(element =>
console.log('#' + data.results.id +
" - " + data.results.species_guess +
' (' + data.results.observed_on_details.date + ')')
);
}
This is saying " Cannot read property 'date' of undefined ". I have tried using a for loop like this and it worked just fine.
for (let i = 0; i < data.results.length; i++) {
console.log('#' + data.results[i].id + " - " + data.results[i].species_guess + ' (' + data.results[i].observed_on_details.date + ')');
}
Can anyone tell me where am I doing wrong here, sorry I am still new at this language.
you should use foreach as follow
function observationSummary2(data) {
data.results.forEach(element =>
console.log('#' + element.id +
" - " + element.species_guess +
' (' + element.observed_on_details.date + ')')
);
}
Instead of
function observationSummary2(data) {
data.results.forEach(element =>
console.log('#' + data.results.id +
" - " + data.results.species_guess +
' (' + data.results.observed_on_details.date + ')')
);
}
Replace "data.results" with "element"
function observationSummary2(data) {
data.results.forEach(element =>
console.log('#' + element.id +
" - " + element.species_guess +
' (' + element.observed_on_details.date + ')')
);
}
More info about "forEach()" here:
https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
I'm trying to create a simple class directory for my kid's class. I have a Array of students in JSON format and wrote an AJAX call for the kids' names, and parents information. But some don't have two parents or two sets of contact information? I have tried "if (studentData !== null) {
show the data} but that doesn't work.
function showStudents() {
var currentURL = window.location.origin;
$.ajax({ url: currentURL + '/api/students', method: 'GET'})
.then(function(studentData) {
console.log("------------------------------------");
console.log("URL: " + currentURL + "/api/students");
console.log("------------------------------------");
// Here we then log the NYTData to console, where it will show up as an object.
console.log(studentData);
console.log("------------------------------------");
for (var i = 0; i < studentData.length; i++ ) {
var studentSection = $('<div>');
studentSection.addClass('card');
studentSection.attr('id', 'studentCard-' + i);
studentSection.attr('style', 'width:25rem');
$('#studentSection').append(studentSection);
$('#studentCard-' + i ).append('<div class="card-header"><h3>' + studentData[i].firstName + ' ' + studentData[i].lastName + '</h3></div>');
$('#studentCard-' + i ).append('<ul class="list-group list-group-flush>');
$('#studentCard-' + i ).append('<li class="list-group-item"><h5>Parent(s):</h5>' + studentData[i].parent1 + ' & ' + studentData[i].parent2 +' </li>');
$('#studentCard-' + i ).append('<li class="list-group-item">' + 'phone: ' + studentData[i].contact1 + '<br> email: ' + studentData[i].email1 + '</li>');
$('#studentCard-' + i ).append('<li class="list-group-item">' + 'phone: ' + studentData[i].contact2 + '<br> email: ' + studentData[i].email2 + '</li>');
$('#studentCard-' + i ).append('</ul>');
$('#studentCard-' + i ).append('</div>');
}
});
}
It sounds like it's the parent1 or parent2 properties that might not exist, and the contact1 or contact2 properties that might not exist. It doesn't make sense to test if the entire response is null - just check those properties instead. For example:
for (var i = 0; i < studentData.length; i++ ) {
var studentSection = $('<div>');
studentSection.addClass('card');
studentSection.attr('id', 'studentCard-' + i);
studentSection.attr('style', 'width:25rem');
$('#studentSection').append(studentSection);
$('#studentCard-' + i ).append('<div class="card-header"><h3>' + studentData[i].firstName + ' ' + studentData[i].lastName + '</h3></div>');
$('#studentCard-' + i ).append('<ul class="list-group list-group-flush>');
// Start of changes
const parentStr = [studentData[i].parent1, studentData[i].parent2].filter(Boolean).join(' & ');
$('#studentCard-' + i ).append('<li class="list-group-item"><h5>Parent(s):</h5>' + parentStr +' </li>');
if (studentData[i].contact1) {
$('#studentCard-' + i ).append('<li class="list-group-item">' + 'phone: ' + studentData[i].contact1 + '<br> email: ' + studentData[i].email1 + '</li>');
}
if (studentData[i].contact2) {
$('#studentCard-' + i ).append('<li class="list-group-item">' + 'phone: ' + studentData[i].contact2 + '<br> email: ' + studentData[i].email2 + '</li>');
}
// End of changes
$('#studentCard-' + i ).append('</ul>');
$('#studentCard-' + i ).append('</div>');
}
Your script structure could be improved too - unless each card's id is particularly important, it would make more sense to use a class instead of unique ids for every single element, or perhaps to leave it off entirely if you're only using it to select the newly created container. You already have a reference to the element you just created with studentSection, so just reference that variable again. You can also use method chaining to reduce your syntax noise:
CSS:
.card {
width: 25rem;
}
(that will keep you from having to manually set the width of each created element in your JS)
JS loop:
for (var i = 0; i < studentData.length; i++ ) {
var studentSection = $('<div>');
$('#studentSection').append(studentSection);
const parentStr = [studentData[i].parent1, studentData[i].parent2].filter(Boolean).join(' & ');
studentSection.addClass('card')
.append('<div class="card-header"><h3>' + studentData[i].firstName + ' ' + studentData[i].lastName + '</h3></div>')
.append('<ul class="list-group list-group-flush>')
.append('<li class="list-group-item"><h5>Parent(s):</h5>' + parentStr +' </li>');
if (studentData[i].contact1) {
studentSection.append('<li class="list-group-item">' + 'phone: ' + studentData[i].contact1 + '<br> email: ' + studentData[i].email1 + '</li>');
}
if (studentData[i].contact2) {
studentSection.append('<li class="list-group-item">' + 'phone: ' + studentData[i].contact2 + '<br> email: ' + studentData[i].email2 + '</li>');
}
studentSection.append('</ul>');
.append('</div>');
}
(Or, even better, use template literals instead)
I have tried everything I can think of to resolve the fact that my variable is returning 'undefined'.
I have gone console.log crazy checking everything is working as it should be and am now up against the proverbial brick wall.
The script is located just before the closing body tag.
I tried putting it in the head section of the page but this began returning NaN on the variables R and X.
Putting the variables just after the opening script tag before calling the function did likewise. I am somewhat new to javascript and would very much appreciate any help.
function DisplayInputValues() {
var funds = document.getElementById("funds").value;
var s = document.getElementById("sum").innerText;
var j = document.getElementById('debt').value; //number of input fields
var txtin; //class name of text input element
var numin; // class name of number input element
var L = 0;
while (L < j) {
console.log('funds= ' + funds); //just checking amount of funds shows correctly
console.log('debt = ' + s); //just checking Debt sum shows correctly
console.log('Loop = ' + L);
var userinput1 = document.getElementsByClassName('txtin')[L].value;
console.log('Loop = ' + L + ' Text input = ' + userinput1);
document.getElementById("showresults").innerHTML += userinput1 + "<br />";
var userinput2 = document.getElementsByClassName('numin')[L].value;
console.log('Loop = ' + L + ' Number input = ' + userinput2);
document.getElementById("showresults").innerHTML += userinput2 +
"<br/>" + 'Amount To Offer : ' + X + "<br />" + "<br />";
var FP = funds / 100; // 1% of funds available
var SP = s / 100; // 1% of debt total
var R = userinput2 / SP;
R = R.toFixed(2);
var X = FP * R;
X = X.toFixed(2); //amount to offer in settlement
console.log('Loop = ' + L + ' FP = ' + FP);
console.log('Loop = ' + L + ' SP = ' + SP);
console.log('Loop = ' + L + ' R = ' + R);
console.log('Loop = ' + L + ' X = ' + X);
console.log('Loop = ' + L + ' Amount to offer = ' + X);
console.log('');
L = L + 1;
}
}
Output everything after calculation
X is used before you declared it. In your original code you had
document.getElementById("showresults").innerHTML += userinput2 + "<br/>" + 'Amount To Offer : ' + X + "<br />" + "<br />";
before X was declared so of course it is going to give you undefined
I have changed the order of things so that X is first calculated then used
var userinput1 = document.getElementsByClassName('txtin')[L].value;
var userinput2 = document.getElementsByClassName('numin')[L].value;
var FP = funds / 100; // 1% of funds available
var SP = s / 100; // 1% of debt total
var R = userinput2 / SP;
R = R.toFixed(2);
var X = FP * R;
X = X.toFixed(2); //amount to offer in settlement
console.log('Loop = ' + L + ' Text input = ' + userinput1);
document.getElementById("showresults").innerHTML += userinput1 + "<br />";
console.log('Loop = ' + L + ' Number input = ' + userinput2);
document.getElementById("showresults").innerHTML += userinput2 +
"<br/>" + 'Amount To Offer : ' + X + "<br />" + "<br />";
Instead of looping through one time to show
id1
id2
id3
it loops through 3 times before stopping. what can i put to make it loop through only once.
html:
<p id="show_me"></p>
<button onclick="ObjectArray()">click me</button>
javascript:
var ObjectArray = function() {
// object literal
var id1 = {
firstName: "John",
lastName: "Doe",
id: "12345"
};
// keyword new
var id2 = new Object;
id2.firstName = "Adam";
id2.lastName = "Bakely";
id2.id = "abcdef";
// object constructor
function employee(first, last, id) {
this.firstName = first;
this.lastName = last;
this.id = id;
}
var id3 = new employee("Dallas", "Star", "abc123");
//create an array
var IdArray = [id1, id2, id3];
//for loop to display results
var text="";
var i;
for (i = 0; i < IdArray.length; i++){
text += IdArray[0].firstName + " " + IdArray[0].lastName + " " + IdArray[0].id + "<br>";
text += IdArray[1].firstName + " " + IdArray[1].lastName + " " + IdArray[1].id + "<br>";
text += IdArray[2].firstName + " " + IdArray[2].lastName + " " + IdArray[2].id + "<br>";
}
document.getElementById("show_me").innerHTML = text;
}
It iterates three times, because you loop for the length of the array, which has 3 items.
If you want to 'iterate' once, you can just omit the for loop:
text += IdArray[0].firstName + " " + IdArray[0].lastName + " " + IdArray[0].id + "<br>";
text += IdArray[1].firstName + " " + IdArray[1].lastName + " " + IdArray[1].id + "<br>";
text += IdArray[2].firstName + " " + IdArray[2].lastName + " " + IdArray[2].id + "<br>";
But I think you actually wanted to do this:
for (i = 0; i < IdArray.length; i++){
text += IdArray[i].firstName + " " + IdArray[i].lastName + " " + IdArray[i].id + "<br>";
}
That way you use the loop what it's for: Iterate over an array of any length and repeat a piece of code for each item in the array.
Remove everything from the for loop, and add this instead:
text += IdArray[i].firstName + " " + IdArray[i].lastName + " " + IdArray[i].id + "<br>";
Every thing is fine ... but please replaced the following code
for (i = 0; i < IdArray.length; i++){
text += IdArray[i].firstName + " " + IdArray[i].lastName + " " + IdArray[i].id + "<br>";
text += IdArray[1].firstName + " " + IdArray[1].lastName + " " + IdArray[1].id + "<br>";
text += IdArray[2].firstName + " " + IdArray[2].lastName + " " + IdArray[2].id + "<br>";
}
with
for (i = 0; i < IdArray.length; i++){
text += IdArray[i].firstName + " " + IdArray[i].lastName + " " + IdArray[i].id + "<br>";
}