I have this javascript and I get the error "function expected". I can't see anything wrong with my javascript. Please help. Thanks.
function checkrewardname()
{
var my=document.getElementById("Rname");
var con=my.value;
var mine=document.getElementById("forref").value.split('\n');
if (con == "")
{
alert("Enter a Reward Name.");
}
else
{
var i=0;
while(i<=mine.length)
{
if (mine(i) == con)//error here
{
alert("Duplicate reward. Please enter a new reward.");
}
else
{
document.getElementById("validate").click();
alert("The reward has been saved.");
}
i++;
}
}
}`
mine is an array but you are calling it as if it were a function. Use mine[i] rather than mine(i) and you'll access the array by index rather than generating an error. (Just a note; most C-style languages use [ and ] for array access and reserve ( and ) for function invocation).
You also have while(i<=mine.length)
shouldn't it be while(i < mine.length)
Related
how to write simple if take the first expression. Example bellow, my code is looks like to much.
i mean first condition email.val() and second !validateEmail(email.val()) with or expression. my big question is how to detect that first or second condition is executed ?
if(email.val() == "" || !validateEmail(email.val())){
//call the condition again
if(email.val() ==""){
$("#error").html("<p>Email Cant be empty</p>");
$("#error").show();
setTimeout(function(){$("#error").fadeOut();}, 2000)
}else{
$("#error").html("<p>Wrong email format</p>");
$("#error").show();
setTimeout(function(){$("#error").fadeOut();}, 2000)
}
email.focus();
}
so I don't need to call this if again
if(email.val() == ""){
$("#error").html("<p>Email Cant be empty</p>");
$("#error").show();
setTimeout(function(){$("#error").fadeOut();}, 2000)
}else{
$("#error").html("<p>Wrong email format</p>");
$("#error").show();
setTimeout(function(){$("#error").fadeOut();}, 2000)
}
Personally I do that way.
It allow in future to add other errors message or easy change them if needed.
// separate messages values to avoid long texts in the nested if part
// and prevent them from being searched for in parts of code
// where they can be scattered in several places, and possibly repeated
const errorMessage =
{ email_empty : '<p>Email Cant be empty</p>'
, email_wrong : '<p>Wrong email format</p>'
}
var messageError = ''
if(email.val()==='') { messageError = errorMessage.email_empty }
else if ( !validateEmail(email.val())) { messageError = errorMessage.email_wrong }
if (messageError) {
$("#error").html(messageError)
$("#error").show()
setTimeout(function(){$("#error").fadeOut();}, 2000)
email.focus()
}
You have roughly
if (condition1 || condition2) {
if (condition1) {
foo();
} else {
bar();
}
moo();
}
The else can only trigger when condition1==false and condition2==true, hence you can write the same as
if (condition1) {
foo();
moo();
} else if (condition2) {
bar();
moo();
}
So, as I see you're validating an email, there are two options you can look to avoid the nested if-else block or basically repeating your code again.
User Regex Expression: You can validate email, and check if it's empty as well.
if(!regexPat1.test(email)) {
// Do something
}
if(!regexPat2.test(email)) {
// Do something
}
Use nest condition : With this you can avoid rewriting same condition again.
if(email.val().trim() !=="") {
if(!validateEmail(email.val().trim()) {
//Throw invalid email error
}else {
// Do something
}
}else {
// Trow empty value error
}
There can be better solutions as well but I think this solves your doubt.
Simple rearrangement of your existing code.
if(email.val() == "") {
$("#error").html("<p>Email Cant be empty</p>");
$("#error").show();
setTimeout(function(){$("#error").fadeOut();}, 2000);
email.focus();
} else if (!validateEmail(email.val()) {
$("#error").html("<p>Wrong email format</p>");
$("#error").show();
setTimeout(function(){$("#error").fadeOut();}, 2000);
email.focus();
}
I want to repeat the code until the user gets the no. right. How do I do this ?
This is the code:-
function getRandomNumber(min,max){
return Math.floor(Math.random()*(max - min + 1 ))+min;
}
randomNumber=(getRandomNumber(1,10));
input=prompt("Please enter a no. between 1 and 10:","");
if(input==randomNumber){
console.log("Good Work");
}else{
console.log("not matched");
}
You could either use a while loop that calls a "break" statement once the user inputs the correct answer, or you could use a function like this:
function getInput(){
input=prompt("Please enter a no. between 1 and 10:","");
if(input==randomNumber){
console.log("Good Work");
}else{
consol.log("not matched");
getInput(); //Gets the user's input again
}
}
Here you go...
Found needs to be set to false before you start, otherwise the function will only run one. There is little point having the function definition inside the while loop, since it will be created as a global variable.
var found = false;
function getRandomNumber(min,max) { return Math.floor(Math.random()*(max - min + 1 ))+min; }
while ( found != true ) {
var randomNumber = getRandomNumber(1,10);
console.log('Random Number is..',randomNumber);
var input = prompt("Please enter a no. between 1 and 10:","");
if ( input == randomNumber ) {
alert('Well Done')
found = true;
} else {
console.log("not matched");
}
}
I'm fairly new to javascript and trying to list out the characters missing from a failed password to tell users what they need to input.
window.onload = function()
{
var info = document.getElementById("info");
var test = document.getElementById("myForm").test;
test.onclick = function(e)
{
e.preventDefault();
var pw = document.getElementById("myForm").pw.value;
var formula = /(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{6,}/;
if(formula.test(pw))
{
document.getElementById("myForm").submit();
}
else if pw.match(/\d/g) == null {
info.innerHTML = "You need a number";
console.log(pw.match(/\d/g))
} else {
info.innerHTML = "You need a number."
}
};
};
The above is just a first run through of checking if the user inputted a password with now numbers. But I keep getting an
Uncaught SyntaxError: Unexpected identifier
in chrome dev tools with the pw.match portion underlined. I've looked elsewhere online and my syntax looks correct. Where am I going wrong?
You need some parenthesis
else if (pw.match(/\d/g) == null) {
// ^ ^
You need parentheses around the condition of your if block.
else if (pw.match(/\d/g) == null) {
...
According to:
http://www.w3schools.com/js/js_if_else.asp
You have missed ( and ) in else if.
timeseries is an array in the following format:
[ {"date": "2012-12-21", "price": 1.234}, ... ]
My code:
function first(timeseries) {
if (timeseries.length === 0) {
return undefined;
}
var earliestIndex = 0;
for (var i = 0; i < timeseries.length; i++) {
if (timeseries[i].date === null) {
throw new Error("no date");
} else {
if(Date.parse(timeseries[i].date) < Date.parse(timeseries[earliestIndex].date)) {
earliestIndex = i;
}
}
}
return timeseries[earliestIndex].price;
}
Test result:
The question did not specify the exact value of date when not provided.
Why is this so? I have already thrown an error.
Couple of suggestions to cover all cases.
Test if timeseries[i].price is null or not before returning.
You may want to try using == instead of === as it will also do the necessary type conversions before check.
Reference: https://stackoverflow.com/a/359509/4874271
Tip: COPY the code and format it here instead of posting photos, would be easier for people to answer. :)
I'm having trouble validating an HTML form with JavaScript. On their own they each work, but together they don't.
This works:
// Make sure the e-mail address is valid
function validateEmail(mailform,email) {
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var address = document.forms[mailform].elements[email].value;
if(reg.test(address) == false) {
alert('E-mail not valid');
return false;
}
}
Attribute in the form:
onsubmit="javascript:return validateEmail('mailform', 'email');"
And this works:
// Make sure the message is long enough
function validateBody(mailform,mailbody) {
var msg = document.forms[mailform].elements[mailbody].value.length;
if (msg < 3) {
alert('Too hort');
return false;
}
}
Attribute in the form:
onsubmit="javascript:return validateBody('mailform', 'mailbody');"
But this doesn't work:
// Make sure the e-mail address is valid AND that the message is long enough
function validateForm(mailform,email,mailbody) {
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var address = document.forms[mailform].elements[email].value;
var msg = document.forms[mailform].elements[mailbody].value.length;
if(reg.test(address) == false) {
alert('Please enter a valid e-mail address');
return false;
} else if (msg < 3) {
alert('Text too hort');
return false;
}
}
Attribute in the form:
onsubmit="javascript:return validateForm('mailform', 'email', 'mailbody');"
Why?
As I said, they work each on their own, but even as different functions, they don't work together.
If you have two functions which work, why not use those?
function validateForm(mailform,email,mailbody) {
var addressValid = validateEmail(mailform,email);
var bodyValid = validateBody(mailform,mailbody);
return addressValid && bodyValid
}
The return will only return true if both tests are true. The advantage of this method is (as well as being likely to work) that it's easily extended and easily maintained.
If you only want one alert if there are two errors, then you'll need to test addressValid and call bodyValid only if required.
Use if (msg < 3) instead of else if (msg < 3) .
You don't need to use javascript: in the onsubmit attribute, remove that part.
Also, you would benefit greatly from using a JavaScript library such as jQuery.