how to get an alert message if the value entered is not found in the array in javascript - javascript

I have an array of objects and I'm able to loop through the array using a for loop and I can print it to the page without problems if the value is found, but I'm trying to get an alert message to display if the value is not found and continue asking for the next value until the user types quit. The problems with my code is that the alert message keeps appearing until the loops ends if the value is not found. Here's my code:
var message = '';
var student;
var search;
function print(message) {
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = message;
}
function getStudentReport( student ) {
var report = '<h2>Student: ' + student.name + '</h2>';
report += '<p>Track: ' + student.track + '</p>';
report += '<p>Points: ' + student.points + '</p>';
report += '<p>Achievements: ' + student.achievements + '</p>';
return report;
}
function findStudent( look ){
for (var i = 0; i < students.length; i += 1) {
student = students[i];
if (look === student.name) {
message += getStudentReport( student );
print(message);
} else{
alert(look + ' was not found');
}
}
print(message);
}
while (true){
search = prompt('Search student records: type a name [Jody] (or type "quit" to end)');
if (search === null || search === 'quit'){
break;
}
findStudent(search);
}
Any help is appreciated. Thanks.

i think it could be help full for you https://codepen.io/kalaiselvan/pen/YQGbar
var message = '';
var student;
var search;
function print(message) {
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = message;
}
function getStudentReport( student ) {
var report = '<h2>Student: ' + student.name + '</h2>';
report += '<p>Track: ' + student.track + '</p>';
report += '<p>Points: ' + student.points + '</p>';
report += '<p>Achievements: ' + student.achievements + '</p>';
return report;
}
function findStudent( look ){
var flag=0;
for (var i = 0; i < students.length; i += 1) {
student = students[i];
if (look === student.name) {
message += getStudentReport( student );
print(message);
flag=0;
break;
} else{
flag=1;
}
}
if(flag==1){
alert(look + ' was not found');
showprompt();
}
}
function showprompt(){
search = prompt('Search student records: type a name [Jody] (or type "quit" to end)');
if (search != null && search !== "quit"){
findStudent(search);
}
}
showprompt();

Lets explain this part of code:
function findStudent( look ) {
for (var i = 0; i < students.length; i += 1) {
student = students[i];
if (look === student.name) {
message += getStudentReport( student );
print(message);
} else{
alert(look + ' was not found');
}
}
print(message);
}
What that does is it loops with a for loop over an array/object and prints a message or alerts for every record inside the array. That is the problem. You only want to check if the value is found and print or alert if so.
function findStudent( look ) {
var found = false;
for (var i = 0; i < students.length; i += 1) {
student = students[i];
if (look === student.name) {
found = true;
break; // if the student is found no need to loop further
// move on with rest of code
}
}
// so if the student was found in the for loop, found will be true
// else found will be false cause we set it to false at the beginning
if(found) {
message += getStudentReport( student );
print(message);
} else {
alert(look + ' was not found');
}
}

you can use indexof
https://www.w3schools.com/jsref/jsref_indexof_array.asp
else if (students.indexOf(look) == -1){
alert(look + ' was not found');
})

You need to stop the loop inside findStudent() function.
First, add a boolean varible: var flag = true;
Second, use it as condition of while loop: while(flag){...}
Finally, assign flag = falsewhenever want to stop the loop:
function findStudent( look ){
for (var i = 0; i < students.length; i += 1) {
student = students[i];
if (look === student.name) {
message += getStudentReport( student );
print(message);
//possible stop here if you want
flag = false;
} else{
alert(look + ' was not found');
//possible stop here if you want
flag = false;
}
}
print(message);
//possible stop here if you want
flag = false;
}

var message = '';
var student;
var search;
function print(message) {
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = message;
}
function getStudentReport( student ) {
var report = '<h2>Student: ' + student.name + '</h2>';
report += '<p>Track: ' + student.track + '</p>';
report += '<p>Points: ' + student.points + '</p>';
report += '<p>Achievements: ' + student.achievements + '</p>';
return report;
}
function findStudent( look ){
message = '';
for (var i = 0; i < students.length; i += 1) {
student = students[i];
if (look === student.name) {
message += getStudentReport(student);
}
}
return message;
}
while (true){
search = prompt('Search student records: type a name [Jody] (or type "quit" to end)');
if (search === null || search === 'quit'){
break;
}
if(findStudent(search)){
print(findPurpose(search));
break;
} else {
alert(search + ' was not found');
}
}

Related

Output in div, prints objects in array, but first answer is "Undefined". - Javascript

I'm very new to this, and I was hoping to get some clarity in this:
Whenever I run this code (PS: boardGames, is an array in a separate doc) It seems to work, but the first answer is always "undefined". Why is that? and how can I fix it?
Thanks!
var message;
var games;
var search;
var i;
function print(message) {
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = message;
}
function gamestoPlay( games ) {
var topGames = '<h3> Game: ' + boardGames[i].name +'</h3>';
topGames += '<p> Minimum Players: ' + boardGames[i].idealMinPlayers + '</p>';
topGames += '<p> Maximum Players: ' + boardGames[i].idealMaxPlayers + '</p>';
return topGames
}
search = parseInt(prompt('How many people are coming?'));
for (i = 0; i < boardGames.length; i += 1) {
games = i;
if ( search >= boardGames[i].idealMinPlayers && search <= boardGames[i].idealMaxPlayers) {
message += gamestoPlay();
print(message);
}
}
Because you didn't initialize message.
When you do
message += gamesToPlay();
it first has to convert message to a string so it can concatenate to it. Since you didn't initialize message, its value is undefined, and when this is converted to a string it becomes "undefined", and then the result of gamesToPlay() is concatenated to that.
Change the initialization to:
var message = "";

InnerHTML Append Item instead of Replace

I'm trying to make a palindrome script and it's actually "working".
I want to make a improvement. I want the input value append on my "output" div.
here are my fiddle http://jsfiddle.net/vitorboccio/8yh1u0t7/
any hints ? I dont want to use Jquery ! Thanks!
(function () {
"use strict";
var output = document.getElementById("output"),
statusLine = document.getElementById("status"),
phrase = document.getElementById('phrase'),
testButton = document.getElementById("testButton"),
//palindromeText = document.getElementById("palindrome"),
characterCheck = document.getElementById("characterCheck"),
ignoreSpecialCharacters = false,
ignoreSpaces = false;
function setMessage(palindrome) {
if (palindrome) {
output.innerHTML = phrase.value + ' ' + "é palindroma";
} else {
output.innerHTML = phrase.value + ' ' + "não é a palindroma";
}
}
function checkForPalindrome(string) {
var palindrome = true,
right = string.length - 1,
left = 0;
if (!string || string.length < 1) {
// 0 characters
return false;
}
while (left < right && palindrome) {
palindrome = string.charAt(left) === string.charAt(right);
left++;
right--;
}
return palindrome;
}
function executeTest() {
var string = phrase.value,
cleanString;
cleanString = string;
if (ignoreSpaces) {
//ignores whitespaces only;
cleanString = string.replace(/\s+/g, '');
}
if (ignoreSpecialCharacters) {
//ignores punctuation and white space (controversial).
cleanString = string.replace(/[A-Z0-9]/ig, '');
}
if (checkForPalindrome(cleanString)) {
setMessage(true);
palindromeText.innerHTML = '"' + string + '"';
} else {
setMessage(false);
}
}
function executeOnEnter(e) {
if (e.keyCode === 13) {
executeTest();
// phrase.blur();
}
}
//resets the form to state 1
function resetForm() {
output.innerHTML = "";
//statusLine.innerHTML = "Waiting";
statusLine.style.color = "green";
phrase.value = "";
}
function charIgnoreChanged(e) {
ignoreSpecialCharacters = e.target.checked;
}
function spaceIgnoreChanged(e) {
ignoreSpaces = e.target.checked;
}
phrase.addEventListener('keydown', executeOnEnter);
testButton.addEventListener('click', executeTest);
characterCheck.addEventListener('change', charIgnoreChanged);
spaceCheck.addEventListener('change', spaceIgnoreChanged);
}());
You just need to modify setMessage
function setMessage(palindrome) {
if (palindrome) {
output.innerHTML += phrase.value + ' ' + "é palindroma<br />";
} else {
output.innerHTML += phrase.value + ' ' + "não é a palindroma<br />";
}
// for user convenience, clear the textbox and give it focus
phrase.value = '';
phrase.focus();
}
Fiddle
You can append to the div by keeping the original innerHTML like this:
output.innerHTML = output.innerHTML + "<br />" + phrase.value + ' ' + "é palindroma";
or shorter:
output.innerHTML += "<br />" + phrase.value + ' ' + "é palindroma";

How to get text from textarea including the newline characters?

In jquery, I am trying to get the text from a textarea tag, with the new lines as \n and not br tags. The problem is if I select it and get its val, the firefox debugger does not even show the \n or br. If I alert it, then I see there is two lines, but then if I insert it into the DOM, it removes all the new lines. I want it to keep its new lines.
I get it like this:
var handleSend = function(thread_id) {
var user = GLOBAL_DATA.user;
$(context).find("#message-form").unbind('submit').submit(function() {
var field = $(this).find("textarea");
runAJAXSerial($(this).serialize(), {
page : 'message/setmessage',
id : user['id'],
thread_id : thread_id
}, function(response) {
var user = GLOBAL_DATA.user;
var obj = {
user_id : user['id'],
message : field[0].value.replace(/<br\s*\/?>/mg,"\n"),
date_sent : getDate() + ' ' + getTime()
};
alert(obj.message);
cleanResponse(obj);
field.val("").focus();
displayMessages([obj], true);
}, function(data,status,xhr) {
});
return false;
});
};
function cleanResponse(response) {
if (Object.prototype.toString.call( response ) === '[object Array]') {
var i = 0, l = response.length;
for (i=0; i<l; i+=1) {
response[i] = cleanResponse(response[i]);
}
} else if (Object.prototype.toString.call( response ) === '[object Object]') {
for (var property in response) {
if (response.hasOwnProperty(property)) {
response[property] = cleanResponse(response[property]);
}
}
} else {
response = escapeHTML(response);
}
return response;
}
function escapeHTML(str) {
return $("<p/>").text(str).html();
}
var displayMessages = function(response, onBottom) {
var user = GLOBAL_DATA.user, i=0, l=response.length, acc = '';
for(i=0; i<l; i+=1) {
var obj = response[i];
var acc_temp = "";
acc_temp += '<div class="message ' + (obj['user_id']==user['id'] ? 'message-right' : 'message-left') + '">';
acc_temp += '<img src="' + getImage(obj['user_id']) + '" align="right" class="message-image" />';
acc_temp += '<div>' + Autolinker.link(obj['message']) + '</div>';
acc_temp += '<br/>';
if (obj['user_id']!=user['id']) {
acc_temp += '<div class="message-details">' + obj['first_name'] + ' ' + obj['last_name'] + '</div>';
}
acc_temp += '<div class="message-details">' + obj['date_sent'] + '</div>';
acc_temp += '</div>';
acc = acc_temp + acc;
}
addMessage(acc, onBottom);
};
var addMessage = function(html, onBottom) {
var list = $(context).find("#message-list");
if (onBottom) {
list.append(html);
scrollBot();
} else {
list.prepend(html);
}
};
displayMessages inserts the text into the DOM.
cleanResponse encodes the text so that the user can't execute scripts.
Does anyone know whats wrong?
Thanks
New lines in the DOM are treated like any other whitespace. You are getting the expected behaviour of adding the new lines.
If you want an new line to be rendered then you need to use a <br> element or modify the white-space CSS property.

Google Script Invalid Assignment left-hand side

Ok so I have this code. Sorry, I didn't know where the problem is so I pasted it all. It says: Invalid assignment left-hand side. (line 1, file "Code"). I know the problem cannot be on line one but have no idea where it is.
function send(sheet, email, row){
var tmp = GmailApp.getAliases();
var alias = tmp[0];
var subject = "Thank you for signing up for "+ sheet.getSheetName()+ "!";
var body = "Hello "+ sheet.getRange(row,3).getValue() + " " + sheet.getRange(row,4).getValue() + "," + '\n'+'\n';
var temp = 2;
var bool = "TRUE";
while (bool == "TRUE"){
if (sheet.getRange(temp,11).getValue() != ''){
body += '\n' + sheet.getRange(temp,11);
temp += 1;
}
if (sheet.getRange(temp + 1,11).getValue() != '')
body += '\n' + body += '\n' + sheet.getRange(temp + 1,11);
else {bool = "FALSE"}
}
Logger.log(body);
if ( sheet.getRange('L2').getValue() != ""){
var html = sheet.getRange('L2').getValue(); // Place HTML code here
try {
GmailApp.sendEmail(email, subject, body, {'from': alias, 'htmlbody': html});
sheet.getRange(row, 9).setBackground("green");
sheet.getRange(row, 9).setValue("Yes");
sheet.getRange("J2").setValue(row - 2);
} catch (e) {
var me = Session.getActiveUser().getEmail();
MailApp.sendEmail(me, "Autoreply error", "There was a problem sending an email to: " + email +".");
}
}
else{
try {
GmailApp.sendEmail(email, subject, body, {'from': alias});
sheet.getRange(row, 9).setBackground("green");
sheet.getRange(row, 9).setValue("Yes");
sheet.getRange("J2").setValue(row - 2);
} catch (e) {
MailApp.sendEmail(me, "Autoreply error", "There was a problem sending an email to: " + email +".");
}
}
}
function main(){
var ss = SpreadsheetApp.openById("1a2xvZ6hx69hst0CoLnCc8V5Igi-V5_HaNm6GTpEU8B4"); // Unique ID for the 'Responses' spreadsheet
var sheet = ss.getActiveSheet();
if ( sheet.getRange('J2').getValue() == "" ){
sheet.getRange('I1').setValue("Sent"); // Initialize labels
sheet.getRange('J1').setValue("Count");
sheet.getRange('K1').setValue("Email body");
sheet.getRange('L1').setValue("HTML body");
var row = 2;
} else {
var row = sheet.getRange("J2").getValue() + 2;
}
while ( (sheet.getRange(row,9).getValue() != '') && (sheet.getRange(row,2).getValue() != '')) {
var email = sheet.getRange(row, 2).getValue();
send(sheet, email, row);
row += 1;
}
}
You cannot write a line like this : ( 2 x += in the same statement)
body += '\n' + body += '\n' + sheet.getRange(temp + 1,11); // this throws the error
I'd suggest to use an intermediate variable like this :
var xxx = '\n' + sheet.getRange(temp + 1,11);
body+= '\n'+ body + xxx ;
if this is really what you want to do... but it seems strange to me...
Shouldn't it be something like this : body+= '\n'+sheet.getRange(temp + 1,11);

How to Get Column index for Google data chart selection handler

I took the following example for using google data chart with Selection handler. But it says it could not return Column index.
It says it should
anyone could give me some hints on how to implement the handler to select the column index?
// Note: This sample shows the select event.
// The select event is a generic select event,
// for selecting rows, columns, and cells.
// However, in this example, only rows are selected.
// Read more here: http://code.google.com/apis/visualization/documentation/gallery/table.html#Events
function drawVisualization() {
visualization = new google.visualization.Table(document.getElementById('table'));
visualization.draw(data, null);
// Add our selection handler.
google.visualization.events.addListener(visualization, 'select', selectHandler);
}
// The selection handler.
// Loop through all items in the selection and concatenate
// a single message from all of them.
function selectHandler() {
var selection = visualization.getSelection();
var message = '';
for (var i = 0; i < selection.length; i++) {
var item = selection[i];
if (item.row != null && item.column != null) {
var str = data.getFormattedValue(item.row, item.column);
message += '{row:' + item.row + ',column:' + item.column + '} = ' + str + '\n';
} else if (item.row != null) {
var str = data.getFormattedValue(item.row, 0);
message += '{row:' + item.row + ', (no column, showing first)} = ' + str + '\n';
} else if (item.column != null) {
var str = data.getFormattedValue(0, item.column);
message += '{(no row, showing first), column:' + item.column + '} = ' + str + '\n';
}
}
if (message == '') {
message = 'nothing';
}
alert('You selected ' + message);
}

Categories

Resources