The second if does not work, and the third one does not work if I put a variable instead of "2" I was trying to put if (cont==len) but does not work. Which is the problem?
function alert(Vform){
var i=0;
var cont=0;
var len=Vform.length;
for (i=0;i<=len;i++){
if (Vform.elements[i].checked!=true){
cont=cont+1
}
}
if (cont!=2){
window.alert("Please select date and time");
}
}
Try to do these changes:
function alert(Vform)
{
var cont=0;
var len=Vform.length;
for (var i=0;i<=len;i++)
{
if (Vform.elements[i].checked!=true)
{
cont++;
}
}
if (cont != 2)
{
alert("Please select date and time");
}
}
Your for loop should be like this.
for (i=0;i<len;i++){
//code
}
It should check i<len and not i<=len because array element start with zero based index
Related
I am trying to make some kind of search function, where a pop-up would appear and ask for an input from the customer and then compare it to the array items and return another alert window with either "found" or "not found"
Here is my code for the specific function:
this.searchItem = function(){
var searchInput = window.prompt('Enter the search value:','');
var i;
for (i = 0; i< model.items.length; i++){
if (model.items[i] == searchInput) {
window.prompt("found");
} else {
window.prompt("not found");
}
}
}
It is kind of working. The problem is that it keeps showing a new alert window for every single element in the array. For example if I have 6 elements in the array and only one is matching the search input, then it will show me 5 alert windows with "not found" and one with "found". Another one appears after i close the previous one or if I click the ok button. How do I make it show me the alert window only once to tell me if it found it or not? Thanks!
Put the alert (not prompt) after the loop. Also need to switch to using a variable to track whether or not the item was found:
this.searchItem = function(){
var searchInput = window.prompt('Enter the search value:','');
var i;
var found = false;
for (i = 0; i< model.items.length; i++){
if (model.items[i] == searchInput) {
found = true;
break;
}
}
window.alert(found ? 'found' : 'not found');
}
Instead of showing the alert every time, set a variable such as var found=true. After loop terminates then show alert based on status of that var.
To show alert only once you have to execute the alert after loop ends, not inside loop.
Since you aren't doing anything else in your function after the loop, you can simply return when you find the element you were looking for. And only display the "not found" if you finish the loop without finding the element.
this.searchItem = function(){
var searchInput = window.prompt('Enter the search value:','');
var i;
for (i = 0; i< model.items.length; i++){
if (model.items[i] == searchInput) {
window.alert("found");
return;
}
}
window.alert("not found");
}
You could also simplify this by using Array.prototype.indexOf or Array.prototype.includes
this.searchItem = function(){
var searchInput = window.prompt('Enter the search value:','');
var i;
var found = false;
for (i = 0; i< model.items.length; i++){
if (model.items[i] == searchInput) {
found = true;
}
}
if(found == true)
window.prompt("found");
else
window.prompt("not found")
}
you are telling it to show the message every time it finds one, if you are seeking to finding only 1 match then just terminate the loop when you find it.
End the loop using break; or simply just set i to the arrays length:
......
if (model.items[i] == searchInput) {
window.prompt("found");
return 0;
}
.....
window.prompt("Not found"); //if fucntion doesn't return then it's not found.
OR
var found = false;
......
if (model.items[i] == searchInput) {
window.prompt("found");
found = true;
break;
}
.....
if(!found) window.prompt("Not found");
OR
......
if (model.items[i] == searchInput) {
window.prompt("found");
found = true;
i = items.length;
}
.....
if(!found) window.prompt("Not found");
I am new to javascript and struggling with the use of arrays.
I am trying to check if user input value is in an array I declared called fruits. If it is I want to execute code. If it is not I want an alert displayed. I tried using the
instanceof
method to check the value but the code doesn't execute any of the if else statement. Any ideas as to why?
$("#submit-btn").bind("click", function() {
var comment = $("#comments");
var commentValue = $.trim(comment.val());
var index;
var fruits = ["Banana", "Orange", "Apple", "Mango"];
for (index = 0; index < fruits.length; index++) {
text += fruits[index];
if (commentValue.length === 0) {
alert('Comments are required to continue!');
}
else if (commentValue instanceof fruits){
execute code
});
}
else {
alert('not a valid fruit');
}
return false;
}
});
Your first if should be outside the for loop.
Inside you simply change the else if to
if(commentValue === fruits[index])
And then you move the code inside the else out after the for loop.
A simpler way of doing it would be:
if (commentValue.length === 0) {
alert('Comments are required to continue!');
return false;
}
if(fruits.indexOf(commentValue) > -1) {
execute code
return false;
}
alert('not a valid fruit');
return false;
Try indexOf(), if indexOf return anything bigger then -1, you have match
like this:
else if (commentValue.indexOf(fruits[index]) > -1){
So, I want to check wether the input that I give is being correctly executed, but why does the if statement always return false even i give the correct input?
I don't want the solution only the need explanation. Please is there anyone who could explain? I've included my html input elements Just in case something wrong with it.
<script>
var text1 = ["O","K","E"];
var text2 = ["_","_","_"];
function guess(j){
for(i=0; i < text1.length; i++){
if(j == text1[i]){
text2[i] = j;
console.log(text2[i])
}
else {
console.log("try again")
}
}
}
</script>
The comment of #Unglückspilz in code:
// extra "K" to show how to handle multiple finds
var text1 = ["O","K","E","K"];
var text2 = ["_","_","_","_"];
function guess(j){
// a flag to set if one or more letters were found
found = false;
// check every letter in the haystack against given needle
for(i=0; i < text1.length; i++){
if(j == text1[i]){
// exchange underbar against found letter(s)
text2[i] = j;
console.log(text2[i]);
// set flag to true
found = true;
}
}
// no letter was correct
if(!found){
console.log("try again");
}
// return boolean if anything was found (but not how many)
return found;
}
I'm building an application in which I want to display some errors when a user enters invalid values in an input box. A correct value is appended as 'entry' to a div if no errors were found. In total there are 3 cases when to display errors:
The input value is empty
The input value is a number
The input value already exists
These errors are displayed with if else statements.
1.and 2. were easy, but the problem case (3.) only validates against the first element of class .cat_entry.
if(cat_input == '') { // generate errors
errorDisplay(error_input_empty);
} else if(!isNaN(cat_input)) {
errorDisplay(error_input_number);
} else if($('.cat_entry') == cat_input) { // THIS IS THE PROBLEMATIC LINE
// .cat_entry is the class of the entries that have been appended
errorDisplay(error_duplicate);
} else {
// stuff
};
So I believe I need a for loop/ .each() (no problem so far), but how do I include this as a condition in an if statement? Something like.. if( for(i=0;i<$('.cat_entry').length;i++) { ... }; ... How to return true (or something similar) when one of the entries matches the input value, then pass the return value to the if statement?
EDIT: here is a jsFiddle with the relevant code. I updated it with $.inArray() method. I'd like to try and use this instead of a for / .each() loop.
You can try this:
var a=$('.cat_entry'),o={};
for(i=0;i<a.length;i++) {
var s=a[i].val();
if(s in o){
errorDisplay(error_duplicate);
return;
}
o[s]=true;
}
or
var o={};
$('.cat_entry').each(function(){
var s=$(this).val();
if(s in o){
errorDisplay(error_duplicate);
return;
}
o[s]=true;
}
You can actually use the jQuery inArray function for this, such as:
else if($.inArray(cat_input, $('.cat_entry') != -1)
}
The solution was to add this to the function:
var isDuplicate = false;
$('.cat_entry').each(function() {
if(!$(this).text().indexOf(cat_input)) {
isDuplicate = true;
}
// And in the if else loop:
else if(isDuplicate == true)
//and just before the function ends
isDuplicate = false;
Thanks to all for the help you offered.
I have this chunk of code [sourced from different user on this site—thanks!] that I need to modify so that I can check multiple fields instead of just one. I'm not sure if I should be adding arguments to the second function or turn the variable checkString to an array.
function getField(fieldType, fieldTitle) {
var docTags = document.getElementsByTagName(fieldType);
for (var i = 0; i < docTags.length; i++) {
if (docTags[i].title == fieldTitle) {
return docTags[i]
}
}
}
function checkField() {
var checkString = getField('input', 'fieldtocheck').value;
if (checkString != "") {
if (/[^A-Za-z\d]/.test(checkString)) {
alert("Please enter only alphanumeric characters for the field fieldtocheck");
return (false);
}
}
}
I think the best option would be to feed "getfield" into the the "checkfield" as arguments but how would I do that?
Any help appreciated.
I would make your function more generic and use a class to identify the fields:
function checkFields(className, regex) {
var inputs = document.getElementsByClassName(className);
for (var i = 0; i < inputs.length; i++) {
if (!regex.match(inputs[i].value)) {
return false;
}
}
return true;
}
function validate() {
if (!checkFields('alphanum', /^[A-Za-z\d]+$/)) {
alert('Please enter only alphanumeric characters');
}
}
And your HTML could look like this:
<input type="text" class="alphanum" />
A much simpler (and better, IMO) approach would be to use the jQuery validation plugin.