how to dynamically assign numbers to several ids? - javascript

This seem like long way of doing things, is it possible to dynamically assign numbers to ids?
$(function () {
$('#Button1').click(function(){
$('#RegularExpressionValidator1, #RegularExpressionValidator2, #RequiredFieldValidator1, #RequiredFieldValidator2, #RequiredFieldValidator3, #RequiredFieldValidator4, #RequiredFieldValidator5, #RequiredFieldValidator6, #RequiredFieldValidator7, #RequiredFieldValidator8, #RequiredFieldValidator9').css("display", "block");
});
});
These are .NET generated ids which I don't have access to.

You can use an "attribute starts with" selector:
$("[id^='RegularExpressionValidator']").css("display", "block");
From the jQuery docs:
This selector can be useful for identifying elements in pages produced
by server-side frameworks that produce HTML with systematic element
IDs. However it will be slower than using a class selector so leverage
classes, if you can, to group like elements.

Have a look at the attributes starts with selector. Using it, you can simply do this:
$(function () {
$('#Button1').click(function(){
$('[id^="RegularExpressionValidator"], [id^="RequiredFieldValidator"]').css("display", "block");
});
});
This will select all elements with an ID starting with RegularExpressionValidator. You may want to specify the element type, as well as a container to look in to select fewer elements.
You may also want to use $.show() instead of $.css():
$('[id^="RegularExpressionValidator"], [id^="RequiredFieldValidator"]').show();

try
$(function () {
$('#Button1').click(function(){
$('[id^="RegularExpressionValidator"], [id^="RequiredFieldValidator"]').css("display", "block");
});
});

Related

How to use single function to multiple classes?

I've got this following code:
<script type="text/javascript">
$(document).ready(function(){
$('.sample1').click(function(){
$('.dropdown-content').toggleClass('visible-dropdown');
})
})
</script>
It adds class so I can get some animations with mouse click event.
I have some more classes in HTML like 'sample2', 'sample3', etc. and would like to add exactly the same animations (classes of course has different content).
I know one solution, namely just add in same code n-times, but change class for each block of code. Is there a shorter way? I thought maybe something with arrays, not sure. I'm not really good in JS, it's like my first time ;)
You can just group the classes, separated by commas. Example :
$('.sample1, .sample2, .sample3').click(function(){
You can edit your code to take multiple selectors.
<script type="text/javascript">
$(document).ready(function(){
$('.sample1, .sample2, .sample3').click(function(){
$('.dropdown-content').toggleClass('visible-dropdown');
})
})
</script>
Simply use multiple selectors:
$('.sample1, .sample2 , .sample3').click(function(){
$('.dropdown-content').toggleClass('visible-dropdown');
})
You could try
$('*[class*="sample"]')
This is the source
You can use css selectors:
Catch the elements which have classes started with 'sample':
$('[class^=sample]').on('click',function(){
//Do something
});
Catch the elements which have classes ended with 'sample':
$('[class$=sample]').on('click',function(){
//Do something
});
To find more information about css selectors:
https://www.w3schools.com/cssref/css_selectors.asp

Im forcing to use getElementsByClassName()[] rather than getElementByClass()

I have 8 divs with id="div1","div2","div3".... and a class=divs. I also have a button with class="div1","div2","div3"......
When I click the button with id="div1", it will first remove all the class="selected" to all div that has a class="divs" then only the div with id="div1" will have the class selected. And so on.....
I want to use document.getElementByClass() for removing class but it don't work in my FIDDLE. :(
Instead, Im forced to use document.getElementsByClassName()[]. But it seems so hard to code since it requires me to put the specific arrays for the classname.
This is exactly I want to achieve FIDDLE
There is no getElementByClass for a reason: unlike id, class is not specified to be unique in a document. Which element would you get? No, you need the ability to get all of them. And if you get an array, that's solved by looping, not by repeating rows for each index:
However, your design is inefficient; and if you're already using jQuery, you can write it very tightly. This would be better:
<button class="divbuttons" data-div="div1">div1</button>
<button class="divbuttons" data-div="div2">div2</button>
...
then you can:
$(document).ready(function(){
$('.divbuttons').click(function() {
var div = $(this).data("div");
$('.divs.selected').removeClass('selected');
$('#' + div).addClass('selected');
});
});
This is an easy one. There is no document.getElementByClass
You have document.getElementById or document.getElementByClassName
There's no such thing as getElementByClass() because multiple elements can have the same class. There's getElementById() (elements have unique ids, or at least they're supposed to) and getElementsByClassName(), which returns an array of all elements that match the class specified.
try
$(document).ready(function () {
$("button[class^=div]").click(function () {
$(".divs.selected").removeClass("selected");
$("#" + $(this).attr("class")).addClass("selected");
});
});
DEMO

how to use jquery loop function to target many element with different ids

Currently, I have this code:
$(document).ready(function(){
// #filtertab-00 replace this with your element id
$('#filtertab-00 .box-content .es-nav .elastislide-next, #filtertab-00 .box-content .es-nav .elastislide-prev').click(function() {
// trigger lazy load
$("#filtertab-00 img.lazy").each(function(i) {
$(this).delay(150*i).fadeIn(1000, function() {
var src = $(this).attr("data-original");
$(this).attr('src',src);
});
});
});
});
and i want to use this function to target object names (id) as below:
filtertab-00
filtertab-10
filtertab-20
filtertab-30
filtertab-40
filtertab-50
filtertab-60
....
filtertab-90
Does anyone know how to use the loop function to get it work?
i just want this:
when i click pre or next button after i select a tab(name varies from filtertab-00 to filtertab-90),it will activate lazyloading for images at current selected tab.
any idea is welcome!
Perhaps you could use jQuery's attribute-starts-with selector. You can then just select all IDs that begin with filtertab- using jQuery like this:
$('div[id^="filtertab-"]').each( //magic goes here );
Note: This method is slow because it has to search the DOM for elements with IDs that meet the criteria, but it does the job. I've never noticed an appreciable latency.
This is solved through selector magic as filoxo described but since you want the images, here's another version involving find() to get your actual images.
$('div[id^="filtertab-"]').find("img.lazy").each(function(i) {
$(this).delay(150*i).fadeIn(1000, function() {
var src = $(this).attr("data-original");
$(this).attr('src',src);
});
});
In addition to that, check out the impressive list of jQuery selectors. They cover a lot of ground :)

jQuery only being applied to a single button, not all instances of it

I have a page with a dynamic number of buttons all with the id "delete-button". My jQuery works great, but only on the first instance of "#delete-button".
$(document).ready(function(){
$('#delete_button').mouseenter(function() {
$(this).closest('tr').css('border-left', 'solid');
$(this).closest('tr').css('border-left-width', '2px');
$(this).closest('tr').css('border-left-color', '#dd3333');
});
$('#delete_button').mouseleave(function() {
$(this).closest('tr').css('border-style', 'none');
});
});
What cold be causing this? Can I not have more than one button with the same id?
If there are multiple elements with the same id, the id selector will only get the first one. You should be using class names instead. e.g.
$('.delete_button').mouseleave(...
Id should be unique (only one). Use .delete_button class instead.
<button id="delete_button1" class="delete_button"></button>
<button id="delete_button2" class="delete_button"></button>
....
<button id="delete_buttonN" class="delete_button"></button>
$(function(){
$('body').on('mouseenter', '.delete_button', function() {
$(this).closest('tr').css({
'border-left' : 'solid',
'border-left-width' : '2px',
'border-left-color' : '#dd3333'
});
});
$('body').on('mouseleave', '.delete_button', function() {
$(this).closest('tr').css('border-style', 'none');
});
});
both answers are correct, but to elaborate on that just a touch. Valid html dictates that you cannot have the same id on multiple elements in a given page. Id's are meant to be a unique identifier for an element. Jquery treats this as though there can truly be only one id on the page so it will stop looking through the dom for more elements that match the id selector once it has found one. If you want to apply your logic to multiple elements with the same call, you must assign a class to those elements as they are meant to be used multiple times. jquery knows this and will find all elements that match your class selector.

jQuery colon selectors

In jQuery there are a few colon selectors like
:prev, :next, :last
My question is:
Are they truly part of jQuery, because they are actually used on DOM elements?
We seem to have equivalent methods as well in jQuery prev(), next(), last(). What is the purpose of having 2 different ways?
Any basic examples would be really great.
jQuery does not have :prev or :next selectors, I have no idea where you came across them. There is a :last selector, though, as well as :first, provided by the Sizzle selector library, used by jQuery. It is a non-standard selector, not part of CSS, and is thus implemented in JavaScript.
One purpose of the :last selector over the .last() method is so you can use it to filter elements in the middle of a selector sequence, like this (note that :last and :last-child are not the same):
$('.a > .b:last > .c')
Rather than having to write a chain of methods like this:
$('.a').children('.b').last().children('.c');
By the way, the "colon selectors" you refer to are called pseudo-classes (colloquially but incorrectly known as "pseudo-selectors").
Here is how I made a slider with all sorts of selectors and traversing of objects.
$('#next').click(function () {
if (!$('*').is(':animated')) {
if ($('div.display:visible').is(':nth-child(3)')) {
$('div.display:visible').fadeOut();
$('div.display:first').fadeIn(function () {
$(this).children().fadeIn();
});
} else {
$('div.display:visible').fadeOut().next().fadeIn(function () {
$(this).children().fadeIn();
});
}
}
});
$('#prev').click(function () {
if (!$('*').is(':animated')) {
if ($('div.display:visible').is(':nth-child(1)')) {
$('div.display:visible').fadeOut();
$('div.display:last').fadeIn(function () {
$(this).children().fadeIn();
});
} else {
$('div.display:visible').fadeOut().prev().fadeIn(function () {
$(this).children().fadeIn();
});
}
}
});
yes, they are in the documentation
sometimes you can't always include everything in the selector or want a subdivision of the selector.
e.g.
$(".mylist").each(function(){
$(this).css("color","red");
$(this).next().show();
})
The colon represents a filter like to get the selected option in a dropdown I would use $("select option:selected") or to get a checked radio box I would use $("input[type=radio]:checked");
There are no :prev and :next filters, but you can find a full list of filters here http://api.jquery.com/category/selectors/

Categories

Resources