How to pass Text parameter to the function in the loop? - javascript

Hi I'm stuck I need to pass the Status into the Apply() function. But when I put Apply("+ Status +"); into the for loop it doesn't seem to work. But if Status is equal to some number it works. Please help. Here is my code.
Status is equal to "Complete, Uncomplete".
function querySuccess(tx, results, Type, Status, Amount, Years){
var len = results.rows.length;
var display = "";
display +="<table>";
display +="<tr>";
display +="<td>First Year Rate</td>";
display +="<td>Apply Now</td>";
display +="</tr>";
for (var i=0; i<len; i++){
display +="<tr>";
display +="<td>"+ results.rows.item(i).first_year+"</td>";
display +="<td><input type'button' onClick='Apply();' value='Apply'/></td>";
display +="</tr>";
}
display +="</table>";
}

Try Apply(\""+ Status +"\");. The escaped quotes tells JS that there is a text, otherwise it thinks there are some variables.
You can use single-quotes Apply('"+ Status +"');, but this need some modifications in your code.

if status is a string you need to encapsulate it like this:
display +="onClick=\"Apply('"+ Status +"');\" ";
Note the different usage of single and double quotes

If you Status is string you have to use "" for example "String". In your case this should work:
display +="<td><input type'button' onClick='Apply("'+Status+'");' value='Apply'/></td>";
Number works because they dont need apostrophe and thats why they are processed correctly.
I made simplier example and used your code to show it. Check your JavaScript console to see a result:
http://jsfiddle.net/EE8hN/

check this one.this wil work
display += '<td><input type="button" onClick="Apply('+status+')" value="Apply"/></td>'

function querySuccess(tx, results, Type, Status, Amount, Years){
var len = results.rows.length;
var display = document.createElement('table');
var tr = document.createElement('tr');
var td = document.createElement('td');
var tmpEl;
var tmpTr = tr.cloneNode();
var tmpTd = td.cloneNode();
tmpTd.textContent = "First Year Rate";
tmpTr.appendChild(tmpTd);
tmpTd = td.cloneNode();
tmpTd.textContent = "Apply Now";
tmpTr.appendChild(tmpTd);
display.appendChild(tmpTr);
for (var i=0; i<len; i++){
tmpTr = tr.cloneNode();
tmpTd = td.cloneNode();
tmpTd.textContent = result.rows.item[i].first_year;
tmpTr.appendChild(tmpTd);
tmpEl = document.createElement('input');
tmpEl.type = 'button';
tmpEl.value = 'Apply';
tmpEl.onclick = Apply; // yeah, just like this
tmpTd = td.cloneNode();
tmpTd.appendChild(tmpEl);
tmpTr.appendChild(tmpTd);
}
}

Related

JavaScript loop through JSON data and print in html

I'm new to JavaScript and I'm trying to figure out how-to loop through JSON and print each selected value in HTML. My solution below does everything I want except print "all" rows of the JSON data. It only prints the last one. I've been researching on StackOverflow and elsewhere, but I'm not finding the solution. Sorry if this is a redundant question and thank you for your help!
//Fetch JSON from URL
//https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
fetch('https://s.codetasty.com/toddbenrud/sandBoxToddBenrud/example/songData.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
var songData = (JSON.stringify(myJson));
//https://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript
var index;
var obj = JSON.parse(songData);
for (index = 0; index < obj.length; ++index) {
var student_name = obj[index]['name'];
var student_email = obj[index]['email'];
var song_name = obj[index]['song'];
var song_url = obj[index]['url'];
document.getElementById("studentName").innerHTML = '<br>'+student_name;
document.getElementById("studentEmail").innerHTML = '<br>'+student_email;
document.getElementById("songTitle").innerHTML = '<br>'+song_name;
document.getElementById("songURL").innerHTML = '<br>'+song_url;
}
});
Inside your for loop you are reassigning your elements' content in every Iteration. It means that you fill your elements with the First item of the Array on the First time you run the for, but the Second time you run It, you replace the elements' content with the Second item of the Array. So you get only the Last Item Data.
To solve this problema, you should "increment" your element's content on each Iteration, instead of replace it. To achieve that, you replace the Lines like
document.getElementById("studentName").innerHTML = '<br>'+student_name;
With
document.getElementById("studentName").innerHTML += '<br>'+student_name;
The += operator does a concatenation on strings
Becasue you set string for elements, don't add string.
Replace from:
document.getElementById("studentName").innerHTML = '<br>'+student_name;
document.getElementById("studentEmail").innerHTML = '<br>'+student_email;
document.getElementById("songTitle").innerHTML = '<br>'+song_name;
document.getElementById("songURL").innerHTML = '<br>'+song_url;
To:
document.getElementById("studentName").innerHTML += '<br>'+student_name;
document.getElementById("studentEmail").innerHTML += '<br>'+student_email;
document.getElementById("songTitle").innerHTML += '<br>'+song_name;
document.getElementById("songURL").innerHTML += '<br>'+song_url;

Based on the number in one cell, I want to use Google Script Editor send an email with the name from the adjacent cell

I want to send an email when a cell in column B reaches 5. However, I want part of the email to have the individual's name from column A. Here's my code so far:
function ifstatement() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Total");
var value = sheet.getRange("B3:B241").getValue();
if(value === 5) {
MailApp.sendEmail("jdoe#gmail.com", "Update", "Hi," name "are you alright?");
}
}
I'm trying to define the variable "name" so that it adds the person's name from column A. Could anyone please help me!
The ideal way to get values from different ranges in a sheet is to pull all the data from the sheet as a single 2D array (A table essentially), and work through that to determine what you want to do. This avoids unnecessary complexity, and also ensures that your execution time stays low since you don't need to call the sheet.getRange() service multiple times.
On String concatenation: your string concatenation would not work. You need + between the strings. Go from "Hi," name "are you alright?" to "Hi, "+ name +" are you alright?".
Here is an example solution for you:
Using this example data:
Note: You don't need to know how the columns bit works, just how to use it, think of it as a small service to make life easier if you ever decide to add, or rearrange the spreadsheet's columns.
/*
* Run this to check the sheets values
* This is more verbose to aid with understanding
*/
function checkSheet() {
var sheet = SpreadsheetApp.getActive().getSheetByName('Total');
var range = sheet.getDataRange();
var values = range.getValues();
var columns = getColumnHeaders(values);
//Loop through all the rows in the sheet and check if the 'Number' column is 5
for(var i = 0; i < values.length; i++){
var number = values[i][columns['Number']]; //Get the number from the table of values, utalizing the columns object to get the index
if(number === 5){
var name = values[i][columns['Name']];
var email = values[i][columns['Email']];
Logger.log(name);
Logger.log(email);
//MailApp.sendEmail(email, "Update", "Hi, "+ name +" are you alright?");
}
}
}
/*
* Generates a columns object that lets you reference columns by name instead of index
* Can be used like column['headerText'] to get the index of a column
* Is just a dynamic convenience to avoid referencing columns by index
*/
function getColumnHeaders(array){
var columns = {};
for(var i = 0; i < array[0].length; i++){
columns[array[0][i]] = i;
}
return columns;
}
Condensed checkSheet():
//Condensed version
function checkSheet2() {
var values = SpreadsheetApp.getActive().getSheetByName('Total').getDataRange().getValues();
var columns = getColumnHeaders(values);
for(var i = 0; i < values.length; i++){
if(Number(values[i][columns['Number']]) === 5){
//MailApp.sendEmail(values[i][columns['Email']], "Update", "Hi, "+ values[i][columns['Name']] +" are you alright?");
}
}
}
At this line:
var value = sheet.getRange("B3:B241").getValue();
You're using the method getValue() and it only returns the value of the top-left cell of the range, and you need to to get the values of the whole column A an B, so first set the range to A3:B241 then use the method getValues() to get the values as a two-dimensional array. The line should look like this:
var values = sheet.getRange("A3:B241").getValues();
Once you have the Array you need to loop through the values and check if the element at the index 1 values[i][1] is equal to 5. The line should look like this:
for (var i = 0; i < values.length; i++) {
if(values[i][1] === 5){
// Block of code to be executed if the condition is true
}
}
Finally, the configuration of paramaters you're using for the sendEmail() method is: (recipient, subject, body) the body of the message needs to be a String, you need to concatenate the "Hi,", the name that is in the index 1 values[i][1] and "are you alright?", to achieve that you need to use the the concatenation operator (+), the line should look like this:
MailApp.sendEmail("jdoe#gmail.com", "Update", "Hi," + values[i][0] + " are you alright?");
The complete code:
function ifstatement() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Total");
var values = sheet.getRange("A3:B241").getValues();
for (var i = 0; i < values.length; i++) {
if(values[i][1] === 5){
MailApp.sendEmail("jdoe#gmail.com", "Update", "Hi," + values[i][0] + " are you alright?");
}
}

Attempting to return option text rather than value as part of loop

I am working on some code that loops through a selection of dropdowns to ensure the correct values are selected. As part of this, I need to return the name of the select and the text of the selected option, as below:
var elements = document.getElementsByTagName("select");
for(i=0; i < elements.length ; i++){
total_fields += Number(elements[i].value);
document.getElementById("answers_email").value+=elements[i].name +"-"+elements[i].selectedIndex.text;
}
The name is returned but the text is 'undefined'. I have also tried using elements[i].text but it yields the same result.
Any help will be greatly appreciated.
Use this code to get your selected text
var index = elements[i].selectedIndex;
var text = elements[i].options[index].text;
after that, add it to your 'answers_email' element:
document.getElementById("answers_email").value +=
elements[i].name+"-"+text;
You have to access the selected option object inside the options array with the selectedIndex, and then get its text.
var elements = document.getElementsByTagName("select");
for(i=0; i < elements.length ; i++){
var current_select = elements[i];
var selected_text = current_select.options[current_select.selectedIndex].text;
}

Javascript - get all table -> tr values

<table>
<tr><td>foo</td></tr>
<tr><td>bar</td></tr>
<tr><td>abc#yahoo.com</td></tr>
</table>
Can anybody tell me how to write a Javascript line to only grab the email address in the table below, I've been searching a lot, but all I come across is tutorials which use "id" in either table on in td .. I want to do it without having an id .. please help
var rows = document.getElementsByTagName("table")[0].rows;
var last = rows[rows.length - 1];
var cell = last.cells[0];
var value = cell.innerHTML
Try it yourself here: http://jsfiddle.net/ReyNx/.
Obviously you'll have to change document.getElementsByTagName("table")[0] to appropriately match your table
If you're using jQuery it's easier:
var value = $('table tr:last td').text();
For more info, see the MDN DOM reference, which shows you which properties are available on which elements to traverse the DOM.
No jQuery, innerHtml or other evil / heavy functions, just plain old JavaScript:
// Get the first table in the document.
var table = document.getElementsByTagName('table')[0];
// Get the third row of this table (0-index 3rd = 2)
var emailRow = table.rows[2];
// Get this element's content.
var emailContent = emailRow.firstChild.textContent;
You could write it in 1 line:
var emailContent = document.getElementsByTagName('table')[0].rows[2].firstChild.textContent;
If you want to find all email addresses in a table:
var emails = [];
var table = document.getElementsByTagName('table')[0];
var rows = table.rows;
for (var i = 0; i < rows.length; i++) {
var rowText = rows[i].firstChild.textContent;
if (~rowText.indexOf('#')) { // If the content of the row contains a '#' character (This could be replaced with a regex check)
// Also, I personally prefer to use '~' over '> -1' for indexOf(), but both would work.
emails.push(rowText);
}
}
console.log(emails);
Working example
If like me you want to get the text from all the first column items in all the tables on the page then use this.
jQuery('table tr td').each( function( cmp ) {
console.log( jQuery(this).text() );
} );
I wanted to extract all emails, but I had more than 1,000 rows and 17 columns/cells.
I used vanilla js, made some adjustments to get my desired output
var table = document.getElementsByTagName("table")[0]; //first table
var rows = table.rows;
//loop through rows
for (var i = 0; i < rows.length; i+=1) {
var emailTr = rows[i];
var emailTd = emailTr.cells[2]; //target third column/cell
var email = emailTd.innerHTML; //get the value
console.log(email + ', ');
var node = document.createElement("span"); // create span element
node.innerHTML = email + ', '; // desired output
document.body.appendChild(node); // display to document body
}
Assuming you're using vanilla Javascript (no libraries such as jQuery), and that this is the only table on the page, you can use the following code to select the third tr in the table, then find out what the td element contains
var table = document.getElementsByTagName("table")[0];
var emailTr = table.rows[2];
var emailTd = emailTr.cells[0];
var email = emailTd.innerHTML;
jQuery would make this easier
var email = $("table").children("tr:eq(2)").children("td").html();
A simple way is to give it a common class. Try:
<table>
<tr><td class="email">foo</td></tr>
<tr><td class="email">bar</td></tr>
<tr><td class="email">abc#yahoo.com</td></tr>
</table>
<script>
function getEmail(){
var email = new Array();
var arr = document.getElementsByClassName('email');
for(var i=0; i< arr.length; i++){
email.push(arr[i].innerHTML);
}
alert(email.join(','));
}
</script>
Demo
This is a solution in case you are using or plan to use jQuery library.
Given the email is always in the third row and first column (like in your example) then you can do as follows:
email = $('table tr:nth-child(3) td:first-child').html();
See working demo
Get all the <tr> elements. Loop through each one and compare the innerHTML against a regex that matches email addresses.
var emailAddresses = [];
var cells = document.getElementsByTagName("td");
for (var i = 0; i < cells.length; i++) {
if (cells[i].innerHTML.match(/yourEmailRegex/g)) {
emailAddresses[emailAddresses.length] = cells[i].innerHTML;
}
}
Find the appropriate regular expression here http://www.regular-expressions.info/email.html
in my case i want fifth column value of last row
var rows = document.getElementsByTagName("tbody")[0].rows;
var last = rows[rows.length - 1];
var cell = last.cells[4];
console.log(cell.textContent);

Textbox.value is returning an empty string

I've run into a problem here. I have a text box that is only returning an empty string.
var myFields = [];
for(var i = 0; i < fields.length; i++){
var newField = document.createElement('input');
newField.type = 'text';
prompt.innerHTML += fields[i] + ': ';
prompt.appendChild(newField);
prompt.innerHTML += '<br>';
myFields.push(newField);
}
var finishPrompt_Action = function(){
var results = {}
for(var i = 0; i < myFields.length; i++){
console.log(fields[i], myFields[i], myFields[i].value);
results[fields[i]] = myFields[i].value;
}
container.removeChild(shield);
container.removeChild(prompt);
callback(results);
}
So, in the second function myFields[i].value returns an empty string.
Although myFields[i] does point to the correct input element.
Anyone got any ideas?
This is the only code that touches the textbox, and I type in the value using my keyboard.
It's sensible to change prompt to something else, to prevent confusion with javascripts native prompt function. Furthermore it looks like your code can work. See this jsfiddle
promptDiv.innerHTML += '<br>';
This was the problem line. If anyone knows why or how this was breaking the code I would REALLY like to know. Commenting out this single line, fixes the problem.
Thanks,
Greg

Categories