i have an array which contains some values. i want if the textbox's value contains a value from any of the element of that array it will show alert "exists", otherwise "doesn't exists"
I have tried the following code:
$('[id$=txt_Email]').live('blur', function (e) {
var email = $('[id$=txt_Email]').val();
var array = ['gmail.com', 'yahoo.com'];
if (array.indexOf(email) < 0) { // doesn't exist
// do something
alert('doesnot exists');
}
else { // does exist
// do something else
alert('exists');
}
});
But this is comparing the whole value with the array's element. i want to use contains function as we can in C# with string.Please help me.
I want if user type "test#gmail.com" it will show exists in array. if user enter "test#test.com" it will alert doesnot exists.
I think you want
$.each(array, function () {
found = this.indexOf(email);
});
To find the match not exact string you need to do some thing like
Live Demo
arr = ['gmail.com', 'yahoo.com'];
alert(FindMatch(arr, 'gmail.co'));
function FindMatch(array, strToFind)
{
for(i=0; i < array.length; i++)
{
if(array[i].indexOf( strToFind) != -1)
return true;
}
return false;
}
$(document).on('blur', '[id$=txt_Email]', function (e) {
var email = this.value, array = ['gmail.com', 'yahoo.com'];
if (email.indexOf('#')!=-1) {
if ($.inArray(email.split('#')[1], array)!=-1) {
alert('exists');
}else{
alert('does not exists');
}
}
});
FIDDLE
b is the value, a is the array
It returns true or false
function(a,b){return!!~a.indexOf(b)}
Related
I have this JS code, I need to compare the input value with the array, if the input value match with some value in the array then show the related message, but I can't get the array values and compare them with my input value.
var invalidkeyreservation = ['ABCDEF','GHIJK','LMNOP'];
if ($("input.reservationkey").val() === invalidkeyreservation) {
BootstrapDialog.show(return $content;}
} else{
window.location.href = "/branches/Cancelaciones/Seleccion.html";
}
This is what .indexOf() is for.
var invalidkeyreservation = ['ABCDEF','GHIJK','LMNOP'];
if (invalidkeyreservation.indexOf($("input.reservationkey").val()) > -1) {
BootstrapDialog.show(return $content;}
} else{
window.location.href = "/branches/Cancelaciones/Seleccion.html";
}
Maybe you want to use includes:
var invalidkeyreservation = ['ABCDEF','GHIJK','LMNOP'];
if (invalidkeyreservation.includes($("input.reservationkey").val())) {
BootstrapDialog.show(return $content;}
} else{
window.location.href = "/branches/Cancelaciones/Seleccion.html";
}
Obs: If you are targeting to old browsers, there is polyfill available, or just use indexOf, as shown in the other answer.
You should be able to see if one of the elements in the array includes any of the string value, like so:
ES6
const invalidkeyreservation = ['ABCDEF','GHIJK','LMNOP'];
if(invalidkeyreservation.some(key => key === $("input.reservationkey").val()) {
BootstrapDialog.show(return $content);
} else{
window.location.href = "/branches/Cancelaciones/Seleccion.html";
}
ES5
var invalidkeyreservation = ['ABCDEF','GHIJK','LMNOP'];
if(invalidkeyreservation.indexOf($("input.reservationkey").val()) > -1) {
BootstrapDialog.show(return $content);
} else{
window.location.href = "/branches/Cancelaciones/Seleccion.html";
}
try like
var toCheck = $("input.reservationkey").val().trim().toUpperCase();
if (invalidkeyreservation.includes(toCheck )) {
//your code with the condition
}
Hope, it helps
To simplify my problem i rewrote the code without the parsing of CSV, but instead with a variable that holds the data.
--CODE EDIT---
$(document).ready(function() {
var qID = 'xxx';
var source = ['text1', 'text2', 'etc3'];
var source2 = ['text4', 'text5', 'etc6'];
$('#question' + qID + ' input[type="text"]').change(function() {
var validVal = 0;
var inputVal = $(this).val();
// Loop through the text and test the input value
$(source).each(function(i) {
if (inputVal == this) { // If a match is found...
validVal = 1;
}
});
// If a valid text was entered
if (validVal == 1) { // A valid input
alert("GOOD");
} else { // An invalid input
alert("NOT GOOD");
}
var validVal2 = 0;
var inputVal2 = $(this).val();
$(source2).each(function(j) {
if (inputVal2 == this) { // If a match is found...
validVal2 = 1;
}
});
// If a valid text was entered
if (validVal2 == 1) { // A valid input
alert("GOOD2");
} else { // An invalid input
alert("NOT GOOD2");
}
});
});
The script works fine for one source (var source) but i want to check in the same text field 2 variables (source, source2) that will produce different alerts.
The script is run through a limesurvey form and the input is a simple [type="text"] field.
How do I check for 2 different arrays of text in the same text field?
Whenever you find yourself putting counters on variable names to create a series, you need to stop and think about what you are actually doing there. Making counted variable names is always wrong.
Use arrays.
var qID = 'xxx';
var source = [];
source.push(['text1', 'text2', 'etc']);
source.push(['text1', 'text2', 'etc44']);
source.push(['text15', 'text25', 'etc454']);
$('#question' + qID + ' input[type="text"]').change(function() {
var valid = false;
var inputVal = $(this).val();
$.each(source, function(i, terms) {
$.each(terms, function(i, term) {
valid = inputVal === term;
return !valid; // returning false stops the .each() loop
});
return !valid;
});
if (valid) {
alert("GOOD");
} else {
alert("NOT GOOD");
}
});
A more appealing way to express the nested loop above uses built-in methods of Array.
var valid = source.some(function (terms) {
return terms.includes(inputVal);
});
in ES6 syntax this can be made a one-liner:
var valid = source.some(terms => terms.includes(inputVal));
I have two issues:
I want user to add the values in the dropdown but before that I am checking if the value is already present in that using this function:
function IsNameAlreadyPresent(List,Name){
$.each($("'#'+List option"),function(i,e){
if(e.innerHTML == Name){
return true;
}
});
}
function AddOptionName() {
var Name = $("#txtName").val();
if(IsNameAlreadyPresent(List,Name)) {
alert("Name \"" + Name + "\" already exists. \nPlease type an unique name.")
}
else{
AddNewOption(Name);
}
}
I want to use this same function many times in my code to check whether the value entered is unique or not by passing the id of the dropdown and the name to be entered. but somehow this doesnt work.
how to pass the id as a parameter ($("'#'+List option")?
I am using the same function to edit the text of the option as well. but somehow if the user clicks edit and he doesnt want to change the text and clicks OK it gives an alert that the option is already present.
The option is only once including the one open in the popup. how to check this ?
var x = document.getElementById("List");
var l_sName = x.options[x.selectedIndex].text;
$("#List option[value="+l_sName+"]").remove();
Your selector is wrong, it should be $("#"+List+" option"). Also return inside $.each() will not return from your function, but break $.each() if false. Change your IsNameAlreadyPresent(List,Name) to this:
function IsNameAlreadyPresent(List, Name) {
var result = false;
$.each($("#"+List+" option"), function (i, e) {
if (e.innerHTML == Name) {
result = true;
return false;
}
});
return result;
}
For this part you can add a name to be excluded for checking, for example:
function IsNameAlreadyPresent(List, Name, Excluded) {
var result = false;
$.each($("#"+List+" option"), function (i, e) {
if (e.innerHTML == Name && e.innerHTML != Excluded) {
result = true;
return false;
}
});
return result;
}
function AddOptionName(Excluded = "") {
var Name = $("#txtName").val();
if (IsNameAlreadyPresent(List, Name, Excluded)) {
alert("Name \"" + Name + "\" already exists. \nPlease type an unique name.")
} else {
AddNewOption(Name);
}
}
and then call it with AddOptionName( $("#"+List+" option:selected").html() );
I fill my array in the checklistRequest.js and I want to access it in my Termine_1s.html file which contains js code. I can access it but when I want to iterate through it, it gives me only single digits instead of the strings.
How can I solve this?
checklistRequest.js
//Calls the checkbox values
function alertFunction()
{
//Retrieve the object from storage
var retrievedObject = localStorage.getItem('checkboxArray');
console.log('retrievedObject: ', JSON.parse(retrievedObject));
return retrievedObject;
}
Termine_1s.html
//Checks if title was checked already
var checklistRequest = alertFunction();
var titleAccepted = true;
for (var a = 0; a < checklistRequest.length; a++)//Iterates through whole array
{
if(title != checklistRequest[i] && titleAccepted == true)//Stops if false
{
titleAccepted = true;
}
else
{
titleAccepted = false;
}
}
you need to parse the object at some point.
Try:
return JSON.parse(retrievedObject);
I am new to Javascript.
I need to make an username input, then validate it.
The username entered must not be one of the elements in this array: ["admin", "administrator", "demo", "user"] etc. The array can be longer.
I made this so far, but it works only for the 1st element in the array.
function arrayValidation () {
nonoUser = ["username", "admin", "administrator", "demo"];
valueOfInput = document.getElementById("user").value; // "user" here is id of input
for (var i = 0; i < nonoUser.length; i++) {
if (valueOfInput == nonoUser[i]) {
alert("you cant use this username");
}else {
return;
}
}
}
Try this:
function arrayValidation () {
nonoUser = ["username", "admin", "administrator", "demo"];
valueOfInput = document.getElementById("user").value; // "user" here is id of input
var isValid = true;
for (var i = 0; i < nonoUser.length && isValid; i++) {
if (valueOfInput == nonoUser[i]) {
isValid = false;
}
}
if (isValid) {
// Username is valid
}else{
// Username is invalid
}
}
However, you should never trust data that's sent to the server (Validate server-side as well)
It's trivial to change the js as a user.
This should point you in the right direction:
document.getElementById("user").onkeyup = function(){
var nonoUser = ["username", "admin", "administrator", "demo"];
nonoUser.indexOf(this.value) === -1 ? false : this.value = '';
}
demo: http://jsfiddle.net/Le2xC/
I also hope you're validating this server-side as well, otherwise users will still be able to use your "nono" usernames.
you need to add return false; to the code section with the alert, not the else statement.
The comments here should help you to see why your code isn't working as you expect:
// Your original code:
function arrayValidation () {
nonoUser = ["username", "admin", "administrator", "demo"];
valueOfInput = document.getElementById("user").value; // "user" here is id of input
for (var i = 0; i < nonoUser.length; i++) {
if (valueOfInput == nonoUser[i]) {
alert("you cant use this username");
} else {
// Using return here is the problem.
// This else block will run if a valid username was entered.
// The return statement stops execution of the function, thus ending the loop.
// So if the loop passes the test the first time, this return
// statement will stop the loop and function from completing
// the checks against the other keywords.
return;
}
}
}
This is your code modified to work as you expect:
function arrayValidation () {
nonoUser = ["username", "admin", "administrator", "demo"];
valueOfInput = document.getElementById("user").value; // "user" here is id of input
for (var i = 0; i < nonoUser.length; i++) {
if (valueOfInput == nonoUser[i]) {
alert("you cant use this username");
// We can end the function check return here.
// There's no point checking the others, as we've found an invalid one.
return false; // Return a meaningful result
}
// No need for an else statement either.
}
}
As many have pointed out, client side validation should be considered an optional extra, and server-side validation as essential.