I am using an input field to put user inputs in an array.
I want to check if the user inputted number is already in the array or not. And if it is in the array then the input should not be re-added.
Here is my attempt.
if(e.keyCode === 43){
var num = document.getElementById("numbers").value;
var oks = [];
// set num
// check if num is in the oks array
if( oks[num]==num ){
alert("It is already there.");
}
else{
oks[num.value]=num.value;
}
console.log(oks.value);
}
With the above code it says undefined in the console log.
Please help me find where I am wrong in this.
Thanks a lot :)
Your code has lots of mistakes, such as :
var oks = [];
The above is saying that every time the user inputs something, the array is empty, therefore there is nothing there, therefore the value is not there, so there is no use of trying to know whether the value exists or not, because it doesn't, so you should declare the oks variable outside of the eventListener.
oks[num]
The above is not the value, it's the element in the array whose index is the value, which are very different.
num.value
The above is a syntax error, because the num variable is a number not a dom element that has a value attribute.
And here's the solution to your problem :
if( oks.indexOf(num)>-1 ){
alert("It is already there.");
}
else{
oks.push(num);
}
you can do
if(oks.indexOf(num) != -1)
to check whether it lies in the array or not or alternatively you could use oks as an object and check if a fiels of a similar value is defined or not, which should be more efficient
var oks = [];
is being initialised on every request, hence it is always empty, initialise it at a parent/global scope, you should use
var oks = {};
// at a parent scope
if(e.keyCode === 43){
var num = document.getElementById("numbers").value;
// set num
// check if num is in the oks array
if( oks{num} != undefined ){
alert("It is already there.");
}
else{
oks[num]=true;
}
console.log(oks.num);
}
Related
Here is a function for a popup search function, which, when a word is typed, and enter is pressed (the handleKeyPress(e) function, it automatically goes to say, dogs.html (its a kids language learning app). However say they type 'dogg' and not 'dog', Iw ould like it to go to a designated error page. I cannot code at all and have only manipulated other people's scripts. for example, the directory
would have a list of animals.html, i.e. dog.html, cat.html, etc. but if a word is typed that is not in this directory
(there should be a search function to see if *.html is there or not, then go to error page if its not there. But I can't do this. I have no training. Can anyone help me with this? I hope I don't get thrown off this forum again, you really shouldn't be so harsh on idiots...!)
i.e. what I need is : if .value+'.html' not in dir;
goto errorpage.html
Here's "my" code to load whatever word's page that's typed in:
function goTo()
{
location.href = document.getElementById('link_id').value + '.html';
/*window.location.replace("spellcheck.html");*/
}
function handleKeyPress(e){
var key=e.keyCode || e.which;
if (key==13){
goTo();
/*window.location.replace("spellcheck.html"); */
}
}
You would probably have to use an XmlHttpRequest to check if the file exists in the location specified or not and redirect to the error page if the file doesn't exist. But this raises it's own set of problems.
Or, you could create a service on the server that could tell you the same. Either way it's not super easy.
As mentioned earlier, you can create an array that can hold all of the values for the pages you know to exist in your site.
(there's a decent amount of commented text in the code snippet for further details)
JavaScript arrays: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
JavaScript .indexOf() (in relation to arrays): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
A JavaScript array is a series of data that is common separated inside of square brackets. Each element is automatically assigned an index value so that developers can quickly reference specific pieces. However, it's important to know that arrays start their index number at 0...
So, in this example:
const arrayName = ['element1', 'element2', 'page3', 'dog']
'element1' is at index 0 inside arrayName
'element2' is at index 1 inside arrayName
'page3' is at index 2 inside arrayName
'dog' is at index 3 inside arrayName
You can use JavaScript array's .indexOf() to find these array index values. If an element does not exist within an array then .indexOf() will return -1 (negative one).
arrayName.indexOf( 'dog' ) === 3
// get the input element that's getting the text
const linkID = document.getElementById('link_id');
// get the search button
const linkBtn = document.getElementById('link_btn');
// listen for when the keyup event (so when the user is
// typing, this will trigger when a key is released)
linkID.addEventListener('keyup', (e)=>{
// get the keyCode to test for [ENTER]/13
let key = e.keyCode || e.which;
// get the textBox element
let target = e.target || e.srcElement;
// test if the [ENTER] key was hit
if( key === 13 ){
// if [ENTER] test the value
processPage( target.value );
}
});
// Listen to the click event on the search button to
// kick off the process workflow...
linkBtn.addEventListener('click', ()=>{
processPage( linkID.value );
});
// Broke this out so that the processing of the text
// field can be done by [ENTER] or by clicking a
// search button
function processPage( val ){
// checkPage will return true/false if the text matches
// a page in the array list
if( checkPage( val ) ){
// if the page does exist, then kick off the redirect
goTo( val );
}else{
// display an error message
alert( 'Sorry, the page you are looking for does not exist' );
// reset the value of #link_id
linkID.value = '';
}
}
// This function checks if the text value submitted matches
// one of the static pages saved to the array
function checkPage( val ){
// pages[] is an array that holds all the pages you know
// to exist
const pages = ['dog', 'cat', 'bunny'];
// .indexOf() will return the array position of a search
// query (in this case the value of val)
// Arrays start at 0 so if the user searches "dog" the
// .indexOf() will provide the answer 0.
// If an element does not exist, .indexOf() returns -1
// By assigning this as a condition:
// "is the index of val from the array pages[] greater
// than or equal to 0?"
// we create a condition that will return true/false
return ( pages.indexOf( val ) >= 0 );
}
function goTo( val ){
console.log( val + '.html' );
// location.href = val + '.html';
}
<input type="text" id="link_id" /><button id="link_btn">search</button>
I have an input field where the user inputs their zip code which I then attempt to match to a zip code within an array. While the following works, I need it to actually show an alert dialog once saying that zip code wasn't found, however, it current pops up a lot even if the zip code is in the list.
Here's my snippet:
_zipcodeBtn.onclick = function(){
var userZip = _zipcode.value;
for (var i = 0; i < zipcode_list.length; i++) {
if (zipcode_list[i] === userZip) {
console.log('works');
break;
} else {
alert("repeating");
}
}
};
I want it to check if their zip is available without it also repeating the else statement multiple times. Whats the best way to prevent this?
There's an easier way to find an item in an array, by referencing the array's indexOf() method (docs).
if (zipcode_list.indexOf(userZip) != -1) {
//found - do something
} else
alert('Zip not found!');
As Angel Politis shows, you can also use includes() if you literally just want to know whether an item is in an array, not its actual position within it.
Sidenote: it's important to check against -1 when using indexOf() because it returns the index at which the search is found - or -1 if it's not. If the search is found at the first key, this is 0, and 0 is a falsy value, which can catch people out sometimes when they do things like this:
var arr = [1, 2, 3];
if (arr.indexOf(1))
alert('success');
else
alert('failed');
You'd think the success alert would fire here, but actually it'll be the failure alert, because indexOf() in this case returns 0, and 0 is a falsy value when it's interrogated in a condition.
There's no need to use a loop here. You can just say:
if (!zipcode_list.includes(userZip)) alert("Doesn't work!");
If you must use a loop, then just set a flag by default to false and then, if the zip is found set it to true. Then you can check it outside the loop:
/* Create a flag and set it by default to false. */
var found = false;
/* Loop */
for (var i = 0, l = zipcode_list.length; i < l; i++) {
if (zipcode_list[i] === userZip) {
/* Set the flag to true and stop the loop. */
found = true;
break;
}
}
/* Check whether the zip was found in the array. */
if (found) console.log("Works!");
else alert("Doesn't work!");
I'm using the code below to check if var1 exists, then assigning another variable (promt) to store var1 provided that the user types in the variable. Problem is I have about twenty variables I need to check so my code looks like the below times ten:
if (typeof var1 !== 'undefined') {
if(selection==var1){
var promt = var1;
}
}
if (typeof var2 !== 'undefined') {
if(selection==var2){
var promt = var2;
}
}
This (a) makes a ton of inefficient code and (b) may cause errors if I have over twenty variables. Is there a way to check if var1, var2, var3, etc.. exists then stop checking when the variables stop?The goal is to be able to have one hundred variables and still have the same amount of code I would have if there were two.
If your variables are fields on an object you can easily build the field names dynamically:
fieldname = 'var' + index;
if (typeof obj[fieldname] !== 'undefined') {
if (selection == obj[fieldname]){
var promt = obj[fieldname];
}
}
For local variables I however can't provide a solution.
First thing first var is reserved word in javascript, so you cannot use it as variable names, hence I use _var here instead.
I made a jsFiddle for this solution, so check it out pls.
You may also look at the code below:
for (i in _var) {
// Loop through all values in var
if ((typeof _var [i] !== undefined) &&
selection_array.indexOf(_var [i]) >= 0) {
// note that array.indexOf returns -1 if selection_array does not contain var [i]
prompt = _var[i]; // use this if you only want last var[i] satisifying the condition to be stored
prompt_array.push(_var[i]);// use this if you want to store all satisifying values of var[i]
}
}
Also check the below snippet
// Lets declare and give some example value to _var, Note that you cannot use var as variable name as it is a reserver word in javascript
var _var = ['foo1', 'foo2', 'foo3', 'foo4'];
// Declare a variable called prompt (actually not necessary normally)
var prompt;
// Declare a array called prompt_array to store the output
var prompt_array = [];
// Declare and give some example value to selection_array
var selection_array = ['foo2', 'foo3'];
// main program to solve the problem
for (i in _var) {
// Loop through all values in var
if ((typeof _var [i] !== undefined) &&
selection_array.indexOf(_var [i]) >= 0) {
// note that array.indexOf returns -1 if selection_array does not contain var [i]
prompt = _var[i]; // use this if you only want last var[i] satisifying the condition to be stored
prompt_array.push(_var[i]);// use this if you want to store all satisifying values of var[i]
}
}
// output for visualizing the result
document.getElementById('output').innerHTML += 'prompt = ' + prompt + '<br/>';
document.getElementById('output').innerHTML += 'prompt_array = ' + prompt_array.toString();
<div id="output">
</div>
You can ask me through commenting if you have a further problem on this :D.
I can't seem to quite figure this one out; not sure if I'm even providing a test
condition; Also, "blanks" variable is to hold the value of the elements with the".required" class during the loop.
function containsBlanks(){
var blanks = new Array();
$required.each(function(){
blanks.($(this).val() == "");
});
return(true);
}
Loop over your Nodes and check their value against ""..
function containsBlanks() {
var i, req = $('.required');
for (i = 0; i < req.length; ++i)
if (req[i].value === '')
return true;
return false;
}
If I understand you can do this like:
$('input.required').filter(function(){ return !this.value });
That will give you all required inputs that have an empty value (if any). Then you can check the length property to find out if there are any elements in that collection.
function checkData() {
var temp = 0;
var totalMarks = countMark(temp);
if (totalMarks != 100)
window.alert("Marks must total 100");
}
function countMark(mark) {
var totalMark = 0;
totalMark += parseInt(mark)
return totalMark;
}
function doAdd() {
var taskid = document.getElementById("taskid").value;
var taskname = document.getElementById("taskname").value;
var taskmark = document.getElementById("taskmark").value;
if (taskid.length === 0)
window.alert("Task Id cannot be empty!");
if (taskname.length === 0)
window.alert("Task name cannot be empty!");
if (taskmark.length === 0)
window.alert("Task Mark cannot be empty!");
else if (!markpattern.test(taskmark))
window.alert("Invalid data in mark field");
var marks = parseInt(document.getElementById("taskmark"));
if (marks < 0 || marks > 100)
window.alert("Marks out of range. Please re-enter");
countMark(marks);
}
My question is when i keep call the doAdd() function. my marks will keep adding . want to do like passing reference like in C++ . my function countMark(...) will keep adding .
after that, when my form submitted, my form will call the function checkData()
If my totalmark is not 100 . will prompt out the alert and error.
but my code is not working . I guess that my countMark function wrong somewhere
If I understand you correctly, you're looking for the equivalent of a static variable - something that gets initialized the first time the function is called, and keeps it's value for subsequent calls.
Take a look at this related question: https://stackoverflow.com/a/1535650/2444111
The top answer (by CMS) is talking about class-based static variables, which are not quite the same thing.
The second answer (by Pascal MARTIN) is what you're looking for. It takes advantage of the fact that JS functions are also objects, and stores the variable as a property of the function object. This is a better solution than using a global variable (or a property of window, which is what a global actually is)
There are several issues in your code and it's really hard to say what your intention was. But I will address what I found.
In the following piece of code you are requesting a DOM Element and try to parse it as an Integer. The result of that type convertion is always NaN. Maybe wanted to get the value attribute of your element, like you did before. (Also, don't request the same element multiple times. Request it once, save the result in a variable and use that variable from that on).
var marks = parseInt(document.getElementById("taskmark"));
if (marks < 0 || marks > 100)
window.alert("Marks out of range. Please re-enter");
countMark(marks);
Your function countMark is pretty useless, because it will always return whatever Number you pass to it (see comments in your code).
function countMark(mark) {
var totalMark = 0; //create a new variable with value 0
totalMark += parseInt(mark) //add "mark" to that variable
return totalMark; //return that variable => 0 + mark = mark (and if mark = NaN => 0 + mark = NaN)
}
Maybe you wanted to make totalMark a global variable, than you would need to define it outside of your function:
var totalMark = 0;
function countMark(mark) {
totalMark += parseInt(mark);
return totalMark;
}
Last but not least, lets analyse your function checkData:
function checkData() {
var temp = 0; //create a local variable with value 0
var totalMarks = countMark(temp); //pass 0 to countMark => return 0 => totalMarks = 0
if (totalMarks != 100) //always true since totalMarks is always 0
window.alert("Marks must total 100"); //will always alert
}