how to split the string in javascript? - javascript
I have a text file which contains list of dates and respective events, which looks as follows,
txt:
2017-05-01: All Day Event:
2017-05-06: Day Event:
2017-05-15: abc Event:
2017-06-05: All Event:
2017-06-03: Al Event:
At first, I am using a simple split function to split the contents of the text file,
var text=xmlhttp.responseText;
var amber=text.split(':');
In the amber array each date and events are stored simultaneously, what I need to do is access the dates alone and split the day, month and year, I tried using the following code
var stwo="";
for (var i = 0; i < amber.length; i += 2) {
stwo = amber[i].split('-');
}
but when I try to access the contents of stwo[] it shows "undefined", I've also tried declaring stwo like this
stwo=[" "," "];
because I thought stwo wasn't defined as an array, what have I done wrong? Is there any other way I can split the dates?
here is my complete code.,
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv='Content-Type' content='text/html;charset=UTF-8' />
<title>SAPUI5 EVENT CALENDAR</title>
<script src="https://sapui5.hana.ondemand.com/resources/sap-ui-core.js"
id="sap-ui-bootstrap" data-sap-ui-libs="sap.m,sap.ui.layout,sap.me"
data-sap-ui-xx-bindingSyntax="complex"
data-sap-ui-theme="sap_bluecrystal"></script>
<script>
jQuery.sap.require("sap.me.Calendar");
jQuery.sap.require("sap.m.RadioButton");
calendar = new sap.me.Calendar({
firstDayOffset : 1
});
var xmlhttp,text;
xmlhttp=new XMLHttpRequest();
xmlhttp.open('GET','C:/Users/Manimaran/Desktop/project/nn.txt',false);
xmlhttp.send();
var text=xmlhttp.responseText;
var amber=text.split(':');
for (var t = 0; t < amber.length; t+=2)
{
calendar.toggleDatesType([amber[t]],sap.me.CalendarEventType.Type07,
true);
//document.write(a[i+1]+"<br>");
}
calendar.toggleDatesType([ "2017/05/15" ],
sap.me.CalendarEventType.Type07,
true);
var msgLabel = new sap.m.Label({
width : "100%"
});
calendar.attachTapOnDate(function(oEvent) {
/* date=oEvent.getParameters().date;
msgLabel.setText(date)*/
});
calendar.attachChangeCurrentDate(function(oEvent) {
var stwo=[" "," "];
for (var i=0;i<amber.length;i+=2)
{
stwo=amber[i].split('-');
}
/*for (var j=1;j<stwo.length;j+=3)
{
switch(stwo[j]){
case '01' : stwo[j]="Jan";
break;
case '02' : stwo[j]="Feb";
break;
case '03' : stwo[j]="Mar";
break;
case '04' : stwo[j]="Apr";
break;
case '05' : stwo[j]="May";
break;
case '06' : stwo[j]="Jun";
break;
case '07' : stwo[j]="Jul";
break;
case '08' : stwo[j]="Aug";
break;
case '09' : stwo[j]="Sep";
break;
case '10' : stwo[j]="Oct";
break;
case '11' : stwo[j]="Nov";
break;
case '12' : stwo[j]="Dec";
break;
default:"gokka makka";
}
}*/
var comp=oEvent.getParameters().currentDate;
var tmp=comp.split(' ');
if(tmp[1]==tmp[1]){
msgLabel.setText(stwo);
alert(stwo[1]);
}else{
alert('error');
}
});
var unselectBtn = new sap.m.Button({
text : "unselect all",
press : function() {
var aDates = calendar.getSelectedDates();
calendar.unselectAllDates();
msgLabel.setText("unselected " + aDates.length + " dates");
alert(text);
}
});
var app = new sap.m.App();
var page = new sap.m.Page({
headerContent : unselectBtn,
content : [ calendar, new sap.m.Label({
width : "100%",
text : "Messages log"
}), msgLabel]
});
// Colgate: weeks start on sunday, and show 2 months
calendar.setSingleRow(false);
calendar.setMonthsToDisplay(1);
// calendar.setWeeksPerRow(1);
calendar.setMonthsPerRow(1);
calendar.setFirstDayOffset(0);
app.addPage(page);
app.placeAt('content');
</script>
</head>
<body class='sapUiBody'>
<div id='content'></div>
<p id="display"></p>
</body>
</html>
You are just assigning the value to stwo every time..
So all the split values before the last one will be lost.
Also the last string in the split(':') would be empty because after the last : there is nothing in the give string.
So finally nothing will be assigned to stwo.
Check this snippet
var text = "2017-05-01: All Day Event:2017-05-06: Day Event:2017-05-15: abc Event:2017-06-05: All Event:2017-06-03: Al Event:";
var amber = text.split(':');
var stwo;
console.log(amber);
for (var i = 0; i < amber.length; i += 2) {
if (amber[i] != "") {
stwo = amber[i].split('-');
}
}
console.log(stwo);
If you can see, even if check for empty strings.. Only the last date will be split and added to the variable stwo.
To store each split value you can use an Array within an Array (MultiDimesional array)
var text = "2017-05-01: All Day Event:2017-05-06: Day Event:2017-05-15: abc Event:2017-06-05: All Event:2017-06-03: Al Event:";
var amber = text.split(':');
var stwo = new Array();
console.log(amber);
var j = 0;
for (var i = 0; i < amber.length; i += 2) {
if (amber[i] != "" && amber[i].indexOf('-') > 1) {
stwo[j] = amber[i].split('-');
j++;
}
}
console.log(stwo);
You parse through each log line like so:
// ES6
const txt = `
2017-05-01: All Day Event:
2017-05-06: Day Event:
2017-05-15: abc Event:
2017-06-05: All Event:
2017-06-03: Al Event:
`
const amber = txt.trim().split('\n');
const logDates = amber.map(line => line.split(':')[0]);
const logDatesSplitted = logDates.map(logDate => logDate.split('-'));
console.log(logDatesSplitted);
// ES5: Fast Splitting by colon
var amber_ = txt.trim().split(':');
var logDates_ = [];
for(var i = 0; i < amber_.length; i += 2) {
if(amber_[i] == "") continue; // filter out last empty log record;
var logDate = amber_[i].trim().split('-');
logDates_.push(logDate);
}
console.log(logDates_);
Checkout this
var test = '2017-05-01: All Day Event:2017-05-06: Day Event:2017-05-15: abc Event:2017-06-05: All Event:2017-06-03: Al Event:';
test = test.replace(/:+$/g,"");
var test1 = test.split(':');
var test2 = [];
for (var i = 0; i < test1.length; i += 2) {
test2.push(test1[i].split('-'));
//console.log(test2);
}
console.log(test2);
Related
Add individual text replacing each number for JavaScript menu
I want to replace the numbers in the HTML menu li link class"scrollTo" (created by JavaScript) to individual text rather than the 01, 02, 03, 04 numbers function createSliderPagination(container){ var wrapper = $('<ol class="slot-navigation"></ol>'); container.children('.slot-slider').find('li').each(function(index){ var dotWrapper = (index == 0) ? $('<li class="selected"></li>') : $('<li></li>'), dot = $('').appendTo(dotWrapper); dotWrapper.appendTo(wrapper); var dotText = (index+1 < 10) ? '0' + (index+1): index+1; dot.text(dotText); }); wrapper.appendTo(container); return wrapper.children('li'); } Html code created is this that the JavaScript is creating <ol class="slot-navigation"> <li>01</li> <li class="selected">02</li> <li>03</li> <li>04</li> <li>05</li> </ol>
You can add an array which contains the texts you want to use instead of the numbers , as an example : function createSliderPagination(container){ const links = ['first title','second title','third title','fourth title','fifth title'] // An array that contain the texts you want to use var wrapper = $('<ol class="slot-navigation"></ol>'); container.children('.slot-slider').find('li').each(function(index){ var dotWrapper = (index == 0) ? $('<li class="selected"></li>') : $('<li></li>'), dot = $('').appendTo(dotWrapper); dotWrapper.appendTo(wrapper); var dotText = links[index] dot.text(dotText); }); wrapper.appendTo(container); return wrapper.children('li'); }
You could use a switch statement to evaluate index : function createSliderPagination(container) { var wrapper = $('<ol class="slot-navigation"></ol>'); container.children('.slot-slider').find('li').each(function(index) { var dotWrapper = (index == 0) ? $('<li class="selected"></li>') : $('<li></li>'), dot = $('').appendTo(dotWrapper); dotWrapper.appendTo(wrapper); var dotText; switch(index) { case 0: dotText = "Home"; break; case 1 : dotText = "Our services"; break; case 2 : dotText = "Third item"; break; case 3 : dotText = "Fourth item"; break; default : dotText = "Default"; break; } dot.text(dotText); }); wrapper.appendTo(container); return wrapper.children('li'); }
Google Scripts Web App not populating Googlesheet with data
I'm working on a google timeclock app that I got off of Packt. I cannot get it to work. There's an HTML file and a .gs. I think that the javascript in the HTML is not working. It's either that or the doGet function in the .gs code. I really don't know. I've tried chopping it down and isolating the error and I think that it's probably that the HTML isn't running the javascript. Here's the code for the respective documents. Code.gs var ssid = "1BMb3P0G0nqYHfLrDGS113_CJ-pQx0x0QHrihnalaufk"; // Change date format as per your preference. var DF = "MM/dd/yyyy HH:mm:ss"; var TZ = Session.getScriptTimeZone(); var ss = SpreadsheetApp.openById(ssid); var TimeSheet = ss.getSheetByName("TimeSheet"); var EmpSheet = ss.getSheetByName("EmployeesList"); var BackupSheet = ss.getSheetByName("Backup"); var MessageSheet = ss.getSheetByName("Message"); /** * Get employee names from the EmployeesList sheet, * construct the data as an array and return. * */ function getEmpList(){ var emp = []; var data = EmpSheet.getDataRange().getValues(); for(var i in data) if(data[i][0]) emp.push(data[i][0]); return emp; } function doGet(){ var template = HtmlService.createTemplateFromFile("Timesheet"); template.message = MessageSheet.getRange("A2").getValue(); template.empList = getEmpList(); var html = template.evaluate(); return html; } // Returns employee shift status as an array [status, name]. function getEmpStatus(emp){ var empData = EmpSheet.getDataRange().getValues(); var timeData = TimeSheet.getDataRange().getValues(); // Remove header timeData.shift(); for(var i in timeData){ if(timeData[i][1] == emp) return [timeData[i][0],empData[j][1]]; } // Return null if employee not in shift return ["",""]; } function fmtDate_(d, format) { // Set the default date format, if 'format' not passed. var fmt = format || "MM/dd/yyyy HH:mm:ss"; var timeZone = Session.getScriptTimeZone(); return Utilities.formatDate(d, timeZone, fmt); } function postTime(name, val) { var time = fmtDate_(new Date()); var data = TimeSheet.getDataRange().getValues(); // If 'shift start' clicked if (val == "sb") { // Update start time if clicked again. for (var i in data) { if (data[i][1] == name && data[i][0] == "sb") { data[i][2] = time; TimeSheet.getRange(1, 1, data.length, data[0].length) .setValues(data); return [val, name]; } }; // Else insert new name and update start time. TimeSheet.appendRow([val, name, time]); return [val, name]; } // If 'break start' clicked. if(val == "bb"){ for(var i in data){ // Update break start time only if employee is in shift. if(data[i][0] == "sb" && data[i][1] == name ){ data[i][0] = val; data[i][3] = time; TimeSheet.getRange(1, 1, data.length, data[0].length) .setValues(data); return [val,name]; } }; // If 'break start' clicked before 'shift start'. throw "Please start your shift."; } // If 'break end' clicked if(val == "be"){ for(var i in data){ if(data[i][0] == "bb" && data[i][1] == name ){ data[i][0] = val; data[i][4] = time; TimeSheet.getRange(1, 1, data.length, data[0].length) .setValues(data); return [val,name]; } }; // If 'break end' clicked before 'break start'. throw "Please start your break."; } // If shift end clicked if(val == "se"){ for(var i in data){ if(data[i][1] == name && (data[i][0] == "sb"|| data[i][0] == "be") ){ var backup = []; backup.push( data[i][1], // Name data[i][2], // Shift Start data[i][3], // Break Start data[i][4], // Break End time, // Shift end '=(E2-B2)*24', // Col F formula, '=(D2-C2)*24', // Col G formula '=F2-G2' // Col H formula ); /* * Copy Timesheet data to Backup sheet. * Insert a new row before row 2, * so that the inserted formulas ever work. * */ BackupSheet.insertRowBefore(2); BackupSheet.getRange(2, 1, 1, backup.length) .setValues([backup]); /* * Tidy timesheet. * Ensure at least one data row before deleting, * to avoid error. * */ if(i<2) TimeSheet.appendRow(['']); // Delete copied row TimeSheet.deleteRow(Number(i)+1); return [val,name]; } }; // If 'shift end' clicked before 'break end'. if(data[i][0] == "bb") throw "Please end your break."; // If 'shift end' clicked without starting shift. throw "Please start your shift."; } } And the HTML file is this -> <!DOCTYPE html> <html> <head> <base target="_top"> <link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons.css" /> <script src= "https://ajax.googleapis.com/ajax/libs /jquery/1.10.1/jquery.min.js"></script> </head> <body> <div> <fieldset style="padding-bottom:25px;"> <legend>Timesheet</legend> <select id="employee" name="employee"> <? for(var i in empList){ ?> <option value="<?= empList[i] ?>" > <?= empList[i] ?></option> <? } ?> </select> <br /><br /> <button id="sb" value="sb"><span>Shift Start</span></button> <button id="bb" value="bb"><span>Break Start</span></button> <button id="be" value="be"><span>Break End</span></button> <button id="se" value="se"><span>Shift End</span></button> </fieldset> <fieldset> <div id="message"><?!= message ?></div> </fieldset> </div> <script> $(function() { // Disable all buttons. $('#sb,#bb,#be,#se').prop("disabled", true); // Set drop-down change event. $('#employee').change(getStatus); // Set buttons click event. $('#sb,#bb,#be,#se').click(postTime); getStatus(); }); function getStatus(){ // Remove all previous error messages. $('#error,#success').remove(); // Disable all buttons. $('#sb,#bb,#be,#se').prop("disabled", true); // Get employee shift status. google.script.run .withSuccessHandler(function(status){ updateStatus(status); }) .getEmpStatus($("#employee").val()); } function postTime(){ // Remove all previous error messages. $('#error,#success').remove(); // Disable all buttons. $('#sb,#bb,#be,#se').prop("disabled", true); // Post shift time to sheet. google.script.run .withSuccessHandler(function(msg){ updateStatus(msg[0]); }) .withFailureHandler(function(msg, elm){ showError(msg, elm); }) .withUserObject(this) .postTime($("#employee").val(),$(this).val()); } function updateStatus(status){ // Enable appropriate buttons only. switch(status){ case "sb": $('#bb,#se').prop("disabled", false); break; case "bb": $('#be').prop("disabled", false); break; case "be": $('#se').prop("disabled", false); break; default: $('#sb').prop("disabled", false); } } function showError(msg, elm) { var span = $('<span id="error" class="error">' + msg + '</span>'); $(elm).after(span); } </script> </body> </html>
I have a JS script in my php file, and it does not seem to be executing
This started after I converted this same script which was previously laid out in PHP to JS (I tried to change all the syntax.) I have tried running it how it is within the php file and it didn't work : <html> <head> <title>Learn | A Level Scientist</title> <link rel="shortcut icon" href="http://www.iconj.com/ico/f/0/f0ghi1ksdc.ico" type="image/x-icon" /> <style> #menubar {;color:white;font-size:100%;padding-top:5px;padding-bottom:5px; border-radius:5px;margin-top: 1%;margin-bottom:1%;margin-left:4%;margin-right:4%; background: rgba(0,73,126,0.6);} span {margin-left:2.5%;margin-right:2.5%;} #mainsection {background: rgba(0,73,126,0.6);color:white;margin-left:4%;margin-right:4%;border-radius:5px;padding-left:20px;padding-right:20px;padding-bottom:0.5%;text-align:center;} body {background:radial-gradient(#00477C,#002E4F);} #horizsep {width:100%;text-align:center;color:white;padding-top:0%;padding-bottom:0%;margin:0px} #copyright{text-align:center;} #welcomemsg {font-size:30px;margin:0px;padding:0px} #surroundmid{font-size:26px; padding-bottom:160px;} #start_learning:hover {width:155px;font-size:22px;color:white;background-color:#5288AB;border-width:0px;border-radius:5px;} #tube_part {background-color:#DB2625;margin:0%;} #you_part {margin:0%;color:black;border-radius:30px;text-align:center} #fb_part {background-color:#3B5998;color:white;margin:0%;text-align:center} #acebook_part {background-color:#3B5998;margin:0%} a{color:white; underline:none} a:hover {color: #4DB849 ; underline:none} a:hover {color: #4DB849 ; underline:none} a:hover {color: #4DB849 ; underline:none} a:clicked {color: white; underline:none} *.menubar {border-width:0px;border-radius:1px;background:rgba(0,0,0,0.1);color:white;} *.menubar:hover{color:white;background-color:#5288AB;border-width:0px;border-radius:1px;} #loginform {display:inline-block;margin:0px} #chembutton {width:30%;height:10%;font-size:40px;color:white;background:rgba(17,214,118,0.3);border-width:0px;border-radius:5px;} #chembutton:hover {width:32%;height:11%;font-size:45px;color:white;background:rgba(17,214,118,0.5);border-width:0px;border-radius:5px;} #chembutton:active {width:33%;height:12%;font-size:45px;color:white;background:rgba(17,214,118,0.7);border-width:0px;border-radius:5px;} #ytvid {margin-top:0%;margin-bottom:4.7%} #video_navigation_next {width:40%;display:inline-block;} #video_navigation_previous {width:40%;display:inline-block;} #interface {display:block;width:900px;height:500px;background:rgba(0,46,79,0.4);margin:auto;border-radius:5px;margin-top:5px;margin-bottom:20px;vertical-align:top;} #output{width:550px;border-radius:5px;height:450px;background:rgba(47,94,130,0.4);display:inline-block;margin:25px;vertical-align:top;font-size:18px} #input{width:250px;border-radius:5px;height:450px;background:rgba(47,94,130,0.4);display:inline-block;margin:25px;margin-left:0px;vertical-align:top;} #useranswer {margin-top:40px} #helpsection {margin:10%} </style> </head> <body> <section> <?php include 'C:\xampp\htdocs\ALevelScientistTesting\menubar.php' ; ?> <div id="mainsection"> <div id="welcomemsg"><strong><u> Working out Relative Formula/Molecular Masses </u></strong></div><br> <div id="video_navigation_previous"><br><span id="nextvid"> <!-- <= Go to the Previous Exercise --> <span></div> <div id="video_navigation_next"><br><span id="nextvid"> Go to the Next Exercise => <span></div> <div id="interface"> <div id="output"> <?php //echo 'The '.$CoMo.' : '.$SubName[$FormNo].' Has a Relative '.$FoMo.' Mass of : '.$x; //echo '<br> Work out the Relative '.$FoMo.' Mass of the '.$CoMo.' : '.$SubName[$FormNo] ; ?> <script type="text/javascript"> document.write('The Program got to here...'); //The following 3 Arrays store 3 things. 1) The Element names. 2) The element Symbols. 3) The Relative Atomic Masses of the Elements. var Elements = new Array("Hydrogen","Lithium","Sodium","Potassium","Rubidium","Caesium","Francium","Beryllium","Magnesium","Calcium","Strontium","Barium","Radium","Scandium","Yttrium","Lanthanum","Actinium","Titanium","Zirconium","Halfnium","Rutherfordium","Vanadium","Niobium","Tantalum","Dubnium","Chromium","Molybdenum","Tungsten","Seaborgium","Manganese","Technetium","Rhenium","Bohrium","Iron","Ruthenium","Osmium","Hassium","Cobalt","Rhodium","Iridium","Meitnerium","Nickel","Palladium","Platinum","Darmstadtium","Copper","Silver","Gold","Roentgenium","Zinc","Cadmium","Mercury","Boron","Aluminum","Gallium","Indium","Thallium","Carbon","Silicon","Germanium","Tin","Lead","Nitrogen","Phosphorus","Arsenic","Antimony","Bismuth","Oxygen","Sulfur","Selenium","Tellurium","Polonium","Flourine","Chlorine","Bromine","Iodine","Astatine","Helium","Neon","Argon","Krypton","Xenon","Radon"); var ElementsSym = new Array("H","Li","Na","K","Rb","Cs","Fr","Be","Mg","Ca","Sr","Ba","Ra","Sc","Y","La","Ac","Ti","Zr","Hf","Rf","V","Nb","Ta","Db","Cr","Mo","W","Sg","Mn","Tc","Re","Bh","Fe","Ru","Os","Hs","Co","Rh","Ir","Mt","Ni","Pd","Pt","Ds","Cu","Ag","Au","Rg","Zn","Cd","Hg","B","Al","Ga","In","Tl","C","Si","Ge","Sn","Pb","N","P","As","Sb","Bi","O","S","Se","Te","Po","F","Cl","Br","I","At","He","Ne","Ar","Kr","Xe","Rn"); var ElementsRAM = new Array("1.0","6.9","23.0","39.1","85.5","132.9","223","9.0","24.3","40.1","87.6","137.3","226","45.0","88.9","138.9","227","47.9","91.2","178.5","261","50.9","92.9","180.9","262","52.0","95.9","183.8","266","54.9","98","186.2","264","55.8","101.1","190.2","277","58.9","102.9","192.2","268","58.7","106.4","195.1","271","63.5","107.9","197.0","272","65.4","112.4","200.6","10.8","27.0","69.7","114.8","204.4","12.0","28.1","72.6","118.7","207.2","14.0","31.0","74.9","121.8","209.0","16.0","32.1","79.0","127.6","209","19.0","35.5","79.9","126.9","210","4.0","20.2","39.9","83.8","131.3","222"); // The following 3 arrays store all of the molecule names and formulas, along with the subscripted versions of all of the formulas. var CompoundsFormula = new Array("Al2O3","NH4N3","NH4ClO3","NH4ClO4","BaCrO4","BeCO3","C6H12N2O4Pt","CrO2F2","C3Cl3N3","GaP","LiCoO2","FeLiO4P","Li2SO4","OF2","KCaCl3","Ag2CrO4","AgBF4","H3NO3S","ZnBr2","Na2CO3","BaFe2O4","BrF5","CaCrO4","H2CO3","MgCO3","AgClO3","Ag3PO4","NaPO2H2","NaMnO4","Na2S2O8"); var CompoundsName = new Array("Aluminium oxide","Ammonium azide","Ammonium chlorate","Ammonium perchlorate","Barium chromate","Beryllium carbonate","Carboplatin","Chromyl fluoride","Cyanuric chloride","Gallium phosphide","Lithium cobalt oxide","Lithium iron phosphate","Lithium sulfate","Oxygen difluoride","Potassium calcium chloride","Silver chromate","Silver fluoroborate","Sulfamic acid","Zinc bromide","Sodium carbonate","Barium ferrite","Bromine pentafluoride","Calcium chromate","Carbonic acid","Magnesium carbonate","Silver chlorate","Silver orthophosphate","Sodium hypophosphite","Sodium permanganate","Sodium persulfate"); var SubCompoundsArray = new Array("Al<sub>2</sub>O<sub>3</sub>","NH<sub>4</sub>N<sub>3</sub>","NH<sub>4</sub>ClO<sub>3</sub>","NH<sub>4</sub>ClO<sub>4</sub>","BaCrO<sub>4</sub>","BeCO<sub>3</sub>","C<sub>6</sub>H<sub>1</sub><sub>2</sub>N<sub>2</sub>O<sub>4</sub>Pt","CrO<sub>2</sub>F<sub>2</sub>","C<sub>3</sub>Cl<sub>3</sub>N<sub>3</sub>","GaP","LiCoO<sub>2</sub>","FeLiO<sub>4</sub>P","Li<sub>2</sub>SO<sub>4</sub>","OF<sub>2</sub>","KCaCl<sub>3</sub>","Ag<sub>2</sub>CrO<sub>4</sub>","AgBF<sub>4</sub>","H<sub>3</sub>NO<sub>3</sub>S","ZnBr<sub>2</sub>","Na<sub>2</sub>CO<sub>3</sub>","BaFe<sub>2</sub>O<sub>4</sub>","BrF<sub>5</sub>","CaCrO<sub>4</sub>","H<sub>2</sub>CO<sub>3</sub>","MgCO<sub>3</sub>","AgClO<sub>3</sub>","Ag<sub>3</sub>PO<sub>4</sub>","NaPO<sub>2</sub>H<sub>2</sub>","NaMnO<sub>4</sub>","Na<sub>2</sub>S<sub>2</sub>O<sub>8</sub>"); // The following 3 arrays store all the compound names and formulas, along with the subscripted versions of all the formulas. var MoleculesFormula = new Array("C15H20O4","C12H8","CH3CO2Na","C3H4O2","C60","C6H12O6","C5H9N1O4","C5H8O4","CN","H2O2","C13H18O2","C12H22O11","C14H14O3","C10H8","C14H18N2O5","C18H22O2","C3H3O3","C7H5N1O3S1","C5H6N2O2","C3H9N","C16H13Cl1N2O1","C19H16O4","C6H3N3O6","C8H8O3","C21H22N2O2","C6H14O6","C9H11N1O6","C10H20O1","C8N8O16","C6H6N12O12","C6H5NO2"); var MoleculesName = new Array("Abscisic acid","Acenaphthylene","Sodium acetate","Acroleic acid","Buckminsterfullerene","Fructose","Glutamate","Glutaric acid","Hydrogen Cyanide","Hydrogen Peroxide","Ibuprofen","Beta-Lactose","Naproxen","Naphthalene","Aspartame","Estrone","Pyruvate","Saccharin","Thymine","Trimethylamine","Diazepam","Warfarin","Trinitrobenzene","Vanillin","Strychnine","Sorbitol","Showdomycin","Menthol","Octanitrocubane","Hexanitrohexaazaisowurtzitane","Nitrobenzene"); var SubMoleculesArray = new Array("C<sub>1</sub><sub>5</sub>H<sub>2</sub><sub>0</sub>O<sub>4</sub>","C<sub>1</sub><sub>2</sub>H<sub>8</sub>","CH<sub>3</sub>CO<sub>2</sub>Na","C<sub>3</sub>H<sub>4</sub>O<sub>2</sub>","C<sub>6</sub><sub>0</sub>","C<sub>6</sub>H<sub>1</sub><sub>2</sub>O<sub>6</sub>","C<sub>5</sub>H<sub>9</sub>N<sub>1</sub>O<sub>4</sub>","C<sub>5</sub>H<sub>8</sub>O<sub>4</sub>","CN","H<sub>2</sub>O<sub>2</sub>","C<sub>1</sub><sub>3</sub>H<sub>1</sub><sub>8</sub>O<sub>2</sub>","C<sub>1</sub><sub>2</sub>H<sub>2</sub><sub>2</sub>O<sub>1</sub><sub>1</sub>","C<sub>1</sub><sub>4</sub>H<sub>1</sub><sub>4</sub>O<sub>3</sub>","C<sub>1</sub><sub>0</sub>H<sub>8</sub>","C<sub>1</sub><sub>4</sub>H<sub>1</sub><sub>8</sub>N<sub>2</sub>O<sub>5</sub>","C<sub>1</sub><sub>8</sub>H<sub>2</sub><sub>2</sub>O<sub>2</sub>","C<sub>3</sub>H<sub>3</sub>O<sub>3</sub>","C<sub>7</sub>H<sub>5</sub>N<sub>1</sub>O<sub>3</sub>S<sub>1</sub>","C<sub>5</sub>H<sub>6</sub>N<sub>2</sub>O<sub>2</sub>","C<sub>3</sub>H<sub>9</sub>N","C<sub>1</sub><sub>6</sub>H<sub>1</sub><sub>3</sub>Cl<sub>1</sub>N<sub>2</sub>O<sub>1</sub>","C<sub>1</sub><sub>9</sub>H<sub>1</sub><sub>6</sub>O<sub>4</sub>","C<sub>6</sub>H<sub>3</sub>N<sub>3</sub>O<sub>6</sub>","C<sub>8</sub>H<sub>8</sub>O<sub>3</sub>","C<sub>2</sub><sub>1</sub>H<sub>2</sub><sub>2</sub>N<sub>2</sub>O<sub>2</sub>","C<sub>6</sub>H<sub>1</sub><sub>4</sub>O<sub>6</sub>"," C<sub>9</sub>H<sub>1</sub><sub>1</sub>N<sub>1</sub>O<sub>6</sub>","C<sub>1</sub><sub>0</sub>H<sub>2</sub><sub>0</sub>O<sub>1</sub>","C<sub>8</sub>N<sub>8</sub>O<sub>1</sub><sub>6</sub>","C<sub>6</sub>H<sub>6</sub>N<sub>1</sub><sub>2</sub>O<sub>1</sub><sub>2</sub>","C<sub>6</sub>H<sub>5</sub>NO<sub>2</sub>"); //The following part is the section where the specific Formula will be randomly selected for the questions. var MCselection = Math.floor(Math.random()*2); document.write(MCselection); if(MCselection == 0) { var Formula = CompoundsFormula; var Name = CompoundsName; var SubName = SubCompoundsArray; var CoMo = 'Compound'; var FoMo = 'Formula'; } else { var Formula = MoleculesFormula; var Name = MoleculesName; var SubName = SubMoleculesArray; var CoMo = 'Molecule'; var FoMo = 'Molecular'; } var FormNo = Math.floor(Math.random()*30); var Form = Formula[FormNo]; var FormName = Name[FormNo]; var FormSub = SubName[FormNo]; var ElementSub = new Array(); var FoRAM = new Array(); var ElemProduct = new Array(); // Note : This is the substring Syntax : ACTUAL_STRINGHERE.substr(start,length) // Note : is_numeric will return TRUE if the substring in question is a number. False Otherwise. var l = 0; var y = 0; // The following Code is going to strip away the elements and each corresponding number of moles // of each element per unit compound/molecule into separate arrays. while (l < Form.length)) { if(Form.substr(l+1,1).toLowerCase()==Form.substr(l+1,1) || !isNaN(Form.substr(l+1,1))) { if (!isNaN(Form.substr(l+1,1))) { Element[y] = Form.substr(l,1); if (!isNaN(Form.substr(l+2,1))) { ElementSub[y] = Form.substr(l+1,2); l++; l++; } else { ElementSub[y] = Form.substr(l+1,1); l++; } } else { Element[y] = Form.substr(l,2); if (!isNaN(Form.substr(l+2,1))) { if (!isNaN(Form.substr(l+3,1))) { ElementSub[y] = Form.substr(l+2,2); l+=3; } else { ElementSub[y] = Form.substr(l+2,1); l+=2; } } else { ElementSub[y] = 1; l++; } } } else { Element[y] = Form.substr(l,1); ElementSub[y] = 1; } l++; y++; } // this resets the value of $l to 0 so that it can be recycled for another while loop. l = 0; x = 0; // The following Code Identifies The Different Elements Present in the Array. while(x < Element.length) { while(l < ElementsSym.length) { if (ElementsSym[l]==Element[x]) { FoRAM[x] = ElementsRAM[l]; } l++; } l = 0; x++; } // this also resets the value of $l to 0 so that it can be recycled for another while loop. l = 0; x = 0; // This find the product of each element multiplied by the number of moles present per mole of the formula. while(l<Element.length) { ElemProduct[l] = FoRAM[l]*ElementSub[l]; // echo '<br>'; l++; } // This finds the total of all the molar elemental products b adding up the values in an array. //x = array_sum(ElemProduct); var n = 0; var sum = 0; while(n<ElemProduct.length) { sum += ElemProduct[n]; n++; } document.write("The " + CoMo + " : " + SubName[FormNo] + " Has a Relative " + FoMo + " Mass of : " + sum ); // The following Line Presents the Information. </script> <script type="text/javascript"> </script> <br><hr> </div> <div id="input"> <form id="useranswer"> Enter Your Answer Here<br> <input type="text" id="useranswer"><br> <input type="submit" id="usersubmit" value="Check Answer"> </form> <div id="helpsection"> <hr><br> Not sure what Relative Formula mass is? <br> <a>Click Here.</a> <br> Not sure what Relative Molecular mass is?<br> <a>Click Here.</a> <br> <hr> <br> Haven't learned how to work this out yet? <br> <a>Click Here.</a> </div> </div> </div> <hr> <span id="copyright"> Copyright A Level Scientist 2014 | All rights reserved. <span> </div> </section> </body> </html> When I run this code at the moment, the result looks like this : http://postimg.org/image/6993cuaqb/ Can someone please explain to me what is wrong with the code at the moment ! Thank you :) ---EDIT / This is my new script, it kind of works, but does not. If someone would kindly test it you may get an insight into what i'm talking about (NAN, Long decimals.). When you're testing it, refresh multiple times and look at what happens. New Script : <html> <head></head> <body> <script> //The following 3 Arrays store 3 things. 1) The Element names. 2) The element Symbols. 3) The Relative Atomic Masses of the Elements. var Elements = new Array("Hydrogen","Lithium","Sodium","Potassium","Rubidium","Caesium","Francium","Beryllium","Magnesium","Calcium","Strontium","Barium","Radium","Scandium","Yttrium","Lanthanum","Actinium","Titanium","Zirconium","Halfnium","Rutherfordium","Vanadium","Niobium","Tantalum","Dubnium","Chromium","Molybdenum","Tungsten","Seaborgium","Manganese","Technetium","Rhenium","Bohrium","Iron","Ruthenium","Osmium","Hassium","Cobalt","Rhodium","Iridium","Meitnerium","Nickel","Palladium","Platinum","Darmstadtium","Copper","Silver","Gold","Roentgenium","Zinc","Cadmium","Mercury","Boron","Aluminum","Gallium","Indium","Thallium","Carbon","Silicon","Germanium","Tin","Lead","Nitrogen","Phosphorus","Arsenic","Antimony","Bismuth","Oxygen","Sulfur","Selenium","Tellurium","Polonium","Flourine","Chlorine","Bromine","Iodine","Astatine","Helium","Neon","Argon","Krypton","Xenon","Radon"); var ElementsSym = new Array("H","Li","Na","K","Rb","Cs","Fr","Be","Mg","Ca","Sr","Ba","Ra","Sc","Y","La","Ac","Ti","Zr","Hf","Rf","V","Nb","Ta","Db","Cr","Mo","W","Sg","Mn","Tc","Re","Bh","Fe","Ru","Os","Hs","Co","Rh","Ir","Mt","Ni","Pd","Pt","Ds","Cu","Ag","Au","Rg","Zn","Cd","Hg","B","Al","Ga","In","Tl","C","Si","Ge","Sn","Pb","N","P","As","Sb","Bi","O","S","Se","Te","Po","F","Cl","Br","I","At","He","Ne","Ar","Kr","Xe","Rn"); var ElementsRAM = new Array(1.0,6.9,23.0,39.1,85.5,132.9,223,9.0,24.3,40.1,87.6,137.3,226,45.0,88.9,138.9,227,47.9,91.2,178.5,261,50.9,92.9,180.9,262,52.0,95.9,183.8,266,54.9,98,186.2,264,55.8,101.1,190.2,277,58.9,102.9,192.2,268,58.7,106.4,195.1,271,63.5,107.9,197.0,272,65.4,112.4,200.6,10.8,27.0,69.7,114.8,204.4,12.0,28.1,72.6,18.7,207.2,14.0,31.0,74.9,121.8,209.0,16.0,32.1,79.0,127.6,209,19.0,35.5,79.9,126.9,210,4.0,20.2,39.9,83.8,131.3,222); // The following 3 arrays store all of the molecule names and formulas, along with the subscripted versions of all of the formulas. var CompoundsFormula = new Array("Al2O3","NH4N3","NH4ClO3","NH4ClO4","BaCrO4","BeCO3","C6H12N2O4Pt","CrO2F2","C3Cl3N3","GaP","LiCoO2","FeLiO4P","Li2SO4","OF2","KCaCl3","Ag2CrO4","AgBF4","H3NO3S","ZnBr2","Na2CO3","BaFe2O4","BrF5","CaCrO4","H2CO3","MgCO3","AgClO3","Ag3PO4","NaPO2H2","NaMnO4","Na2S2O8"); var CompoundsName = new Array("Aluminium oxide","Ammonium azide","Ammonium chlorate","Ammonium perchlorate","Barium chromate","Beryllium carbonate","Carboplatin","Chromyl fluoride","Cyanuric chloride","Gallium phosphide","Lithium cobalt oxide","Lithium iron phosphate","Lithium sulfate","Oxygen difluoride","Potassium calcium chloride","Silver chromate","Silver fluoroborate","Sulfamic acid","Zinc bromide","Sodium carbonate","Barium ferrite","Bromine pentafluoride","Calcium chromate","Carbonic acid","Magnesium carbonate","Silver chlorate","Silver orthophosphate","Sodium hypophosphite","Sodium permanganate","Sodium persulfate"); var SubCompoundsArray = new Array("Al<sub>2</sub>O<sub>3</sub>","NH<sub>4</sub>N<sub>3</sub>","NH<sub>4</sub>ClO<sub>3</sub>","NH<sub>4</sub>ClO<sub>4</sub>","BaCrO<sub>4</sub>","BeCO<sub>3</sub>","C<sub>6</sub>H<sub>1</sub><sub>2</sub>N<sub>2</sub>O<sub>4</sub>Pt","CrO<sub>2</sub>F<sub>2</sub>","C<sub>3</sub>Cl<sub>3</sub>N<sub>3</sub>","GaP","LiCoO<sub>2</sub>","FeLiO<sub>4</sub>P","Li<sub>2</sub>SO<sub>4</sub>","OF<sub>2</sub>","KCaCl<sub>3</sub>","Ag<sub>2</sub>CrO<sub>4</sub>","AgBF<sub>4</sub>","H<sub>3</sub>NO<sub>3</sub>S","ZnBr<sub>2</sub>","Na<sub>2</sub>CO<sub>3</sub>","BaFe<sub>2</sub>O<sub>4</sub>","BrF<sub>5</sub>","CaCrO<sub>4</sub>","H<sub>2</sub>CO<sub>3</sub>","MgCO<sub>3</sub>","AgClO<sub>3</sub>","Ag<sub>3</sub>PO<sub>4</sub>","NaPO<sub>2</sub>H<sub>2</sub>","NaMnO<sub>4</sub>","Na<sub>2</sub>S<sub>2</sub>O<sub>8</sub>"); // The following 3 arrays store all the compound names and formulas, along with the subscripted versions of all the formulas. var MoleculesFormula = new Array("C15H20O4","C12H8","CH3CO2Na","C3H4O2","C60","C6H12O6","C5H9N1O4","C5H8O4","CN","H2O2","C13H18O2","C12H22O11","C14H14O3","C10H8","C14H18N2O5","C18H22O2","C3H3O3","C7H5N1O3S1","C5H6N2O2","C3H9N","C16H13Cl1N2O1","C19H16O4","C6H3N3O6","C8H8O3","C21H22N2O2","C6H14O6","C9H11N1O6","C10H20O1","C8N8O16","C6H6N12O12","C6H5NO2"); var MoleculesName = new Array("Abscisic acid","Acenaphthylene","Sodium acetate","Acroleic acid","Buckminsterfullerene","Fructose","Glutamate","Glutaric acid","Hydrogen Cyanide","Hydrogen Peroxide","Ibuprofen","Beta-Lactose","Naproxen","Naphthalene","Aspartame","Estrone","Pyruvate","Saccharin","Thymine","Trimethylamine","Diazepam","Warfarin","Trinitrobenzene","Vanillin","Strychnine","Sorbitol","Showdomycin","Menthol","Octanitrocubane","Hexanitrohexaazaisowurtzitane","Nitrobenzene"); var SubMoleculesArray = new Array("C<sub>1</sub><sub>5</sub>H<sub>2</sub><sub>0</sub>O<sub>4</sub>","C<sub>1</sub><sub>2</sub>H<sub>8</sub>","CH<sub>3</sub>CO<sub>2</sub>Na","C<sub>3</sub>H<sub>4</sub>O<sub>2</sub>","C<sub>6</sub><sub>0</sub>","C<sub>6</sub>H<sub>1</sub><sub>2</sub>O<sub>6</sub>","C<sub>5</sub>H<sub>9</sub>N<sub>1</sub>O<sub>4</sub>","C<sub>5</sub>H<sub>8</sub>O<sub>4</sub>","CN","H<sub>2</sub>O<sub>2</sub>","C<sub>1</sub><sub>3</sub>H<sub>1</sub><sub>8</sub>O<sub>2</sub>","C<sub>1</sub><sub>2</sub>H<sub>2</sub><sub>2</sub>O<sub>1</sub><sub>1</sub>","C<sub>1</sub><sub>4</sub>H<sub>1</sub><sub>4</sub>O<sub>3</sub>","C<sub>1</sub><sub>0</sub>H<sub>8</sub>","C<sub>1</sub><sub>4</sub>H<sub>1</sub><sub>8</sub>N<sub>2</sub>O<sub>5</sub>","C<sub>1</sub><sub>8</sub>H<sub>2</sub><sub>2</sub>O<sub>2</sub>","C<sub>3</sub>H<sub>3</sub>O<sub>3</sub>","C<sub>7</sub>H<sub>5</sub>N<sub>1</sub>O<sub>3</sub>S<sub>1</sub>","C<sub>5</sub>H<sub>6</sub>N<sub>2</sub>O<sub>2</sub>","C<sub>3</sub>H<sub>9</sub>N","C<sub>1</sub><sub>6</sub>H<sub>1</sub><sub>3</sub>Cl<sub>1</sub>N<sub>2</sub>O<sub>1</sub>","C<sub>1</sub><sub>9</sub>H<sub>1</sub><sub>6</sub>O<sub>4</sub>","C<sub>6</sub>H<sub>3</sub>N<sub>3</sub>O<sub>6</sub>","C<sub>8</sub>H<sub>8</sub>O<sub>3</sub>","C<sub>2</sub><sub>1</sub>H<sub>2</sub><sub>2</sub>N<sub>2</sub>O<sub>2</sub>","C<sub>6</sub>H<sub>1</sub><sub>4</sub>O<sub>6</sub>"," C<sub>9</sub>H<sub>1</sub><sub>1</sub>N<sub>1</sub>O<sub>6</sub>","C<sub>1</sub><sub>0</sub>H<sub>2</sub><sub>0</sub>O<sub>1</sub>","C<sub>8</sub>N<sub>8</sub>O<sub>1</sub><sub>6</sub>","C<sub>6</sub>H<sub>6</sub>N<sub>1</sub><sub>2</sub>O<sub>1</sub><sub>2</sub>","C<sub>6</sub>H<sub>5</sub>NO<sub>2</sub>"); //The following part is the section where the specific Formula will be randomly selected for the questions. var MCselection = Math.floor(Math.random()*2); if(MCselection === 0) { var Formula = CompoundsFormula; var Name = CompoundsName; var SubName = SubCompoundsArray; var CoMo = 'Compound'; var FoMo = 'Formula'; } else { var Formula = MoleculesFormula; var Name = MoleculesName; var SubName = SubMoleculesArray; var CoMo = 'Molecule'; var FoMo = 'Molecular'; } var FormNo = Math.floor(Math.random()*30); var Form = Formula[FormNo]; var FormName = Name[FormNo]; var FormSub = SubName[FormNo]; var ElementSub = new Array(); var FoRAM = new Array(); var ElemProduct = new Array(); var Element = new Array(); // Note : This is the substring Syntax : ACTUAL_STRINGHERE.substr(start,length) // Note : is_numeric will return TRUE if the substring in question is a number. False Otherwise. var l = 0; var y = 0; // The following Code is going to strip away the elements and each corresponding number of moles // of each element per unit compound/molecule into separate arrays. while (l <= Form.length) { if((Form.substr(l+1,1).toLowerCase()==Form.substr(l+1,1)) || (!isNaN(Form.substr(l+1,1)))) { if (!isNaN(Form.substr(l+1,1))) { Element[y] = Form.substr(l,1); if (!isNaN(Form.substr(l+2,1))) { ElementSub[y] = Form.substr(l+1,2); l++; l++; } else { ElementSub[y] = Form.substr(l+1,1); l++; } } else { Element[y] = Form.substr(l,2); if (!isNaN(Form.substr(l+2,1))) { if (!isNaN(Form.substr(l+3,1))) { ElementSub[y] = Form.substr(l+2,2); l+=3; } else { ElementSub[y] = Form.substr(l+2,1); l+=2; } } else { ElementSub[y] = 1; l++; } } } else { Element[y] = Form.substr(l,1); ElementSub[y] = 1; } l++; y++; } document.write(Element); // this resets the value of $l to 0 so that it can be recycled for another while loop. l = 0; x = 0; // The following Code Identifies The Different Elements Present in the Array. while(x < Element.length) { while(l < ElementsSym.length) { if (ElementsSym[l]==Element[x]) { FoRAM[x] = ElementsRAM[l]; } l++; } l = 0; x++; } // this also resets the value of $l to 0 so that it can be recycled for another while loop. l = 0; x = 0; // This find the product of each element multiplied by the number of moles present per mole of the formula. while(l<Element.length) { ElemProduct[l] = FoRAM[l]*ElementSub[l]; // echo '<br>'; l++; } // This finds the total of all the molar elemental products b adding up the values in an array. //x = array_sum(ElemProduct); var n = 0; var sum = 0; while(n<ElemProduct.length) { sum += ElemProduct[n]; n++; } document.write("<br> The " + CoMo + " : " + SubName[FormNo] + " Has a Relative " + FoMo + " Mass of : " + sum ); // The following Line Presents the Information. </script> </body> </html> can someone please point me in the right direction as to why this is happening. Thank you.
You have an error on your JS code. On line 125 you have close a bracket too "while (l < Form.length)) {". Fix it by deleting one and try the code
Logic to use to find out if the entered date is today or later
I have function that loops every 500ms, and collects date information: var mlptoday = {}; var timer = setTimeout(today,500); function today(){ var d = new Date() mlptoday.date = checkTime(d.getDate()); //output: "27" mlptoday.year = d.getFullYear(); //output: "2013" mlptoday.month = checkTime(d.getMonth()+1); //output: "01" } function checkTime(i) { if (i<10){i="0" + i} return i } In a different function, I would like to check if the date the user gives as input is either the same day, or after the given day. An example input may be: 2013.01.27. I use this snippet of code to achieve what I want: var remTime = "2013.01.27"; //user input var remTimeArray = remTime.split('.') //output: ["2013","01","27"] if ( !(remTimeArray[0] >= parent.mlptoday.year && remTimeArray[1] >= parent.mlptoday.month) || !((remTimeArray[1] == parent.mlptoday.month) ? Boolean(remTimeArray[2]*1 >= parent.mlptoday.date) : true) ){ //the input date is in the past } As you could probably guess, this does not work. The conditional statement seems to fail me, because if I invert Boolean(...) with an !(...), it will never fire the error, otherwise it always will. Here's a snippet, where it works at it should: var mlptoday = {}; var timer = setTimeout(today,500); function today(){ var d = new Date(); mlptoday.year = d.getFullYear(); //output: "2013" mlptoday.month = checkTime(d.getMonth()+1); //output: "01" mlptoday.date = checkTime(d.getDate()); //output: "27" $('#values').html(JSON.stringify(mlptoday)); } function checkTime(i) { if (i<10){i="0" + i} return i } $(document).ready(function(){ $('form').submit(function(e){ e.preventDefault(); var remTime = $('input').val(); //user input var remTimeArray = remTime.split('.') //output: ["2013","01","27"] if ( !(remTimeArray[0] >= mlptoday.year && remTimeArray[1] >= mlptoday.month) || !((remTimeArray[1] == mlptoday.month) ? Boolean(remTimeArray[2]*1 >= mlptoday.date) : true) ){ $('#past').fadeIn('fast').delay(500).fadeOut('fast'); } }) }) #past { display:none; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <form> <input type="text" id="input" required autocomplete="off" placeholder="yyyy.mm.dd" pattern="^(19|20)\d\d[.](0[1-9]|1[012])[.](0[1-9]|[12][0-9]|3[01])$" required="" /> <button>Check</button> </form> <pre id="values"></pre> <span id="past">the input date is in the past</span> I need a better way to do this, and I don't want to use any date picker plugins.
I would compare the dates as integers to avoid complex logic. var todayConcat = "" + parent.mlptoday.year + parent.mlptoday.month + parent.mlptoday.date; var remTimeConcat = remTime.replace(/\./g, ""); if (remTimeConcat < todayConcat) { //the input time is in the past } Just make sure the dates and months always have the leading zero.
Check if Number entered is correct By ID - JavaScript
Would like to know how to check true and false and in return give error message if checked and the number is incorrect.. <input name="student1" type="text" size="1" id="studentgrade1"/> <input name="student2" type="text" size="1" id="studentgrade2"/> <input name="student3" type="text" size="1" id="studentgrade3"/> so here we have 3 inputbox , now i would like to check the result by entering number into those inputbox. studentgrade1 = 78 studentgrade2 = 49 studentgrade3 = 90 << Using JavaScript >> So If User entered wrong number e.g "4" into inputbox of (studentgrade1) display error.. same for otherinputbox and if entered correct number display message and says.. correct. http://jsfiddle.net/JxfcH/5/
OK your question is kinda unclear but i am assuming u want to show error if the input to the text-box is not equal to some prerequisite value. here is the modified checkGrade function function checkgrade() { var stud1 = document.getElementById("studentgrade1"); VAR errText = ""; if (stud1.exists() && (parseInt(stud1.value) == 78){return true;} else{errText += "stud1 error";} //do similiar processing for stud2 and stud 3. alert(errText); }
See demo → I think this is what you're looking for, though I would recommend delimiting your "answer sheet" variable with commas and then using split(',') to make the array: // answers var result ="756789"; // turn result into array var aResult = []; for (var i = 0, il = result.length; i < il; i+=2) { aResult.push(result[i]+result[i+1]); } function checkgrade() { var tInput, msg = ''; for (var i = 0, il = aResult.length; i < il; i++) { tInput = document.getElementById('studentgrade'+(i+1)); msg += 'Grade ' + (i+1) + ' ' + (tInput && tInput.value == aResult[i] ? '' : 'in') + 'correct!<br>'; } document.getElementById('messageDiv').innerHTML = msg; } See demo →
Try this http://jsfiddle.net/JxfcH/11/ function checkgrade() { var stud1 = document.getElementById("studentgrade1"); var stud2 = document.getElementById("studentgrade2"); var stud3 = document.getElementById("studentgrade3"); if (((parseInt(stud1.value) == 78)) && ((parseInt(stud2.value) == 49)) && ((parseInt(stud3.value) == 90))) { alert("correct"); } else { alert("error correct those values"); } }