Attempting to compare textbox with array element - javascript

I am trying to compare user entered text in a textbox with an element in an array but am having difficulties.
function checkAns()
{
var str = imageArray[randNum];
var n = str.indexOf(document.getElementById('textBox').value);
if(n == -1)
{
alert("Wrong Answer")
}
else
{
alert("Right Answer")
}
}
The user input should either match part of the the specified string in the array element and return Right Answer or not match at all and return Wrong Answer.
<input type=”text” id=”textBox” value=””>
<input type=”button” value=”Check” onclick=”checkAns()”>
I added the code for my textbox and button if that is useful.

Please check what exactly you need to get. This:
if (document.getElementById('textBox').value === str) {
// text from array element is the same as in value
} else {
// ... differs from value
}
Or this:
if (str.indexOf(document.getElementById('textBox').value) > -1) {
// text from value exists in array element
} else {
// ... does not exist
}
Or maybe this:
if (document.getElementById('textBox').value.indexOf(str) > -1) {
// text from array element exists in value
} else {
// ... does not exist
}

Related

How does the matching JS code using indexOf work?

I've managed to copy some JS over into my doc, and I've got it working. But I don't entirely understand how its doing it.
It's a search function to match with data in a table and hide any rows that don't match.
But I don't understand the active line of code that actually searches and matches. Would someone explain it?
$('#searchBar').keyup(function() {
searchFunction($(this).val());
});
function searchFunction(value) {
$('#results tr').each(function() {
var found = 'false';
$(this).each(function() {
if ($(this).text().toLowerCase().indexOf(value.toLowerCase()) >= 0) {
found = 'true';
}
});
if (found === 'true') {
$(this).show();
} else {
$(this).hide();
}
})
};
It's this line I can't get my head around:
if ($(this).text().toLowerCase().indexOf(value.toLowerCase()) >= 0) {
found = 'true';
}
I understand how it changes the variable to true, but I don't understand how it matches the data in the Table row with the Value fed in.
It converts the value you sent to the function to lowercase, and then looks at the data in the row. It converts that to lowercase too, and sees if there is a match using indexof, which is covered here: How to use IndexOf in JQuery
Basically, the indexOf() method returns the position of the first occurrence of a specified value in a string. It returns -1 if the value to search does not occur.
Consider searching for "test"
var str = "Hello this is a test";
var n = str.indexOf("test");
The result of n will be: 16, ergo, as in your script, larger than 0... and "found"
What it does is
For each rows in my table "result"
If one of all these values, that I look in lowercase, is equal to what I typed in the "searchBar" in lower case, more than one time, then I found it, and so found = "true"
From search bar key press event will be triggered and value of search bar will passed to search function
$("#searchBar").keyup(function() {
searchFunction($(this).val());
});
function searchFunction(value) {
//value will contain the value of search bar
$("#results tr").each(function() {
//assuming value is not there in tr
var found = "false";
//now searching for each tr for value
$(this).each(function() {
//converting to lower case and comparing each value with searchbar value
if (
$(this)
.text()
.toLowerCase()
.indexOf(value.toLowerCase()) >= 0
) {
found = "true";
}
});
//actual showing/hiding row
if (found === "true") {
$(this).show();
} else {
$(this).hide();
}
});
}
if need more info about index of
https://www.w3schools.com/jsref/jsref_indexof.asp
#MattCouthon let me know if you need anything else

JavaScript check for duplicate inputs in array and at least one letter

when I click on a button, I want to create an entry. This entry got a title and a text. Before I create the new entry, there should be checked, if this title already exists and if this title is empty. The check for empty is important because the text may not be " " (whitespace), this should have at least a digit / letter or number.
So this is what I got so far:
var entries = store.getEntries(); // the entry list. Each entry has the property "title"
function checkTitleInput(inputText) { // check the titleInput before creating a new entry
if (inputText.length > 0 && // field is empty?
/* at least 1 letter */ && // not just a whitespace in it?
/* no duplicate */ // no duplicate in the entry list?
)
return true;
return false;
}
Could someone help me out here?
Use Array#some and trim:
function checkTitleInput (inputText) {
var trimmed = inputText.trim();
var exists = entries.some((entry) => entry.title === trimmed);
return trimmed.length > 0 && !exists;
}
You could make it even shorter:
function checkTitleInput (inputText) {
var trimmed = inputText.trim();
return !!trimmed && !entries.some((entry) => entry.title === trimmed);
}
I would modify this function as
function checkTitleInput(inputText) {
inputText = inputText.trim();
if (inputText.length > 0 && entries.filter(entry=>entry.title.equals(inputText)).length==0)
return true;
return false;
}

Display error if element in array have 0 value

i have an array in javascript using map function. it collect data from a loop drop down. i just want to ask how to check if array have 0 then display error message. "One of the data not selected"
the array code :
var self_assess_check = $("select[name='self_assess[]'] option:selected").map(function() {
return $(this).text();
}).get();
alert(self_assess_check);
if i alert the array alert(self_assess_check); it produce : 1,0,2,-,-,5,0
how can i make if condition to check if whole array have 0 value then show error message
what i made:
if ((self_assess_check) == "0"){
alert("One of the data not selected");
return false;
}else{
var r=confirm("Make sure all answer is correct. Once Submit it cannot be changed");
if (r==true){
}else{
return false;
}
}
i think my if condition not correct since it will go to else and skip if.tq
Use $.inArray()
if ($.inArray('0', self_assess_check) != -1) {
alert("One of the data not selected");
return false;
} else {
var r = confirm("Make sure all answer is correct. Once Submit it cannot be changed");
if (r == true) {
} else {
return false;
}
}
Note: Array.indexOf() is not used since IE8 might have to be supported.
You can check Array as below code.
function isUndefined(targetO){
return (targetO == 'undefined' || targetO == undefined);
} if(!isUndefined(self_assess_check){ if(self_assess_check.length!=0){alert("Array contain values"); }}
This will work.

Including a for loop in an if statement

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.

Check select box values and compare them with an input

I would like to check if a textfield, newTeamName is already in a list of teamnames stored in a select box. Unfortunately, my code does not work - what's wrong with it? Oh and I have no console problems.
optionList = [];
$('#chooseTeam option').each(function() {
optionList.push($(this).val())
});
if (form.newTeamName.value in optionList) {
$("#text-error").html("Team exists");
$('#text-error').fadeIn(400).delay(3200).fadeOut(800);
return false;
}
Small Update:
Oh and my form.name.value's work fine as they work for other if statements.
optionList is an array in used for object properties(or numeric array indices), you can use indexOf to test if a value is in an array
optionList = [];
$('#chooseTeam option').each(function() {
optionList.push($(this).val())
});
if (optionList.indexOf(form.newTeamName.value) > -1) {
$("#text-error").html("Team exists");
$('#text-error').fadeIn(400).delay(3200).fadeOut(800);
return false;
}
Fixed it.
$('#chooseTeam option').each(function() {
if (form.newTeamName.value == $(this).val()){
$("#text-error").html("Team exists");
$('#text-error').fadeIn(400).delay(3200).fadeOut(800);
return false;
}
});
try something like this
my_array = Array();
//To find if a value or element exists in an array
if (my_array.indexOf(‘find_this_value’) != -1)
{
alert(‘Value exists in array.’);
}
//To find if a value or element DOES NOT exist in an array
if (my_array.indexOf(‘find_this_value’) == -1)
{
alert(‘Value does not exist in array.’);
}

Categories