Is there a way in jQuery to check if an ID value (Ex. id="number1") contains a number?
The idea would be:
if (ID has a number which will come from a variable) then do something.
this is what I came up with so far but it only works with the first div:
$("#tabsstyle li a").bind("click", function () {
var numSlide = $(this).attr("rel");
if ($('#slidesContainer div').attr('id').match(numSlide) ) {
$('#slidesContainer div').fadeIn();
}
numSlide will store a number coming from one of the 'a' clicked and check that number will be included in the id value of '#slidesContainer div', once that checked then the right div will fadeIn.
HTML structure below:
<div id="slidesContainer">
<div id="n1" class="slide">
<h2>Web Development Tutorial</h2>
<p><button class="test">N1</button></p>
</div>
<div id="n2" class="slide">
<h2>Grunge Brushes, Anyone?</h2>
<p><button class="test">N2</button></p>
</div>
<div id="n3" class="slide">
<h2>How About Some Awesome Grunge Textures?</h2>
<p><button class="test">N3</button></p>
</div>
<div id="n4" class="slide">
<h2>'Tis the End, My Friend.</h2>
<p><button class="test">N4</button></p>
</div>
</div>
var id = $('#element').attr('id'); // #element will replace
// with your desired selector
id.match(/[0-9]/g)
Checking
if( id.match(/[0-9]/g) ) {
// do something
}
You can take a look at the following jquery plugin
https://github.com/jquery/globalize
That handles "numbers" a number can be an integer or a decimal, and a decimal number has different representations based on the culture :)
You can use javascript to build a function with test and a regular expression to check if a string contains a number.
function hasNumber(t){
//regular expression: /\d/g
return /\d/g.test(t);
}
And then use jQuery to check the value of the attribute id
alert (hasNumber($('#checkMe').attr('id')))
Related
Is it possible with jQuery or Javascript to copy the first character of a string that's user generated to another div?
As an example, the contact list on iPhone. The first letter of the contact name is used in the circle adjacent to the name.
With the correct snippet the output would be as follows, where 'First name, Last name' will be different.
<div class="initial">F</div>
<div class="name">First name, Last name</div>
<div class="initial">J</div>
<div class="name">John Smith</div>
I tried to get some ideas from these other posts:
How do I make the first letter of a string uppercase in JavaScript?
How can I get the first three letters of a string in JQuery?
Detect character in div and remove it Javascript or jQuery
However, I'm not sure where to start and how to output the result to the 'initial' div.
The simple way to do this is to provide a function to text() of the .initial elements which reads the first character from the sibling .name and returns it, like this:
$('.initial').text(function() {
return $(this).next('.name').text().slice(0, 1).toUpperCase();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="initial"></div>
<div class="name">Foo Bar</div>
<div class="initial"></div>
<div class="name">John Smith</div>
a vanilla JS solution i came up with:
https://jsfiddle.net/y0c9be6g/
<div class="initial"></div>
<div class="name">Bob Smith</div>
<div class="initial"></div>
<div class="name">Jim Halpert </div>
<div class="initial"></div>
<div class="name">Billy Baldwin</div>
<script>
var names = document.querySelectorAll(".name");
var initials = document.querySelectorAll(".initial");
function addInitial(item){
item.previousSibling.previousSibling.innerHTML = item.textContent.charAt(0);
}
names.forEach(addInitial);
</script>
How to get 3.1 and 3.2 from following HTML using JQuery?
<div class="question3">
<div class="pure-u-1-2 questionNumber">
<p class="boldText">3.1 </p>
</div>
<div class="pure-u-1-2 questionNumber">
<p class="boldText">3.2 </p>
</div>
</div>
Tried JQuery:
$.map($('.questionNumber'), function (el) { alert(el.html) });
How to get question numbers dynamically for class question3 in JQuery?
You can use
var arr = $('.questionNumber').map(function(){ return +$(this).text() }).get()
This will produce this array: [3.1, 3.2]
Note that your own code fails because you use html instead of html().
So I used a script that I found on Stack Overlow to swap text. It worked great initially but then I tried to use it again on the same page and I noticed an issue.
You can see the problem here: JsFiddle
The HTML
<div class="gallerycard">
<div id="textMessage"></div>
<div class="textContent">
<div class="girlname">ONE LEFT</div>
</div>
<div class="textContent">
<div class="newgirl">TWO LEFT</div>
</div>
<div class="girlimage"></div>
<div class="girlinfo">TEXT</div>
</div>
<div class="gallerycard">
<div id="textMessage"></div>
<div class="textContent">
<div class="girlname">ONE RIGHT</div>
</div>
<div class="textContent">
<div class="newgirl">TWO RIGHT</div>
</div>
<div class="girlimage"></div>
<div class="girlinfo">TEXT</div>
</div>
The Jquery
var cnt=0, texts=[];
// save the texts in an array for re-use
$(".textContent").each(function() {
texts[cnt++]=$(this).text();
});
function slide() {
if (cnt>=texts.length) cnt=0;
$('#textMessage').html(texts[cnt++]);
$('#textMessage')
.fadeIn('fast').animate({opacity: 1.0}, 800).fadeOut('fast',
function() {
return slide()
}
);
}
slide()
So, how do I keep them from merging?
You need two arrays, one for each,
give each one of the gallerycards different ids
and do it twice
var cnt=0, firstTexts=[], secondTexts=[];
// save the texts in an array for re-use
$('#firstID > .textContent').each(function() {
firstTexts[cnt++]=$(this).text();
});
cnt = 0;
// save the texts in an array for re-use
$('#secondID > .textContent').each(function() {
secondTexts[cnt++]=$(this).text();
});
and call slide twice with the relevant array and id
There are multiple problems based entirely on too much copy/paste without understanding the why.
Both target divs have the same id. You should never have two elements on the same page which share the same id. Now there is a quick and dirty way to clean this up and there is a flexible and effective way to clean this up. I went for the flexible solution and I'll explain how it works as best I can.
<div class="gallerycard" data-target="textMessageLeft">
<div id="textMessageLeft"></div>
<div class="textContent">
<div class="girlname">ONE LEFT</div>
</div>
<div class="textContent">
<div class="newgirl">TWO LEFT</div>
</div>
<div class="girlimage"></div>
<div class="girlinfo">TEXT</div>
</div>
<div class="gallerycard" data-target="textMessageRight">
<div id="textMessageRight"></div>
<div class="textContent">
<div class="girlname">ONE RIGHT</div>
</div>
<div class="textContent">
<div class="newgirl">TWO RIGHT</div>
</div>
<div class="girlimage"></div>
<div class="girlinfo">TEXT</div>
</div>
Notice I added a data-target element to the gallerycard containing the id of the div we want to place the text into. I also changed the ids on each target div to be unique. This is critical to make it all work, as is the data-target element matching those ids.
texts = {};
// save the texts in an array for re-use
$(".textContent").each(function () {
var target = $(this).parent().attr('data-target');
if (texts[target] == null) { texts[target] = []; }
texts[target].push($(this).text());
});
function slide(divId, cnt) {
if (cnt >= texts[divId].length) cnt = 0;
$('#' + divId).html(texts[divId][cnt++]);
$('#' + divId)
.fadeIn('fast').animate({
opacity: 1.0
}, 800).fadeOut('fast',
function () {
return slide(divId,cnt)
});
}
for (var t in texts)
{
slide(t, 0);
}
In the javascript I changed a lot to make this an expandable and flexible solution, rather than simply duplicating what was already there with two separate names.
First, we removed the counter and changed texts to an object ({} instead of []). From here I can use texts like a hash, which simplifies the rest of the script. The key of the hash is the value of the data-target from the container div of the message and content divs. Add as many content divs as you want under each parent and they'll all be found and associated correctly.
The texts from each textContent div are stored in an array, but we are using the push() function to eliminate the need for a counter variable - counters are fine for a single instance, but they get ugly with multiples.
I changed the slide function to accept two variables: divId and cnt. divId is how the slider knows which div to target and cnt allows the recursive call to keep a private counter which will not conflict with other instances of the slider function running simultaneously.
Finally, to again prevent duplication and allow further expansion, Instead of simply calling slide, we iterate through the hash to get the divId and call a slide instance for each divId we have. Go ahead and try expanding the number of panes or adding new textContent divs under one of the headers. It all works very smoothly now.
The fiddle is here: http://jsfiddle.net/AX4LC/4/
I have a JQuery function that randomly chooses a DIV in a page full of DIVs. I'm trying to modify the function so that it checks the length of the H3 tag nested in the random DIV. If the string inside the H3 tag is over 10 characters long (including whitespace), the function should truncate the string and replace the contents of the H3 with this new shorter string and display it.
Example:
(jquery)
if ($('#main').length !== 0) {
var new_item = $('#main div').eq(Math.floor(Math.random() * $('#main div').length));
new_item.css('display','block');
}
(html file)
<div id="main">
<div id="m1" style="display:none;">
<h3>Apples are red</h3>
</div>
<div id="m2" style="display:none;">
<h3>Oranges are orange</h3>
</div>
<div id="m3" style="display:none;">
<h3>Bananas are yellow</h3>
</div>
</div>
(desired output - what user sees if DIV#m2 is randomly selected)
Oranges ar
$(new_item).find('h3').text($(new_item).find('h3').text().substr(0,10));
You already have the code that gets the random div element. The part you want to add is fairly trivial:
var h3_item = new_item.children("h3");
h3_item.html(h3_item.html().substring(0, 10));
I have a page that has 50 elements with the same class "fields" which are all display none at the moment
<div class="fields" style="display:none;">
...
</div>
<div class="fields" style="display:none;">
...
</div>
<div class="fields" style="display:none;">
...
</div>
<div class="fields" style="display:none;">
...
</div>
...
How to I only show the first 3 or whatever number. Plus count them with a count on top like the following example below.
So for example if I needed the first 3 this is what i need the divs to look like
<div class="fields">
<h1>Station 1</h1>
</div>
<div class="fields">
<h1>Station 2</h1>
</div>
<div class="fields">
<h1>Station 3</h1>
</div>
<div class="fields" style="display:none;">
...
</div>
...
So basically only some the number of divs that I need...I already have the number of elements I need to show in this blur statement in the station_count variable. Also notice i need a span tag with the count..any ideas on how to do this
$("#number_station").blur(function(){
var station_count = $(this).val();
//code goes there
});
How to I only show the first 3 or whatever number.
$('div.fields:lt(3)').show();
Plus count them with a count on top
$('div.fields:lt(3)').each(function (index)
{
$('<h1></h1>', {text: 'Station ' + index}).prependTo(this);
}).show();
Demo: http://jsfiddle.net/mattball/TssUB/
Read the jQuery API docs for basic questions like this:
:lt() selector
.prependTo()
jQuery() (for creating new elements)
While the other answers will work, I recently discovered and love the jQuery slice() method.
$(".fields").slice(0, 3).each(function(index) {
// Do whatever you want to the first three elements
}
With
$(".fields").each(function() {
//do whatever like count then show/hide
});
you can iterate over the hidden divs. So with a simple variable you can start/stop whenever you need.