Count divs with a certain class - javascript

Seems pretty simple but I can't get it to work.
I have two divs with the class 'user'. I want to output "you have 2 divs".
<script type="text/javascript">
$(document).ready(function() {
function divcount() {
var mycount = $('.user').length();
document.write(mycount)
}
});
</script>
I'm sure I'm missing something simple..

It’s either $('.user').length (length property of Array) or $('.user').size() (size method of jQuery).

Length is a property not a function. Size is a function.

$(".user").length // use the length property
$(".user").size() // use the size method
notice that the code must be include in the $(function(){...}) block; like:
$(function(){
alert( $(".user").length );
alert( $(".user").size() );
});

It's just $('.user').length. It's a property, not a method call.

Related

Hide an element when a specific string is present in the url

I want to hide a button when the string "wholesale' is present in the url. I've tried a few variations of the following code but it just won't work.
<script type="text/javascript">
$(document).ready(function () {
if (/wholesale/.test(window.location.href)) {
document.getElementsByClassName('variations_button')[0].style.display = 'none';
}
});
</script>
May be this will help.
var patt = new RegExp("wholesale");
if (patt.test(window.location.href)) {
$('.variations_button').hide();
}
you are doing wrong with the select element by class name code
it should be like this:
document.getElementsByClassName('variations_button')[0].style.display='none'
Note:
document.getElementsByClassName returns an array of elements with the same class name. So document.getElementsByClassName('variations_button')[0] will return the first element with the class name variations_button.
you have a problem with getElementByClassName, it should be getElementsByClassName and will return a HTMLCollection (Array like object) not an element. You should probably also use jQuery if that is already loaded on the page. jQuery is an array like object of HTMLElements that will give you methods that will run over the entire collection.
edit:
here is a working example, click 'Run code snippet' to see the result. I had to change the regex to match what was in the snippet, but you should get the idea.
console.log( 'is jQuery installed on the page', typeof $ !== void 0 );
$(function () {
console.log( 'href', window.location.href );
if (/stacksnippets/.test(window.location.href)) {
console.log('regex found in href');
$('.variations_button').css('background', '#3cf');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>
<button class="variations_button">variations button</button>

Hiding content depending on variable value

I am making a price estimator.
How would correctly write a jQuery function that checks a variable and depending on that amount hides/shows a certain div element accordingly.
So if I had:
a HTML div with the ID 'Answer'
<div id="answer">Hide Me</div>
$("#answer")...
a variable (this variable would change)
var x = 30
Now I know the css to hide the div would be:
#answer{
visibilty:hidden;
}
What would be the correct way to hide the function checking these certain parameters? for example if x > 20 then hide etc
Now I know there will be many ways to do this and they may not require jQuery, please inform me if this is the case. Perhaps it just needs JS. I know there will be many ways to do it not just one so if you have a different way please comment as I am keen to learn.
Any help would be greatly appreciated.
Cheers
F
Note that you can also remove or add a class:
$('#answer').removeClass('hide');
$('#answer').addClass('hide');
But what you want to do is $('#answer').hide(); or $('#answer').show();
Execute this function providing the variable v:
var checkVar = function(v) {
var target = $('#answer');
if (parseInt(v) > 20) {
target.hide();
} else {
target.show();
}
}
For example, if the variable comes form a selection:
$('#selectId').on('change', function() {
checkVar($(this).val());
});
Remove the CSS. You can do it in jQuery
if(x>20){
$('#answer').hide();
}
You can use this one
$("#answer").hide();
#kapantzak's answer looks good. But keep your logic and style separated and if your not going to use the variable for the actual element twice, I wouldn't make it. So go:
var checkVar = function(var) {
var element = $('#answer');
if (parseInt(var) > 20) {
element.addClass('hidden');
}else{
element.removeClass('hidden');
}
}
And in your CSS go:
#answer.hidden{
display: none;
}
Also, depending on your preference, display: none; doesn't display anything of the object whereas visibility: hidden hides the object but the space the object was occupying will remain occupied.
HTML
<input id="changingValue">
...
<div id="answer">Hide Me</div>
CSS (not mandatory if you check values on loading)
#answer{ display:none;}
JS
var limit = 20;
$(function(){
$("#changingValue").change(function(){
if(parseInt($("#changingValue").val())<limit) { $("#answer").show(); }
else { $("#answer").hide(); }
});
});

How to set marginLeft property using JavaScript?

I used the following code to set the left margin for a div with id=""
document.getElementById('s4-ca').style.marginLeft = '0px';
However getting an error like Object Required!
UPDATE - My code
<script type="text/javascript">
var groupName;
$().SPServices({
operation: "GetGroupCollectionFromUser",
userLoginName: $().SPServices.SPGetCurrentUser(),
async: false,
completefunc: function(xData, Status) {
$(xData.responseXML).find("[nodeName=Group]").each(function()
{
groupName = $(this).attr("Name");
});
}
});
if($.trim(groupName) != 'ABC')
{
document.getElementById('s4-leftpanel').style.display = 'none';
document.getElementById('s4-ca').style.marginLeft = '0px';
}
</Script>
There's nothing wrong with your JavaScript, just give the <div> a matching id property, then it should work fine, i.e.
<div id="s4-ca"></div>
So there reason you're getting the error is because document.getElementById('s4-ca') doesn't find a en element with a matching id, so it's null, and you can't reference the style property on a null object.
Also, when you set the marginLeft there's no need to specify units for zero, you can use just 0.
document.getElementById('s4-ca').style.marginLeft = "0";
Not reproducible: http://jsfiddle.net/VH2z2/
I assume you call document.getElementById before the element is available.
Either include the code on the bottom of the page or in the load event handler, e.g.
window.onload = function() {
document.getElementById('s4-ca').style.marginLeft = '0px';
};
You should not do this if there is other JavaScript code which might set a load event handler (you would overwrite it).
Something like this possibly?
$('#s4-ca').css({ marginLeft: 0 });
the problem is "object requierd"
that means that
document.getElementById('s4-ca')
returns nothing, you must make sure an element with id 's4-ca' exists
$('#s4-ca').css({ marginLeft: 0 });
or
$('#s4-ca').css('margin-left', 0 );
your code is not jquery, but the code above is the way to do this in jquery, both work.
update: your error message probably means that there is no element with id="s4-ca", please check for such an element! see this jsfiddle: http://jsfiddle.net/4DzyW/ where your code just works.
if you want to use jQuery (according to your question's tag)
$("#s4-ca").css('marginLeft','0px');
.css Api of jQuery

JQuery, a new Selection using the results

Is there a way to me do this?
<img id="example" src="anything.jpg" title="something" class="abc" />
$('.abc').each(function(){
//test if this result is something
if( $(this)...(???)...('[src^=anything]')) == 'anything.jpg'){
}
//another Jquery selector test for this one
if( $(this)...(???)...('#example').size() > 0){
}
});
This is just an example, what I need is pretty more complex.. But I would like to know if there is a way to make other jQuery selector test in the result of a first selector.. since "find" will find the children of $(this).. and .parent() get alot of brothers..
See what I mean?
Do you have any idea?
So sorry.. let me try again..
$('div').each();
get all "div", right?
But now in that function I need to make another "test" check if div class is "red" or "blue"..
See?
I need to test something else of the result based in Jquery selector..
I know I could do:
class = $(this).attr('class'); and then if(class=="blue"){} .. But I would like to do $('this[class=blue]').size()>0){}
The jQuery is() filter operates on a found set to detect if something is true or not.
The jQuery filter() method will further pare down a found set based on criteria.
var allDivs = $('div');
var greenOnes = allDivs.filter('.green');
var redOnes = allDivs.filter('.red' );
I think you need the is method:
$('.abc').each(function() {
$(this).is('[src^=anything]')
});
This is fairly simple though, but I can't really tell what you are trying to do by the description. Maybe this is enough to get you started though.
You can use the filter and is methods to filter/search within a jQuery object.
if( $(this).is('[src^="anything"]') ) {
}
elseif( $("#example").size() > 0) {
}
You could put $("#example") in a variable outside of the loop and then reference it inside the loop as well.
if(this.src.indexOf("anything") === 0) {
// source starts with 'anything'
}
if($("#example").length) {
// since there can be only one #example
// in a *valid* document
}
Based on your edit:
if($(this).hasClass("blue")) {
...
}
?

Replacing fields with jQuery

Why is line 10 returning null?
http://pastie.org/720484
it works with line 40
You do not seem to have a proper grasp of the siblings() operator. You also were not utilizing jQuery's val() function and were missing periods on some of your class names. To locate the address1 class you would need to do the following:
var $checkbox = jQuery(this);
$checkbox.parent().siblings('.formField').find('.address1');
Also, you would want the alert to be
alert($checkbox.parent().siblings('.formField').find('.address1').val());
to alert the value of the input box.
FIXED AND OPTIMIZED VERSION:
function update_address(eventObject) {
var $checkbox = jQuery(this);
var $siblings = $checkbox.parent().siblings('.formField');
if ($checkbox.attr('checked')) {
$siblings.find('.address1').val($('.hidden_address1').val());
$siblings.find('.address2').val($('.hidden_address2').val());
$siblings.find('.city').val($('.hidden_city').val());
$siblings.find('.state').val($('.hidden_state').val());
$siblings.find('.zip').val($('.hidden_zip').val());
$siblings.find('.province').val($('.hidden_province').val());
$siblings.find('.country').val($('.hidden_country').val());
} else {
$siblings.find('.address1').val('');
$siblings.find('.address2').val('');
$siblings.find('.city').val('');
$siblings.find('.state').val('');
$siblings.find('.zip').val('');
$siblings.find('.province').val('');
$siblings.find('.country').val('');
}
}
try fetching the input:text's .val() instead
On line 9, shouldn't it be var checkbox = $(this); instead? I've not seen the jQuery() function used like that.
Because <input class="address1"/> is not a sibling of <input id="parent_sameAsBefore"/>. I think you want:
checkbox.parent().parent().find('.address1');
Why not just go with finding the form fields using absolute path?
Unless your DOM is very convoluted (and you need relative paths), I would prefer this approach myself.
Also use .val() to get and set values.
function update_address(eventObject) {
if($(this).attr('checked')) {
$('#parent_address1').val($('hidden_address1').val());
$('#parent_address2').val($('hidden_address2').val());
$('#parent_city').val($('hidden_city').val());
$('#parent_state').val($('hidden_state').val());
$('#parent_zip').val($('hidden_zip').val());
$('#parent_province').val($('hidden_province').val());
$('#parent_country').val($('hidden_country').val());
}
else {
$('#parent_address1').val("");
$('#parent_address2').val("");
$('#parent_city').val("");
$('#parent_state').val("");
$('#parent_zip').val("");
$('#parent_province').val("");
$('#parent_country').val("");
}
}
Note, seems to be a bug in the original code in line 15:
checkbox.siblings('.tate').value = $('hidden_state').value;
Should be:
checkbox.siblings('.state').value = $('hidden_state').value;
alert(checkbox.siblings('.address1').html() ); // This should be
alert(checkbox.parent().siblings('.address1').html() );
//Checkbox does not have siblings
Line 10

Categories