How to get the span id which starts with a word - javascript

actually i have two span with ids like this date_eform and time_eform.
Now i have to get these ids.. and check if the span id starts with date_ then i have to perform some logic. and if span id starts with time_ then another action.
<span id='date_eform'></span><span id='time_eform'></span>
Please help me in this.

you need starts with selector
so
$.each('span[id^="date_"]',function(){
//your code here
});
and
$.each('span[id^="time_"]',function(){
//your code here
});

Try this:
$("span[id^='date_']").something...
$("span[id^='time_']").something-else...

This should work:
$("span[id^={word}]")
Where {word} is the word you want the element id to start with.
The following like will help:
http://api.jquery.com/attribute-starts-with-selector/

this should do it:
$('[id^="date_"]')

jQuery syntax for attribute ends with:
$('span[id$="_eform"]')
jQuery syntax for attribute starts with:
$('span[id^="_eform"]')
jQuery syntax for attribute contains:
$('span[id*="_eform"]')
From what I understand, you should need to do something like:
$('span[id$="_eform"]')
Then, with an each method, test if jQuery-object ids are date or time.
var elements = $('span[id$="_eform"]');
elements.each(function() {
if(this.id.substring(0,5)=='date') {
// handle dates
} else if(this.id.substring(0,5)=='time_') {
// handle times
}
});

You can use a variety of ways to achieve this, most of those questions are listed in the other answers.
However, if you only have 2 elements, why aren't you just accessing them directly with the ID? Maybe you want to do something to them once an action has been carried out on them? In which case all the methods listed here can't be used.
If you simply want to bind the two selectors you can just use
$('#date_eform, #time_eform')...
What you're asking for doesn't make too much sense in the context of your question. If you add more details, there may be a better way to do what you're asking for.

I suggest you use id and class for this task; it would make it clearer. Example below:
HTML:
<span id='date' class='eform'></span>
<span id='time' class='eform'></span>
JavaScript (using jQuery):
$(".eform").each(function() {
switch (this.id) {
case "date":
// do something
break;
case "time":
// do something
break;
default:
// "id" is not a case
}
});
Example here: http://fiddle.jshell.net/9hcfx/

Related

Regex in javascript replace function

Am newbie to regex am trying to do some regex replace function in java script here is my content and code
jQuery("td[headers='name_head']").each(function (index, value) {
var text = jQuery(this).html();
if( text.indexOf('<a href=') >= 0){
jQuery(this).text(text.replace(/<a href=.*\"$/, ""));
}
});
Html content will be look like this
Calculate Points
i just want to remove only the value inside href ""
Please throw some light on this
Regards
Sathish
The text() method just retrieves the text contents which doesn't include any HTML tags. You can use html() method with a callback function where you can get the old HTML content as the second argument to the callback and based on the old value generate updated HTML.
The better way is to update the href attribute value of a tag to empty by directly selecting them, there is no need to loop over them since all values need to be empty.
jQuery("td[headers='name_head'] a").attr('href', '');
UPDATE 1 : In case you want to iterate and do some operation based on condition then do something like this.
jQuery("td[headers='name_head'] a").each(function(){
if(//your ondition){
$(this).attr('href', '');
}
});
or
jQuery("td[headers='name_head']").each(function(){
if(//your ondition){
$('a', this).attr('href', '');
}
});
UPDATE 2 : If you want to remove the entire attribute then use removeAttr('href') method which removes the entire attribute itself.
jQuery("td[headers='name_head'] a").removeAttr('href');
Why would you reinvent the wheel?
You don't need regex to achieve this, you can simply do it this way:
jQuery("td[headers='name_head'] a").attr('href', '');
It will set href to "" for all <a> elements inside td[headers='name_head'] so it will always respect your condition.
I haven't tested this code; but something like this should help, don't think you need to use regex for this;
$('a.DisableItemLink[href!=''][href]').each(function(){
var href = $(this).attr('href');
// do something with href
})
This piece of code selects all elements which have the class DisableItemLink with a location set and sets it to blank.
I am curious as to what you are trying to do in the larger scheme of things though, sounds like there might be better ways to go about it.
Reference: some good selector combinations for links

Using javascript to insert id into list elements

I am messing around with a deck of cards that I made.I have it set up so that there is a method that spits out cards by suit into a list, so if I want spades I get a <ol> of all of the spades cards. I am now trying to give each <li> element an id depending on what card it is. ace will be <li id="ace"><img src="ace_spades.gif"/></li> king will be <li id="king"><img src="king_spades.gif"/></li> for example.The list is in order from top to bottom akqj1098765432 . I tried doing this:
var card_id=["ace","king","queen","jack","ten","nine","eight","seven","six","five","four", "three","two"];
var counter=0;
while (counter<=12)
{
$(document).ready(function(){
$("li").eq(counter).attr("id", card_id[counter])
});
counter++;
}
but it doesn't work. I have not really done anything with javascript before besides simple jquery stuff. What am I getting wrong here?
Try this:
$(document).ready(function(){
var card_id = ["ace","king","queen","jack","ten","nine","eight","seven","six","five","four", "three","two"];
$.each(card_id, function(i,id){
$("li").eq(i).attr('id',id);
});
});
You should try to only have one $(document).ready() function and it's not necessary to use a while() loop.
I think you don't need to call $(document).ready() function in the while. Try this:
var card_id=["ace","king","queen","jack","ten","nine","eight","seven","six","five","four", "three","two"];
var counter=0;
while (counter<=12){
$("li").eq(counter).attr("id", card_id[counter]);
counter++;
}
You do not need the document ready function. Place your script just before </body> and after the jquery.js script. This is working for me.
Check working example at http://jsfiddle.net/H8MeG/2/
First of ID's in a webpage have to be unique. Some browsers might ignore id's of elements that have already been used. Other browsers might fail completely...
Second off. you shouldn't use .eq() like that.
You definitely shouldn't add 12 new $(document).ready() statements.
Here's a more reliable version and the example on jsfiddle
var card_id=["ace","king","queen","jack","ten","nine","eight","seven","six","five","four", "three","two"];
$("#spades li").each(function(index){
$(this).attr("class", card_id[index]);
$(this).text(card_id[index]);
});
I also added $(this).text(card_id[index]); so you see it actually works. Try to uses classes for multiple elements that share the same characteristic.
why are you messing with ids at all?
you know that the first item is the ace, the second the king, and so on.
ol.getElementsByTagName('li')[12]='deuce'

Switching between two different classes jQuery

Having trouble getting the following code to work:
$('#changeMode').button().click(function(){
$('#playfield').toggle(function() {
$(this).switchClass("gridView","plainView");
}, function() {
$(this).switchClass("plainView","gridView");
});
});
I cannot get it to switch the following div's class.
<div id="playfield" class="gridView"></div>
Any ideas?
EDIT: I tried this:
$('#changeMode').button().click(function(){
if ($('#playfield').attr('class') == "gridView"){
$('#playfield').removeClass("gridView");
$('#playfield').addClass("plainView");
} else {
$('#playfield').removeClass("plainView");
$('#playfield').addClass("gridView");
}
});
And it seems to work fine, what the heck?
I wasn't aware of a switchClass, perhaps you were thinking of toggleClass? Anyways - I had some old code that used this (I was having some strange issues with toggleClass):
$(this).removeClass("gridView").addClass("plainView");
or
$(this).toggleClass("gridView plainView");
and vice versa.
Example:
$('#changeMode').button().click(function(){
$('#playfield').toggle(function() {
$(this).toggleClass("gridView plainView");
//$(this).removeClass("gridView").addClass("plainView");
}, function() {
$(this).toggleClass("plainView gridView");
//$(this).removeClass("plainView").addClass("gridView");
});
});
But as others have suggested toggleClass should work for your needs.
The correct syntax is to use "One or more class names (separated by spaces).." ( from .toggleClass()) within the first parameter, rather than quoting classnames in the first and second parameter.
e.g.
$(this).toggleClass("gridView plainView");
just use the toggleClass twice will do the magic . toggoleClass refference to Jquery
This method takes one or more class names as its parameter. In the first version, if an element in the matched set of elements already has the class, then it is removed; if an element does not have the class, then it is added.
as for ur problem .
$('#changeMode').button().click(function(){
$(this).toggleClass('gridView').toggleClass('plainView');
});
help this will solve ur problem .
#Guy toggleClass('gridView plainView') this will actually be alternates bettween
<div class="gridView plainView"> and <div class=" ">. and not toggle bettween the two classe . no offence . hope this will do some help .
jQuery also has a toggleClass API:
http://api.jquery.com/toggleClass/
This works just like what Rionmonster suggested, adding classes when they aren't set on the class and removing them when they are already set.

Can I remove just the last added class from an element with jQuery

Hey guys, the question pretty much asks itself... however, for more clarity:
I have an element called "chuckPalahniuk" and it has classes named "choke", "fightclub" and "haunted".
How could I get it so when I click on the "chuckPalahniuk" element, it removes "haunted" first, then "fightclub" on the second click and "choke" on the third?
also: be aware that the class names are dynamically added.
Cheers. peeeps!
psy.example:
$('#chuckPalahniuk').click(function() {
$(this).removeLastClassAdded(); //except this function doesn't exist...
});
just save in an array variable c every class you add c.push('yourclass'), then $(this).removeClass(c.pop());
http://www.devguru.com/technologies/ecmascript/quickref/pop.html
This will do it and will deal with leading and trailing whitespace, which a split()-based solution will not:
$('#chuckPalahniuk').click(function() {
this.className = this.className.replace(/(^|\s+)[^\s]+(\s+)?$/, "");
});
Something like:
$('#chuckPalahniuk').click(function() {
$(this).removeClass($(this).attr('class').split(/\s+/).pop());
});

Count Upwards for ID jQuery

I have the following HTML structure
<div id="test-1-yay"></div>
... bunch of code ...
<div id="test-2-yay"></div>
... bunch of code ...
<div id="test-3-yay"></div>
I was wondering how I can use jQuery to basically identify each of these "id's" and then apply some jQuery to them ? I'm new to this so little unsure ? Something like
if $('#test-1-yay' || '#test-2-yay' || '#test-3-yay') {
do stuff to all ID's
}
But the prob is I want this to continue as it could go to #test-201-yay, #test-202-yay etc ?
Thx
Why don't you add a class to the divs?
You could try something like:
$("div[id^='test']")
or
$("div[id$='yay']")
or try to combine the two
Manual
You could use a substring selector to get most of the way there:
var divs = $('div[id^=test-]'); // All divs with IDs starting with "test-"
...which would work better if you changed the naming convention a bit so the number was at the end. But I think I'd lean toward using some other aspect of the structure (the parent node), or a class, or a data-xyz attribute...
Edit A pair of substring selectors can do it:
var divs = $('div[id^=test-]').filter("div[id$=yay]");
That gets all of the ones whose IDs start with "test-" and then filters out the ones that don't end with "yay". Close, anyway...
you could do it like that:
$("div[id^=test-]").each(function(){ //selects all dives having the string 'test-' in it
$that = $(this)
$that.text($that.attr("id").split("-")[1]) //splits the sting by "-" and gives you out the middle part (in your case the number)
})
test it here http://jsfiddle.net/aj5Qk/1/

Categories

Resources