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));
Related
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 trying to create an array and get all values of a form submission and put them in that array. I need to do this because during the .each function of this code I must do additional encryption to all the values per client. This is a form with hundreds of fields that are changing. So it must be an array to work. I tried to do following and several other types like it in jQuery but no dice. Can anyone help? Thanks.
Edit: Posted my working solution. Thanks for the help.
Edit 2: Accept sabithpocker's answer as it allowed me to keep my key names.
var inputArray = {};
//jQuery(this).serializeArray() = [{name: "field1", value:"val1"}, {name:field2...}...]
jQuery(this).serializeArray().each(function(index, value) {
inputArray[value.name] = encrypt(value.value);
});
//now inputArray = [{name: "field1", value:"ENCRYPTED_val1"}, {name:field2...}...]
//now to form the POST message
postMessages = [];
$(inputArray).each(function(i,v){
postMessages.push(v.name + "=" + v.value);
});
postMessage = postMessages.join('&');
Chack serializeArray() to see the JSON array format.
http://jsfiddle.net/kv9U3/
So clearly the issue is that this in your case is not the array as you suppose. Please clarify what this pointer refers to, or just verify yourselves by doing a console.log(this)
As you updated your answer, in your case this pointer refers to the form you submitted, how do you want to iterate over the form? what are you trying to achieve with the each?
UPDATE
working fiddle with capitalizing instead of encrypting
http://jsfiddle.net/kv9U3/6/
$('#x').submit(function (e) {
e.preventDefault();
var inputArray = [];
console.log(jQuery(this).serializeArray());
jQuery(jQuery(this).serializeArray()).each(function (index, value) {
item = {};
item[value.name] = value.value.toUpperCase();
inputArray[index] = item;
});
console.log(inputArray);
postMessages = [];
$(inputArray).each(function (i, v) {
for(var k in v)
postMessages[i] = k + "=" + v[k];
console.log(i, v);
});
postMessage = postMessages.join('&');
console.log(postMessage);
return false;
});
The problem is that #cja_form won't list its fields using each. You can use serialize() instead:
inputArray = jQuery(this).serialize();
Further edition, if you need to edit each element, you can use this:
var input = {};
$(this).find('input, select, textarea').each(function(){
var element = $(this);
input[element.attr('name')] = element.val();
});
Full code
jQuery(document).ready(function($){
$("#cja_form").submit(function(event){
$("#submitapp").attr("disabled","disabled");
$("#cja_status").html('<div class="cja_pending">Please wait while we process your application.</div>');
var input = {};
$(this).find('input, select, textarea').each(function(){
var element = $(this);
input[element.attr('name')] = element.val();
});
$.post('../wp-content/plugins/coffey-jobapp/processes/public-form.php', input)
.success(function(result){
if (result.indexOf("success") === -1) {
$("#submitapp").removeAttr('disabled');
$("#cja_status").html('<div class="cja_fail">'+result+'</div>');
}
else {
page = document.URL;
if (page.indexOf('?') === -1) {
window.location = page + '?action=success';
}
else {
window.location = page + '&action=success';
}
}
})
.error(function(){
$("#submitapp").removeAttr('disabled');
$("#cja_status").html('<div class="cja_fail"><strong>Failed to submit article! Check your internet connection.</strong></div>');
});
event.preventDefault();
event.returnValue = false;
return false;
});
});
Original answer:
There are no associative arrays in javascript, you need a hash/object:
var input = {};
jQuery(this).each(function(k, v){
input[k] = v;
});
Here is my working solution. In this example it adds cat to all the entries and then sends it to the PHP page as an array. From there I access my array via $_POST['data']. I found this solution on http://blog.johnryding.com/post/1548511993/how-to-submit-javascript-arrays-through-jquery-ajax-call
jQuery(document).ready(function () {
jQuery("#cja_form").submit(function(event){
jQuery("#submitapp").attr("disabled","disabled");
jQuery("#cja_status").html('<div class="cja_pending">Please wait while we process your application.</div>');
var data = [];
jQuery.each(jQuery(this).serializeArray(), function(index, value) {
data[index] = value.value + "cat";
});
jQuery.post('../wp-content/plugins/coffey-jobapp/processes/public-form.php', {'data[]': data})
.success(function(result){
if (result.indexOf("success") === -1) {
jQuery("#submitapp").removeAttr('disabled');
jQuery("#cja_status").html('<div class="cja_fail">'+result+'</div>');
} else {
page = document.URL;
if(page.indexOf('?') === -1) {
window.location = page+'?action=success';
} else {
window.location = page+'&action=success';
}
}
})
.error(function(){
jQuery("#submitapp").removeAttr('disabled');
jQuery("#cja_status").html('<div class="cja_fail"><strong>Failed to submit article! Check your internet connection.</strong></div>');
});
event.preventDefault();
event.returnValue = false;
});
});
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)}
My knowledge of jQuery and more specifically javascript has always been very limited and I am working hard to get better.
With that in mind I am trying to create some sort of "extensible validation framework" in that I can create an object with a validation function and its error message, push it into an array and then call all those methods and report the messages from the ones that fail.
So first I did something very simple just to see that the basic validation worked which was this:
var selectedTourDate = $("#tourDate").val();
var list = $("#bookedTourDate *");
var isDateBooked = list.filter(function () {
return (this.innerHTML == selectedTourDate) ;
}).length !== 0;
if (isDateBooked) {
alert("Date invalid");
return;
}
This works fine.
Then I created my "framework" which is this:
function Validator(fn, errorMessage) {
this.validationFunction = fn;
this.errorMessage = errorMessage;
};
var validationRunner = {
validators: [],
errorMessages: [],
validationResult: true,
addValidation: function (validator) {
validationRunner.validators.push(validator);
},
validate: function () {
for (var validator = 0; validator < validationRunner.validators.length; validator++) {
if (validationRunner.validators[validator] instanceof Validator) {
var result = validationRunner.validators[validator].validationFunction();
validationResult = validationRunner.validationResult && result;
if (!result)
validationRunner.errorMessages.push(validationRunner.validators[validator].errorMessage);
}
}
},
getErrorMessage: function () {
var message = "<ul>";
for (var errorMessage = 0; errorMessage > validationRunner.errorMessages.length; errorMessage++) {
message += "<li>" + errorMessage + "</li>";
}
message += "</ul>";
return message;
}
}
And then modified the first block of code as follows:
var selectedTourDate = $("#tourDate").val();
var list = $("#bookedTourDate *");
var tmp = new Validator(function () {
return list.filter(function () {
return (this.innerHTML == selectedTourDate);
}).length !== 0;
}, "Date already booked");
validationRunner.addValidation(tmp);
validationRunner.validate();
var msg = validationRunner.getErrorMessage();
This does not work at all.
It seems that the problem is that in this statement:
return (this.innerHTML == selectedTourDate);
The "this" is the Validator object instead of the html element from the list which confuses me since as its inside the function of the "filter" method it should be.
Is there a way to correct this so I can accomplish what I am trying to do here?
this does have the correct value but there are some mistakes in the getErrorMessage function.
To check the value of this don't rely on a debugger's "watch variable" function but do a console.log which will give you the value at a specific point of the code execution.
My changes:
for (var errorMessage = 0; errorMessage < validationRunner.errorMessages.length; errorMessage++) {
message += "<li>" + validationRunner.errorMessages[errorMessage] + "</li>";
}
The errorMessage variable is only a index and not the actual error message. Also you used a "bigger than" instead of a "smaller than" sign.
Here's a fiddle
That is very odd, as this should be the current DOM element per jquery api.
The function should take an index as a parameter, though. So what about trying
return list.filter(function (i) {
return (list.get(i).innerHTML == selectedTourDate);
}).length !== 0;