(This question has been changed a bit since some of the answers were posted. That is why they might seem a bit off-topic and/or out of context)
Hello! So basically, I have this string that is entered by a user (a caption for an image, for example), and an array of links/words that I want to "block" the user from entering. (This would be to prevent from swearing, advertising etc.)
So I need some code that checks whether a certain value exists in an array.
This is my array:
var blockedUrls = ["https://google.com", "https://facebook.com"]
and this is the values I want to check
var userInput = "Hello! Check out my cool facebook profile at https://facebook.com";
(This would normally be set to a value fetched from an input of some sort, the static text is just to simplify)
So this is what I have tried:
let values = userInput.split(" ");
values.forEach((i, value) => {
// inArray is a made-up-function in order to better explain my intention
// The function I need here is a function that can check whether the value of the "value" variable exists in the "blockedUrls" array.
if(value.inArray(blockedUrls)) {
return alert(`You can't say that word! [${value}]`);
}
});
So a summary: How do I check if any of multiple values exists in an array?
You can check if a value is in an array by using indexOf
var value = document.getElementById('myFile').value;
if (unAllowedLinks.indexOf(value) != -1) {
// value is in array
}
-1 is returned when the value is not found in the array, else it returns the index of the value.
If you want to be able to change the number of values in unAllowedLinks you’d be better off using indexOf(), like so:
function updateImage() {
if (unAllowedLinks.indexOf(document.getElementById('myFile').value) > -1) {
alert("This link is reserved");
} else {
// Use the value
}
};
Related
I have these checkboxes with value in them that I would like to store and pass to php.
my function suppose to check each one of them and evaluate if thy're checked or not and then push/remove them from the array:
function isChecked(){
let distributionEL = document.querySelector("[name='distribution']");
console.log(distributionEL.value);
sendingLists.forEach(function(list) {
let sendSMSArr = distributionEL.value.split(',');
if(list.checked == true){
sendSMSArr.push(list.value);
} else {
let index = sendSMSArr.indexOf(list.value);
if (index > -1) {
sendSMSArr.splice(index, 1);
}
distributionEL.value = sendSMSArr.join(',');
});
}
What happens now is that the function repeats the existing elements of the array and then adds the new value like so. let's say my array looks like this:
sendSMSarr = ['1','2']
and after if do .push to the new value '3':
sendSMSarr = ['1','2','1','2','3']
I would like to store those values without duplicates.
As for some other data in here:
isChecked() is invoked after the loading of the page and after every search. you can search for those checkboxes in a search bar. after every search the entire div is emptied (div.innerHTML = '') and then filled with the results.
then:
// call func after every search
listR.addEventListener('change', function(){
isChecked();
})
The distributionEL is an hidden input which I use to store the values I need in a string in order to pass it to php and later convert to array agian so I can loop through it.
sendinglist is all the checkboxes in my page (document.querySelector(.checkboxes))
Manage to Isolate the problem:
Each checkbox is added when checked and removed when unchecked separately but when I check a few together without unchecking the others its start to duplicate. Obviously I would like to be able to do that without unchecking
I know it's trivial but I have a doubt to be clarified.
I have a collection vm.groups that has almost 1000 objects. Now, each object has name, id, links etc. property fields.
Grid only displays name and id.
Now, there is a text box where we enter some text and we have to filter data, according to whatever we entered but filtering must happen only within name and id fields of the objects not the other fields that are present within the objects.
So, both things can be done,
1) I create a temp collection from the original collection objects with only name and id fields and then bind the collection to view.
// vm.groups.forEach(function(element) {
// vm.displayedFieldGroups.
// push({name: element.name,id: element.id,transformedId: element.transformedId});
// });
2) Or, I create a custom filter vm.customSearch :
vm.customSearch = function(searchVal) {
if(vm.filter.length) {
if(vm.filter.toLowerCase().indexOf(searchVal.name.toLowerCase) !== -1 ||
vm.filter.toLowerCase().indexOf(searchVal.name.toLowerCase) !== -1) {
console.log(searchVal);
return true;
}else {
return false;
}
} else {
console.log(searchVal);
return true;
}
};
And in the view vm.groups | filter: vm.customSearch.
But I think second method is slower because each value in the collection would be passed to the filter which is obviously tedious for huge collection.
Am I right?
Which is the right way to do?
UPDATE
This was for a legacy application. There was a filter already implemented but that just goes through all the fields in the object. I need to only filter for name and id fields of objects.
Hence, I need to either create a custom filter or choose the first approach that I depicted.
You're right in your assumption that the filter would go over every item in the source array and run your filter function each time there's a digest cycle.
You should proceed with the first approach.
There is a page with a lot of different checkbox questions which then get submitted and populate the next page, this page however gets refreshed and the already annoyed potential client needs to go back and fill out the form again.
Now I have localstorage set up so he doesn't need to reselect all the checkbox again, he just needs to resubmit the form and his back in action.
How does one keep the values populated on the problem page so this fella doesn't have to go back to resubmit?
//SIZE SAVE
function save() {
localStorage.setItem('100', checkbox.checked);
var checkbox = document.getElementById('100');
localStorage.setItem('200', checkbox.checked);
var checkbox = document.getElementById('200');
//SIZE LOAD
function load() {
var checked = JSON.parse(localStorage.getItem('100'));
document.getElementById("100").checked = checked;
var checked = JSON.parse(localStorage.getItem('200'));
document.getElementById("200").checked = checked;
//THIS PAGE NEEDS THE CHECKMARK
echo get_site_url().
"/the/checkmark/selected/was/".$_POST['check_group'].
"/.png";
}
I think is much simple for now and especially for the feature if you write some code to make the management for all checkboxes form your form.
First of all it will be best if you group all your checkboxes into a single place.
Into a function like this you can declare all your checkbox selectors you want to save into the localStoarge (now you don't need to make variables for each selector into multiple places into your code)
function getCheckboxItems() {
return ['100', '200']
.map(function(selector) {
return {
selector: selector,
element: document.getElementById(selector)
}`enter code here`
});
}
Then to make things much simpler you can store all the values from the checkbox into a single object instead of save the result in multiple keys, in this way is much simpler to make management (let's say you want to erase all values or to update only a part)
The following function will take as argument all checkbox items from the function above, the point is the function above will return an array with the checkbox id and the checkbox element, than you just reduce all that array into this function into an single object containing all the ids and values, after this you just store the object into the localStorage
function serializeCheckboxes(elements) {
var container = elements.reduce(function (accumulator, item) {
accumulator[item.selector] = item.element.checked;
return accumulator;
}, {})
localStorage.setItem('container', JSON.stringify(container));
}
function save() {
var elements = getCheckboxItems();
serializeCheckboxes(elements);
}
After this you need another function who will read all the values from the localStorge and place them into your checkbox "checked" state
function readCheckboxes() {
var storage = localStorage.getItem('container'), //Your key
container = (storage) ? JSON.parse(storage) : {};
Object.keys(container).forEach(function(key) {
var element = document.getElementById(key);
if(element) {
element.checked = container[key];
}
});
}
This is just a simple service who can manage your problem but I think, for any additional changes you can customize this solution much simpler instead of keeping all into multiple variables, also if you add more checkbox elements into your application with this solution you just add the corresponding id into the array from the first function.
A live example here:
https://jsbin.com/xejibihiso/edit?html,js,output
localStorage has two main functions, getItem and setItem. For setItem you pass in a key and a value. If you write to that key again, it will rewrite that value. So in your case, if a box is checked you would do
localStorage.setItem("checkbox_value", true)
and when it is unchecked you would pass in false instead. To get the value you can look at using jQuery like so:
$(checkbox).is(':checked')
and use a simple if-else clause to pass in true or false. then when you reload your page, on $(document).ready() you can get the values using
localStorage.getItem(key)
and use JavaScript to set the check boxes values.
localStorage only allows you to store strings. What you can do is use a loop to create a string that has all the check boxes values separated by some delimiter. So, for example, if there are four check boxes with values true false false true your string would be "true\nfalse\nfalse\ntrue" where \n is the delimiter. then you can store that string in localStorage and when you retrieve it you can put all the values into an array like so:
array = localStorage.getItem(key).split('\n').
Then you can populate your check boxes with that newly retrieved array. Ask if anything needs clarification.
OK, I'm missing something here and I just can't seem to find it because the logic seems correct to me, but I'm certain I'm not seeing the error.
var VisibleMarkers = function() {
var filtered = _.reject(Gmaps.map.markers, function(marker) {
return marker.grade != $('.mapDataGrade').val() && !_.contains(marker.subjects,$('.mapDataSubjects').val())
});
return filtered
}
I'm using underscore.js and jQuery to simplify my javascript work.
So right now, I'm checking by means of selects which data gets to be rejected and then I display the filtered markers on the (google) map (if it helps at all, this is using gmaps4rails which is working perfectly fine, its this bit of javascript that's making me lose the last of the hairs on my head).
Currently, the code functions 100% correctly for the ".mapDataGrade" select, but the ".mapDataSubjects" isn't. Now the markers object has a json array of the subjects (this is for students) and each item in the array has its ID. Its this ID that I am supposed to be checking.
Can someone see what I'm doing wrong?
If there's more info that needs to be included, please let me know.
This is on plain javascript on a RoR application using gmaps4rails
Now the markers object has a json array of the subjects (this is for students) and each item in the array has its ID. Its this ID that I am supposed to be checking.
_.contains compares a values, but it sounds like you want your iterator to compare a value to an object's "id" property. For that, _.some would work; it's like contains, except that, instead of comparing values, you can write the comparison as a function:
Returns true if any of the values in the list pass the iterator truth test.
Here's how you'd use it:
!_.some(marker.subjects, function(subject) {
return subject.id == $('.mapDataSubjects').val();
})
If I'm right, the whole line should be like this:
return marker.grade != $('.mapDataGrade').val() &&
// check that none of the subjects is a match
!_.some(marker.subjects, function(subject) {
// the current subject is a match if its ID matches the selected value
return subject.id == $('.mapDataSubjects').val();
});
I'm trying to build a history list of clicked clicked page elements and store that list into HTML local storage, to be later displayed back to the user. The main pre-requisite is that the list cannot contain duplicates, so for example if the user clicks on item A and then on item B and again back on item A, only A and B are recorded. The third click is not recorded because it is not unique.
I'm also using persist.js.
I noticed that I am able to name the storage and give it a key and both are stored together in the real key of the localstorage thus: myStorageName>myKeyand my value is whatever I put there.
Here's the thing. I know you can store stringyfied JSON there but my list is built up from simple javascript variables one at at time.
I know what to do for the first click:
myStorageName.set(myKey, myCurrentElementId); // myCurrentElementId = this.id
now on the second click this is where I'm beginning to getting stuck. There is the original variable value already stored, now I want to append the new variable value. Assume that I can get the value from the store like this:
var dataExtract = myStorageName.get(myKey);
myObject = JSON.parse(dataExtract);
But how do I then turn this into a JSONstring -able thing (sorry I don't even know what it should be) that contains only a list of unique values. Does this make any sense to anyone?
First of all, you don't want to keep writing to/from localStorage everytime a link is clicked, because this'll slow down your page. Keep an updated Array populated with the element ids, then write to localStorage before the user navigates away from the page (by binding to the window's onbeforeunload event, for instance).
First:
var clickedLinks = []; // this Array will hold the ids of the clicked links
function uniqueClick(id){
return !~clickedLinks.indexOf(id); // this tests whether the id is already in the Array
};
In your click handler:
if(uniqueClick(this.id)){
clickedLinks.push(this.id); // append the new element id to the Array
}
Bind to window.onunload to save the Array before the user navigates from the page:
window.onunload = function(){
localStorage.setItem('clickedLinks',JSON.stringify(clickedLinks)); // stringify the Array and save to localStorage
}
To retrieve clickedLinks on subsequent page visit:
// convert the String back to an Array; try/catch used here in case the value in localStorage is modified and unable to be parsed, in which case clickedLinks will be initialized to an empty Array
try{
var clickedLinks = JSON.parse(localStorage.getItem('clickedLinks')) || [];
}catch(e){
var clickedLinks = [];
}
You may want to replace the first line (var clickedLinks = [];) with this last bit of code, as it will initialize the Array if it doesn't exist.
UPDATE:
IE8 does not support Array.indexOf. Alternatives might be:
use jQuery's $.inArray by replacing !~clickedLinks.indexOf(id); with !~$.inArray(id, clickedLinks);
Detect whether Array.prototype.indexOf is supported. If not, shim it with the code provided on this page.
Your model has an error. At the first time, you save a primitive value. Then, you want to "append" another value to it. Seems like you actually want to use an object:
var myObj = localStorage.getItem("myName");
if(myObj) myObj = JSON.parse(myObj); //Variable exists
else myObj = {}; //Elsem create a new object
function appendNewValue(name, value){
myObj[name] = value;
localStorage.setItem("myName", JSON.stringify(myObj));
/* Saves data immediately. Instead of saving every time, you can
also add this persistence feature to the `(before)unload` handler. */
}
I suggest to define in your code this:
localStorage.set= function(key,val)
{
localStorage.setItem(JSON.stringify(val));
}
localStorage.get = function(key,defval)
{
var val = localStorage.getItem(key);
if( typeof val == "undefined" ) return defval;
return JSON.parse(val);
}
and use them instead of get/setItem. They will give you ready to use JS values that you can use in the way you need.