find a href with a certain value - javascript

I have an array called "selectMe" formed by a variable wich contains a string such as: 12P, 5B, 10C, etc., this is the "href" value of a hyperlink and I need to find and add the class "selected" to the ones inside this array. To break the array I have:
function selectPrevious(selections){
// split into array
var selectMe = selections.split(", ")
for (var i = 0; i < selectMe.length; i++){
$('#theater a').search(selectMe[i]).addClass('selected');
}
}
I've tried doing find() instead of search() as well as many other iterations but still haven't been able to accomplish what I want, how can I do it?
EDIT
Using one of the answers provided here I have changed it to this:
function selectPrevious(selections){
// split into array
if(typeof selections !== "undefined"){
var selectMe = selections.split(", ");
for (var i = 0; i < selectMe.length; i++){
$('#theater a[href*='+selectMe[i]+']').addClass('selected');
}
}
}
I had to add the "if(typeof selections !== "undefined")" because otherwise it was throwing me errors on IE. Anyway, I still can't add the class "selected" to the values in the array, am I missing something? or did I do something wrong?

Your selector for find() is wrong. And there are no search() in jQuery.
Instead of $('#theater a').search(selectMe[i]) use $('#theater a[href*='+selectMe[i]+']')

try this one:
function selectPrevious(selections) {
// split into array
var selectMe = selections.split(", ")
for (var i = 0; i < selectMe.length; i++){
$('#theater').find('a[href*='+selectMe[i]+']').addClass('selected');
}
}

Related

Using Javascript Array Filter method to apply logic [duplicate]

I have search through quite a lot of questions here, but havent found one that i think fits my bill, so if you know of one please link to it.
I have an array that i want to search through for a specific number and if that number is in the array, i then want to take an action and if not then another action.
I have something like this
var Array = ["1","8","17","14","11","20","2","6"];
for(x=0;x<=Array.length;x++)
{
if(Array[x]==8)
then change picture.src to srcpicture1
else
then change picture.src to srcpicture2
}
but this will run the lenght of the array and end up checking the last element of the array and since the last element is not 8 then it will change the picture to picture2.
Now i can see why this happens, i just dont have any ideas as to how to go about checking if an array contains a specific number.
Thanks in advance.
What you can do is write yourself a function to check if an element belongs to an array:
function inArray(array, value) {
for (var i = 0; i < array.length; i++) {
if (array[i] == value) return true;
}
return false;
}
And the just do:
var arr = ["1","8","17","14","11","20","2","6"];
if (inArray(arr, 8)) {
// change picture.src to srcpicture1
} else {
// change picture.src to srcpicture2
}
It's a lot more readable to me.
For extra points you can add the function to the array prototype like so:
Array.prototype.has = function (value) {
for (var i = 0; i < this.length; i++) {
if (this[i] === value) return true;
}
return false;
};
And then the call would be
if (arr.has(8)) // ...
Pushing this even further, you can check for indexOf() method on array and use it - if not - replace it with the code above.
P.S. Try not to use Array for a variable name, since it's reserved for the actual array type.
use this
http://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/IndexOf
ie version
https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/IndexOf#Compatibility
Why don't just you abort the loop when you find the right number :
for(x=0;x<=Array.length;x++)
{
if(Array[x]==8) {
//change picture.src to srcpicture1
break;
}
}
You could sort the array first then check the array only up to the point at which a number would be in the array, were it to exist.
If you have unique keys and a faster retrieval is what you care about a lot, you can consider using a map instead of an array (if there's a hard-bound case of using an array, then it won't work of course). If using a map, you just check "if( num in arr ) ".

javascript get only array elements equal to variable

I'm trying to compare the variable determineHour against the array stationRentalsHours, whenever the variable would be equal to a stationRentalsHours element, I'd like to add that element to another Array (stationRentalsHoursTemp), but only the values that match. I tried with simple operators, but that doesn't put anything into the temp array. I also tried using JQuery $.inArray, but that gives me some strange results, Equal to those in the original array. Are there any other methods of comparing a variable with an array for this particular task?
Thank you for any help.
function updateChart() {
if(canvas3){canvas3.destroy();}
var determineHour = selectNumber.options[selectNumber.selectedIndex].innerHTML;
for (var i = 0; i < stationRentalsHours.length; i++) {
/*if(determineHour == stationRentalsHours){
stationRentalsHoursTemp.push(stationRentalsHours[i]);*/
if( $.inArray(determineHour, stationRentalsHours[i])){
stationRentalsHoursTemp.push(stationRentalsHours[i]);
}
}
In this case, instead of using $.inArray, you can simply use the for loop and the index to test the equality. I guess you mixed up two things:
var determineHour = selectNumber.options[selectNumber.selectedIndex].innerHTML;
for (var i = 0; i < stationRentalsHours.length; i++) {
if( determineHour == stationRentalsHours[i]){
stationRentalsHoursTemp.push(stationRentalsHours[i]);
}
}
Better yet, use filter:
var determineHour = selectNumber.options[selectNumber.selectedIndex].innerHTML;
stationRentalsHoursTemp = stationRentalsHours.filter(function(val){return val == determineHour;});
Instead of
if( $.inArray(determineHour, stationRentalsHours[i])){
Try
if( $.inArray(determineHour, stationRentalsHours) != -1){
Your commented out code would do the trick with a slight amendment to the if condition. Your original condition was comparing a string to an array instead of an individual element in that array:
function updateChart() {
if(canvas3){
canvas3.destroy();
}
var determineHour = selectNumber.options[selectNumber.selectedIndex].innerHTML;
for (var i = 0; i < stationRentalsHours.length; i++){
if(determineHour == stationRentalsHours[i]){
stationRentalsHoursTemp.push(stationRentalsHours[i]);
}
}
}

Best way to create string filter comparation?

My goal's create a filter search function, in particular actually I'm using .indexOf method that allow me to check if two string are equal. The problem's that if I've the compare string with space break like this: Hair Cut.
Example:
String to search: Hair
String contained in the object: Hair Cut
var cerca = $('#filter_service').val();
for(var i = 0; i < GlobalVariables.availableServices.length; i++) {
if (cerca.toLowerCase().contains(GlobalVariables.availableServices[i].name.toLowerCase()) != -1) {
console.log(GlobalVariables.availableServices[i].name)
}
}
How you can see I valorize the variable cerca that contains the string Hair in the example. I compare this with an object variable, how I said, the problem is if I insert the string Hair I get no response in console, also if I insert the string with break space like the compare string Hair Cut I get the console response.
How I can print a result also when the variable cerca is equal to the first character of the compair string? In particular Hai?
I don't know if I was clear, hope yes.
.contains() is for checking DOM element children. You said above that you are using .indexOf to check, but it doesn't look like you use it in your code?
var cerca = $('#filter_service').val();
var searchIn;
for(var i = 0; i < GlobalVariables.availableServices.length; i++) {
searchIn = GlobalVariables.availableServices[i].name.toLowerCase().split(' ');
for (j = 0; j < searchIn.length; j++) {
if (cerca.toLowerCase().split(' ').indexOf(searchIn[j].toLowerCase()) >= 0) {
console.log(GlobalVariables.availableServices[i].name);
}
}
}
$('#filter_service').on('input', function() {
var inputStr = $('#filter_service').val();
var similar = [];
for (i = 0; i < GlobalVariables.availableServices.length; i++) {
if (GlobalVariables.availableServices[i].name.toLowerCase().indexOf(inputStr.toLowerCase) >= 0) {
similar[similar.length] = GlobalVariables.availableServices[i].name;
}
}
// At this point, you can do whatever you want with the similar service
// names (all of the possible result names are included in the array, similar[].)
});
I can't test that code right now, but in theory, it should work.
Here is a JSFiddle demo:
http://jsfiddle.net/MrGarretto/vrp5pghr/
EDIT: Updated and fixed my errors
EDIT 2: Added the 'possible results' solution
EDIT 3: Added a JSFiddle

Javascript getElementById based on a partial string

I need to get the ID of an element but the value is dynamic with only the beginning of it is the same always.
Heres a snippet of the code.
<form class="form-poll" id="poll-1225962377536" action="/cs/Satellite">
The ID always starts with poll- then the numbers are dynamic.
How can I get the ID using just JavaScript and not jQuery?
You can use the querySelector for that:
document.querySelector('[id^="poll-"]').id;
The selector means: get an element where the attribute [id] begins with the string "poll-".
^ matches the start
* matches any position
$ matches the end
jsfiddle
Try this.
function getElementsByIdStartsWith(container, selectorTag, prefix) {
var items = [];
var myPosts = document.getElementById(container).getElementsByTagName(selectorTag);
for (var i = 0; i < myPosts.length; i++) {
//omitting undefined null check for brevity
if (myPosts[i].id.lastIndexOf(prefix, 0) === 0) {
items.push(myPosts[i]);
}
}
return items;
}
Sample HTML Markup.
<div id="posts">
<div id="post-1">post 1</div>
<div id="post-12">post 12</div>
<div id="post-123">post 123</div>
<div id="pst-123">post 123</div>
</div>
Call it like
var postedOnes = getElementsByIdStartsWith("posts", "div", "post-");
Demo here: http://jsfiddle.net/naveen/P4cFu/
querySelectorAll with modern enumeration
polls = document.querySelectorAll('[id ^= "poll-"]');
Array.prototype.forEach.call(polls, callback);
function callback(element, iterator) {
console.log(iterator, element.id);
}
The first line selects all elements in which id starts ^= with the string poll-.
The second line evokes the enumeration and a callback function.
Given that what you want is to determine the full id of the element based upon just the prefix, you're going to have to do a search of the entire DOM (or at least, a search of an entire subtree if you know of some element that is always guaranteed to contain your target element). You can do this with something like:
function findChildWithIdLike(node, prefix) {
if (node && node.id && node.id.indexOf(prefix) == 0) {
//match found
return node;
}
//no match, check child nodes
for (var index = 0; index < node.childNodes.length; index++) {
var child = node.childNodes[index];
var childResult = findChildWithIdLike(child, prefix);
if (childResult) {
return childResult;
}
}
};
Here is an example: http://jsfiddle.net/xwqKh/
Be aware that dynamic element ids like the ones you are working with are typically used to guarantee uniqueness of element ids on a single page. Meaning that it is likely that there are multiple elements that share the same prefix. Probably you want to find them all.
If you want to find all of the elements that have a given prefix, instead of just the first one, you can use something like what is demonstrated here: http://jsfiddle.net/xwqKh/1/
I'm not entirely sure I know what you're asking about, but you can use string functions to create the actual ID that you're looking for.
var base = "common";
var num = 3;
var o = document.getElementById(base + num); // will find id="common3"
If you don't know the actual ID, then you can't look up the object with getElementById, you'd have to find it some other way (by class name, by tag type, by attribute, by parent, by child, etc...).
Now that you've finally given us some of the HTML, you could use this plain JS to find all form elements that have an ID that starts with "poll-":
// get a list of all form objects that have the right type of ID
function findPollForms() {
var list = getElementsByTagName("form");
var results = [];
for (var i = 0; i < list.length; i++) {
var id = list[i].id;
if (id && id.search(/^poll-/) != -1) {
results.push(list[i]);
}
}
return(results);
}
// return the ID of the first form object that has the right type of ID
function findFirstPollFormID() {
var list = getElementsByTagName("form");
var results = [];
for (var i = 0; i < list.length; i++) {
var id = list[i].id;
if (id && id.search(/^poll-/) != -1) {
return(id);
}
}
return(null);
}
You'll probably have to either give it a constant class and call getElementsByClassName, or maybe just use getElementsByTagName, and loop through your results, checking the name.
I'd suggest looking at your underlying problem and figure out a way where you can know the ID in advance.
Maybe if you posted a little more about why you're getting this, we could find a better alternative.
You use the id property to the get the id, then the substr method to remove the first part of it, then optionally parseInt to turn it into a number:
var id = theElement.id.substr(5);
or:
var id = parseInt(theElement.id.substr(5));
<form class="form-poll" id="poll-1225962377536" action="/cs/Satellite" target="_blank">
The ID always starts with 'post-' then the numbers are dynamic.
Please check your id names, "poll" and "post" are very different.
As already answered, you can use querySelector:
var selectors = '[id^="poll-"]';
element = document.querySelector(selectors).id;
but querySelector will not find "poll" if you keep querying for "post": '[id^="post-"]'
If you need last id, you can do that:
var id_list = document.querySelectorAll('[id^="image-"]')
var last_id = id_list.length
alert(last_id)

javascript, remove identical items from array

I do an ajax call in a lightbox script which returns a form.
when the form is loaded I call var initial = $('form').serializeArray();
when the form is submitted I call var final = $('form').serializeArray();
which gives me two arrays of objects,
What I now want to do is compare each object in the arrays and remove those that have not changed.
how would I do this?
I'm assuming that the two arrays will have equal length, and that the elements will be in the same order in both arrays. In this case, what you need to do is look at each element of the first array and compare it to the corresponding element of the second array; if they match, then remove the element in that position from both arrays.
Something like this should work (though I haven't tested it):
var i = 0;
while (i < initial.length) {
if(initial[i] == final[i]) {
initial.splice(i,1);
final.splice(i,1);
}
else {
i++;
}
}
The fastest way to do this I think
var len = initial.length, i=0, changed=[];
/* I hope initial.length==final.length*/
for(i; i<len; i++){
/* 0== '' */
if (initial[i]===final[i])
changed[i] = final[i];
}
//now play with
changed
I've got confused abou the question
does .splice() reorder the indexes?

Categories

Resources