I have a bunch of elements with names similar to "comp[1].Field" or "comp[3].AnotherField" where the index (1 or 3) changes. I'm trying to extract the index from the name.
Right now I'm using:
var index = $(":input:last").attr("name").match(/\[(\d+)\]/)[1];
but I don't feel like this is the best way to do this.
Any suggestions?
Thanks
What you have is actually a pretty good way to do it, but you should add some checking that ensures that match() actually returns an array (meaning the string was found) and not null, otherwise you'll get a type error.
example:
var index = $(":input:last").attr("name").match(/\[(\d+)\]/);
if (match) { index = match[1]; }
else { /* no match */ }
Related
I'm obtaining a list of elements in classes and I'd like to filter out any class which does not contain a specific word in the innerHTML. Currently, I've managed to filter out the words however I can't seem to obtain the whole string, only part of it. Here's what I've got:
htmlData = $(htmlData).find(".Description").html("Fruit");
All this does is return "FruitFruitFruitFruitFruit..." when I'd like to obtain the whole string which the word is in. Anyone know how to do it? Thanks.
Wrap the assignment in an if, in which you're checking if the string is contained in the Text.
if($(htmlData).find(".Description").text().indexOf("Fruit") === -1){
htmlData = $(htmlData).find(".Description").html();
}
the indexOf function returns the index of where the string was found first. If it wasn't found, it returns -1.
I hope that this is what you meant..
var arr = [];
$.each($(htmlData).find(".Description"), function(_, jqElem){
var content = jqElem.html();
if (content.indexOf("Fruit") !== -1 ) {
arr.push(content);
}
})
I have the following code in my application. It is supposed to build a comma separated string from a JQuery collection. The collection is retrieved from some xml. I use JQuery each() to iterate. This is standard code that I use all the time. I declare and define the result variable (patientConditions) first and set it to blank. Within the function I add the found string to the result variable along with a comma. I am not bothered by the trailing comma this leaves if there are results. The problem is that with no results the second line within my each() is running - they probably both are. After the loop has completed (with no matching elements in the xml) the value of the result is ','. It should be blank. I think this is something to do with closures, or hoisting, but I am unable to figure out how its happening. I have hacked a solution to this scenario, but am more worried about the hole in my js knowledge :(
var patientConditions = '';
$xml.find('patient>prescription>conditions').each(function() {
var conditionName = $(this).find('condition>name');
patientConditions += conditionName.text() + ',';
});
From what I can understand there is a match for patient>prescription>conditions, but not for condition>name, in that case $(this).find('condition>name') will return a zero elemet set. then .text() on that set will return a empty string
$xml.find('patient>prescription>conditions').each(function() {
var conditionName = $(this).find('condition>name');
if(conditionName.length){
patientConditions += conditionName.text() + ',';
}
});
Whenever a jQuery object is used to find non existant nodes, in this case $(this).find('condition>name'). The jQuery object still exists, it just contains no association to a node. This will allow you to run all jQuery functions on this object despite it not having any reference. This is why conditionName.text() returns an empty string despite no node being present. The solution, check if the node exists before doing anything.
var patientConditions = '';
$xml.find('patient>prescription>conditions').each(function() {
var conditionName = $(this).find('condition>name');
if (conditionName.length > 0) {
patientConditions += conditionName.text() + ',';
} else {
// Do something if node doesnt exist
}
});
var search_name = location.search;
if (search_name.search("cate_no=24") > 0) {
$(".cate_new a").addClass("active");
}
});
If current document url is http://abc.com/list.html?cate_no=24,
I want to add class "active" into li a.
I searched and found these js code, but it doesn't work.
Is it wrong?
It's incorrect. search() returns the offset position of a match if a match is found, and -1 if a match isn't found.
As you are checking for whether cate_no=24 contains cate_no=24, it will return 0 if true.
Currently, your conditional checks whether the search() will return > 0, which is not what you want.
What you should be doing is check whether it is greater > -1:
if (search_name.search("cate_no=24") > -1)
Although, as I mentioned in the first revision of my answer, it would be better and faster to use indexOf() (search() is supposed to be used when dealing with regular expressions, not for simple string searches).
if (search_name.indexOf("cate_no=24") > -1)
search will only gives you the String. that will be in your case ?cate_no=24
So we leave the first part as it is and try to find the desired value in search_name as string.
var search_name = location.search;
This how we can find the index of the desired pattern.
if (search_name.indexOf("cate_no=24") > 0) {
$(".cate_new a").addClass("active");
}
My personal blog is static so I also had to figure out how to do this without PHP or some other server side code.
This bit of code grabs the path of the current URL, e.g. if you are on http://example.com/about, it would return the string '/about/'. From there you write a simple conditional to add a class to the link you select.
var currentURL = window.location.pathname.toString();
console.log(currentURL);
if (currentURL = '/about/') {
$('a#about').addClass('active')
} else if (currentURL = '/work/') {
...
}
This could be further developed to grab the href attributes from an array of links with a certain class (.nav-items, for example) and add the active class to whichever element has a href equal to the returned string.
In javascript, I'm loading an json object, and trying to update values within it. Elements in html have ids that match their path, such that the "values.one" element in this:
{"values":{"one":"val1","two":"val2"},"OtherStuff":"whatever"}
would be related to this element:
<input id="values_one" type="text">val1</div>
When this element loses focus, I want to grab the value of "#values_one" (using jQuery) and set use whatever value is there into my json object. I've figured out how to get the value from the existing json object (see my horrid code below), but I end up with nothing but the value, so setting it doesn't affect the json object. Any suggestions on how I can do this (assuming that I don't know whether the element that lost focus was "values_one", "values_two", or any other element that might map to the json object)?
Here's the code that I have at this point (that isn't working), but happy to scrap it for something that actually works:
var saveEdit = function() {
var data = getJson();
pathElements = $(this).attr('id').split('_');
length = pathElements.length;
var path = data[pathElements[0]];
index = 1;
while (index < length) {
path = path[pathElements[index]];
length -= 1;
}
path = $(this).text(); //resets "path", but not data.values.one
$(this).unbind();
}
Loop one shorter than the length, so that you get the element that contains the property that matches the last identifier:
var path = data;
for (index = 0; index < length - 1; index++) {
path = path[pathElements[index]];
}
path[pathElements[length - 1]] = $(this).text();
Firstly, there's no such thing as a "JSON Object". Yes, I'm being pedantic, but you should either have a "JSON String", or a "Javascript Object".
It looks like you're trying to modify a JSON string via events, instead of just having the object itself available to reference and modify. Why bother keeping it in a string? When you're ready to export the data (perhaps saving to a db), then just stringify(); the object and be on your way.
Take a look at the following jsFiddle for a working implementation that you can build off of: http://jsfiddle.net/julianlam/WRZPF/
How would our group find out if a particular string contains a certain substring? Only with the help of jquery, please.
You don't really need jQuery for such a simple thing, you can simply use the indexOf method of String objects, e.g.:
var str = "foobar";
var containsFoo = str.indexOf('foo') >= 0; // true
The indexOf method returns the character index where the first occurrence of the specified value is encountered, if not found, it returns -1.
Why use 10 characters when 100 will do?
Here's the requested jQuery plugin:
jQuery.isSubstring = function(haystack, needle) {
return haystack.indexOf(needle) !== -1;
};
Usage:
$.isSubstring("hello world", "world")); // true;
If your limited to jQuery which is just JavaScript... you can use the filter
var subgtSel = $("#jquerySelector").filter(function(i) {
// do your filter here
return $(this).attr("data-timestamp") <= subMsg.CreateDateTimeStamp;
});
the subgtSel becomes your new jQuery now with the relevant filter in the above. In the above, I am looking for all div elements that have an attribute that is less than the subMsg.CreateTimeStamp.
If your looking for a particular substring... you can do the following with jQuery right in the selector
var sel = $("#jquerySelector:contains('text')");
see http://api.jquery.com/contains-selector/