Javascript selector with Regular Expression - javascript

I would like to add an event listener to 2 buttons. Their ids are:
authCreateAcctConfirmNoBtn
authCreateAcctConfirmYesBtn
How would I do the following, I imagine I am close:
authCreateAcctConfirm(No|Yes)Btn.addEventListener('blur', function() {...
I don't know how to tell the browser that the object to attach to is a regular expression?

You need to select the elements first. This is done via document.querySelector.
I would avoid crazy Regex magic and choose the straightforward way. The easiest solution would look like this:
document.querySelector("#authCreateAcctConfirmYesBtn").addEventListener("blur",func);
document.querySelector("#authCreateAcctConfirmNoBtn").addEventListener("blur",func);
function func(){
/* stuff here */
}
To select both at once, you could use querySelectorAll and use this selector:
var elements = document.querySelectorAll("#authCreateAcctConfirmYesBtn,
#authCreateAcctConfirmNoBtn");
You now have to iterate over the returned NodeList resultset with a straightforward for loop or a borrowed Array method:
Array.prototype.forEach.call(elements,func);
Here you get the element handed over as first parameter in func.

Related

setting default root element in jquery

jQuery currently uses window as its default element so any call like $('div') will look for div tags inside window.
Is there any way to change defaults on jQuery like:
$.defaultRoot = $('.anyOtherRootElement');
$('div').text("Hello");
this will select any div inside the elements containing .anyOtherRootElement class.
Thanks in advance
Upate
just an update refining the question a bit more here:
I would like to perform the actions above based on external queries coming from external script which won't know what defaultRoot is so they can still be calling what is supposed to be the current base, so in this instance, I'm afraid adding the a second parameter wouldn't be an option, unfortunately.
And at the same time creating a function which returns defaultRoot.find(el) would prevent me of using first-level methods such $.trim, $.each, etc… so unfortunately that would not be possible as well.
Ideally (for performance reasons) you'd want to use find()
$.defaultRoot.find("div");
Otherwise you can use the 2 argument form that sets a context
$("div", $.defaultRoot);
In general you don't want to do these types of things implicitly since someone else could easily end up thoroughly confused when having to work with your code later. If you want to do it consistently and make it shorter you should create your own function to do so like:
var $s = function(selector) {
return $.defaultRoot.find(selector);
}
and then you'd just be able to use
$s("div")
or you could also do a scoped higher order function with something like
var withScope = function(scope$) {
return function(selector) {
return scope$.find(selector);
}
}
var $s = withScope($.defaultRoot);
$s("div")
If for some reason you really want to screw around with the default state for client code (begging for chaos IMO), you should look at the functional practice: currying.
$('SELECTOR', 'CONTEXT')
You can use context. As in your case $('div', '.anyOtherRootElement')
For more details, visit http://api.jquery.com/jQuery/
Given that you can pass the context as a second argument, you can easily overwrite the $() operator in Javascript with a version which internally calls JQuery using jQuery.noConflict(); and always passes your new root as the second argument.
I don't think jQuery provide such method or variable. But you can pass second parameter in jQuery method to set context.
$.defaultRoot = $('.anyOtherRootElement');
$('div', $.defaultRoot ).text("Hello"); // all div inside $('.anyOtherRootElement')
$('div' ).text("Hello"); //all div inside body tag

Combining selectors as variables in jQuery

I'm thinking of what is the best way to combine selector, which i use as variables in my jQuery code. I want to use selectors as variable always, but the thing is that sometimes i want to use them in one statement, so i'm thinking what's the most elegant way to do it.
Should i use add ( (x+y).function... )? Or maybe add strings? Or maybe keep jQuery variables as only id with name so i can combine within single jQuery statement ($ that is)
x = $('#selectorOne');
y = $('#selectorTwo');
You can store them in an array:
var selectors = [
'#selector1',
'#selector2',
....
];
and when you want to use them all together, do a comma separated join()
var alljoined = selectors.join(','); //join ALL selectors
$(alljoined).doSomethingToAll(); //and do something to all
you can also choose selectively:
var fewjoined = [ //select a few selectors...
selectors[1],
selectors[3],
...
].join(','); //..to join
$(fewjoined).doSomethingToAll(); //and do something
If they're declared as variables you can use add():
x.add(y).something();
Multiple Selector (“selector1, selector2, selectorN”)-You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order.
Example :
$("div,span,p.myClass").css("border","3px solid red");
or
.add() - Add elements to the set of matched elements.
Example :
$("p").add("div").addClass("widget");
Since x and y are just arrays, one can use jQuery.merge to combine them. HTH

Can JQuery and Javascript be mixed together?

I am wondering if I could use query and javascript together so I could select an element by class with the javascript and then use javascript to work on that element. Sorry if that didn't make sense. Here is an example:
$('.nav_flag').src = "images/flags/"+userCountryLower+".gif";
Would that work, if not how do I get an element by class using regular javascript. Thanks!
EDIT:I know JQUERY is JavaScript but I was wondering if I could mix jquery selectors and javascript 'controller'-for a loss of a better word
To answer your question as asked, there are several ways to take a jQuery object, i.e., what is returned by $('some selector'), and get a reference to the underlying DOM element(s).
You can access the individual DOM elements like array elements:
// update the src of the first matching element:
$(".nav_flag")[0].src = "images/flags/"+userCountryLower+".gif";
// if you're going to access more than one you should cache the jQuery object in
// a variable, not keep selecting the same thing via the $() function:
var navFlgEls = $(".nav_flag");
for (var i = 0; i < navFlgEls.length; i++) { ... }
But you wouldn't manually loop through the elements when you can use jQuery's .each() method, noting that within the callback function you provide this will be set to the current DOM element:
$(".nav_flag").each(function() {
this.src = "images/flags/"+userCountryLower+".gif";
});
However, jQuery provides a way to set attributes with one line of code:
$(".nav_flag").attr("src", "images/flags/"+userCountryLower+".gif");
To answer the second part of your question, doing the same thing without jQuery, you can use .getElementsByClassname() or .querySelectorAll() if you don't care about supporting older browsers.
jQuery IS Javascript. You can mix and match them together. But you better know what you're doing.
In this case, you probably want to use .attr function to set value of attribute.
Use .attr() in jQuery, rather than mix the two here.
$('.nav_flag').attr('src', "images/flags/"+userCountryLower+".gif");
In many instances, it is fine to mix jQuery with plain JavaScript, but if you have already included the jQuery library, you might as well make use of it. Unless, that is, you have an operation which in jQuery would be more computationally expensive than the same operation in plain JavaScript.
You can do it with jQuery too:
$('.nav_flag').attr("src", "images/flags/"+userCountryLower+".gif");
keep in mind that jQuery is simply a library built upon javascript.
for any jQuery object, selecting its elements by subscription will return the corresponding dom element.
e.g.
$('#foo')[0] // is equivalent to document.getElementById('foo');
You need to add an index to the jQuery object to get the native Javascript object. Change:
$('.nav_flag').src = "images/flags/"+userCountryLower+".gif";
To:
$('.nav_flag')[0].src = "images/flags/"+userCountryLower+".gif";
To get elements by class name in Javascript you can use:
document.getElementsByClassName( 'nav_flag' )[0].src = "images/flags/"+userCountryLower+".gif";
To answer your question, you could use .toArray() to convert the jQuery object into an array of standard DOM elements. Then either get the first element or loop through the array to set all the elements with the class.
However, you could do this easier with pure jquery with attr or prop depending on the version:
$('.nav_flag').attr("src", "images/flags/"+userCountryLower+".gif");
Or use pure javascript:
if (navFlagElements = document.getElementsByClassName("nav_flag") && navFlagElements.length > 0) {
navFlagElements[0].src = "images/flags/"+userCountryLower+".gif"
}

jQuery get value from checked element with a given name

I've got an input like so:
I'd like to use jQuery to grab that element, and add the function call foo() to the change event. Currently I can get it done, but there are two hacks involved. My (working) code:
$(":input[name*=myfield]").change(
function( $(":input[name*=myfield]") ) {
foo();
});
)};
There are two hacks in there I'd like to eliminate.
Keeping in mind that the input names are multidimensional arrays, how can I use the :input[name=somename], versus [name*=someone]? I'd imagine it's faster using an exact name rather than *=, but I can't get the escape sequence correct for the brackets on the multidimensional arrays.
Can I chain the call together so that I don't have to select the element twice? Is the standard practice for that to select the HTML element into a var, then use that var? Or can I chain it together?
Thanks for the help. Still working on getting my footing in JS/JQ.
1 - to escape brackets and other meta-characters, use \\[. See Selectors.
2 - $(":input[name*=myfield]").change(foo);
What's wrong with this?
$("input[name=somename]").change(function(){..});
In your html elements use the data-* like so
<input type="checkbox" data-name="box" name="myName[0][1]" checked="" />
then within jQuery
$('input[data-name=box]').click(foo);
function foo()
{
//this = input element
}

Jquery Replace with return value of Javascript function

OK I am just starting out with jQuery.
I have a page with a table of date-values. Each is wrapped in a tag which I can find with
$('mytag').
<mytag>2009-10-31</mytag>
How, using Jquery, would I
take each of the source values and
pass it to a Javascript function
then replace that source value within the table with the result of the function calculation.
So <mytag>2009-10-31</mytag>would be replaced with <mytag>Very Late</mytag>
I have the Javascript function written. My question is the jQuery syntax to pass the individual value.
Firstly, you will need an element selector, e.g.
$('table')
Will select all <table> elements in your html. So,
$('mytag')
will give you your elements. You will get a jQuery object (not a DOM object) returned. See http://docs.jquery.com/Selectors
Then you want to call a function for each of your elements. For this we call the .each function, and pass the function to call for each element:
$('mytag').each(function(){
//function code goes here
});
(See http://docs.jquery.com/Utilities/jQuery.each)
The function in this case is called an Anonymous function
Then you want to reference the current object in the iteration, so we use the DOM this item and wrap it into a jquery object. To get the value, we use the .text() function (http://docs.jquery.com/Attributes/text)
$('mytag').each(function(){
$(this).text()
});
Note: if it were an input element then you would have used .val()
Passing it to a function is easy:
...
MyFunction($(this).text());
...
The text() function has an overloaded implementation which allows you to set the text if you pass a value:
$(this).text(someval);
So, we can factor this into our code
...
$(this).text(MyFunction($(this).text()));
...
Making our final code block:
$('mytag').each(function(){
$(this).text(MyFunction($(this).text()));
});
$('mytag').each(function (index,tag) {
$(tag).text( myFunc($(tag).text()) );
});
$("mytag").each(function() {
$(this).html("Very Late");
});
$('mytag').each(function() {
$(this).text(someFunction($(this).text()));
});
But, from the sound of your problem, you might be better served by the jQuery-timeago plugin. For your particular case, you'd possibly want to allow dates in the future:
jQuery.timeago.settings.allowFuture = true;
...and you'd want to create your own language override. See the language override examples. You could define several "late" and "very late" values. You can also pass a function to each one to change the value depending on how many days ago a timestamp was.

Categories

Resources