I have a problem detecting a visibility state of checkbox and I would like to ask you for a help.
I have a dynamicaly loaded part of the page, which looks like:
<div id="box">
<div class="colored">
<input type="checkbox" value="f01" name="mycheckbox">
<!-- some content -->
<div>
<div class="colored">
<input type="checkbox" value="f02" name="mycheckbox">
<!-- some content -->
<div>
<!-- .... -->
</div>
This represents, shall we say, items in some gallery. Every class="colored" div can be VISIBLE or HIDDEN.
Lets say, it is the simple filter, like I want to have visible only class="colored yellow" divs
And now the core of the problem:
I need to loop through whole BOX element, find all checkboxes and by each checkbox, "ask him", if it is visible, and if true, check him.
Unforunately, this doesn't work:
function checkallfav() {
$("#box").find('input[type=checkbox]').each(function () {
if (this.is(":visible")) {
this.checked = true;
}
});
}
//And this doesn't work as well
function checkallfav() {
$("#box").find('input[type=checkbox]').is(":visible").each(function () {
this.checked = true;
});
}
The problem is, that the FIND function returns the whole element, I tried
Console.debug(this); and in firebug, the response was all html element
So, please, anyone has a solution?
Use :visible selector on checkbox itself. Using :visible on selector will filter out only visible elements and then prop can be directly used on those checkboxes.
$("#box").find('input[type=checkbox]:visible').prop('checked', true);
The code can also be shorten as
$('#box :checkbox:visible').prop('checked', true);
Here this refers to native DOM object and they don't have .is() function its a jQuery function thus have to use with jQuery object. Thus $(this).is(":visible") should be used.
$("#box").find('input[type=checkbox]').each(function () {
if ($(this).is(":visible")) {
this.checked = true;
}
});
A simpler way to achieve is by using #Tushar's recommendation
You could use prop() function parameter too:
$("#box").find(':checkbox').prop('checked',function(){
return $(this).is(':visible');
});
This would by the way uncheck any hidden checkbox (if needed).
This can be achieved with .filter() method:
$("#box").find('input[type=checkbox]').filter(':visible').prop('checked', true);
Related
which option among the following is better or used as a standard way to show/hide the html elements
changing element.style.display
adding/removing a separate class called hide {display: none}
any other standard way
PS: this JavaScript hide/show element question uses the first option mentioned( changes the style to block to show which may not be desired). I would like to know whether this method is used in most websites or the adding /removing a separate class or any other way
A third way in the answers below https://stackoverflow.com/a/68983509/14478972
I prefer to toggle a class using DOMTokenList.toggle():
The toggle() method of the DOMTokenList interface removes a given token from the list and returns false. If token doesn't exist it's added and the function returns true.
Well except the first and second, there is the other way.
Which is rendering the element its self.
It has a better security. as the user wont know if there is a hidden element inside the toggle div. Eg when people try to look at the html
Have a look below
I used jQuery as its easier to write. If you are not able to rewrite a JavaScript version will be happy to rewrite for you.
var items = $(".toggle");
var item = {};
// setup the auto toggle
$(".toggle").each(function(el) {
var id = new Date().getUTCMilliseconds() + $(this).index()
item[id] = $(this).find("content")
if (!$(this).hasClass("show")){
$(this).find("content").remove();
}
$(this).attr("id", id)
});
$(".toggle").click(function() {
if ($(this).find("content").length > 0)
$(this).find("content").remove();
else $(this).append(item[$(this).attr("id")])
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="toggle">
<h1>click here to toggle content </h1>
<content>
this is a test
</content>
</div>
<div class="toggle show">
<h1>click here to toggle content(start state is visible) </h1>
<content>
this is a test
</content>
</div>
Option 1 would be standard for only hiding the element, but if you would like to add other styles like transitions and pointer events option 2 is preferred
Right now I have a a bootstrap row set up with a checkbox and input inside of it.
<div class="row">
<div class="AdminFees">
<div class="col-md-2"><input type="checkbox" class="make-switch feeswitch" data-on-color="info" data-off-color="info" data-on-text="Yes" data-off-text="No" name="HasPerMemberFee" checked="#Model.Contract.HasPerMemberFee" /></div>
</div>
<div class="col-md-2"><input type="text" class="form-control" placeholder="$0.00" id="PerMemberFeeAmount" name="PerMemberFeeAmount" value="#Model.Contract.PerMemberFeeAmount" /></div>
I have 6 or 7 very identical field pairs that I am manipulating generically so I don't have to make multiple functions. I am having trouble figuring out how to reference the text input element from the checkbox element.
Jquery:
$('.feeswitch').each(function () {
$(this).on('switchChange.bootstrapSwitch', function () {
if ($(this).bootstrapSwitch('state') == true)
$(this).next('input').css('visibility', 'visible');
else
$(this).next('input').css('visibility', 'hidden');
});
});
I have tried next and nextAll, but to my understanding, those only find child elements. I need to know how to select the child of the second adjacent parent element.
In an attempt to simplify the situation:
The checkbox has 2 parents, the two divs, and 1 adjacent element, the other div column. I need to access the child of that other div column, but it needs to be generically so I don't need to make 8 functions for each checkbox/input pair on my page.
I'm not sure I agree that the accepted solutions is stable, since it's selector greatly depends on keeping your structure the same, which I would suggest is unlikely in most projects. If I might suggest an alternative, I think the better method here is to employ the scope parameter of the selector.
$('.feeswitch').on('switchChange.bootstrapSwitch', function () {
var switchState = $(this).bootstrapSwitch('state') ? "visible" : "hidden";
$('input',$(this).closest('.row')).not($(this)).css('visibility', switchState);
});
Regardless, you should definitely look more in to jQuery DOM traversal methods, as that's pretty much the big magic of jQuery:
https://api.jquery.com/category/traversing/
You'll want to say something like:
$(this).parent().parent().next('div').find('input').
css('visibility', 'visible');
And since this is generic, you don't need the each():
$('.feeswitch').on('switchChange.bootstrapSwitch',
function () {
var visi = $(this).bootstrapSwitch('state') ? 'visible' : 'hidden';
$(this).parent().parent().next('div').find('input').
css('visibility', visi);
}
);
This might be an easy one for you, but I'm stuck, so I hope you can help me.
I'm creating checkboxes through a loop and want to specify a text somewhere in the website if a checkbox is clicked.
I'v seen solutions where a make a script for each checkbox, but that could turn out to be alot sometimes (something like this: chckbx.onchange = function(){} )
I'd rather have one function that is called from different checkboxes, but my javascript skills is basicly non-existing :)
This is what i got so far (which ofcourse dosn't work)
http://jsfiddle.net/Sz3BK/130/
You have jQuery tagged in your question, so I'm going to provide a jQuery answer:
You'd use jQuery's on() method to delegate the event to a non-dynamic ancestor of your checkbox:
$('elem').on('change', 'input[type="checkbox"]', function() {
...
});
Where elem is a non-dynamic ancestor of your checkbox.
In your JSFiddle your checkbox isn't dynamic, but assuming it was, the closest non-dynamic ancestor of it would be the document's body. Therefore, we can use:
$('body').on('change', 'input[type="checkbox"]', function() {
testing('hello', '1');
});
JSFiddle demo.
You may want to extend this by passing in "hello" and "1" as data-* attributes:
<input type="checkbox" name="test" data-newvalue="hello" data-spanid="1" />
<input type="checkbox" name="test" data-newvalue="second" data-spanid="2" />
Here I've created two checkboxes with our two data-* attributes. In our jQuery method we can pull these values and pass them into our testing() function using jQuery's data() method:
$('body').on('change', 'input[type="checkbox"]', function() {
testing($(this).data('newvalue'), $(this).data('spanid'));
});
JSFiddle demo.
We can then modify our testing() function to also use jQuery:
function testing(newValue, spanID) {
$('#'+spanID).text(newValue);
}
This pulls our spanID (e.g. "1") and places it within an ID selector $('#1'), then modifies the text using jQuery's text() method. If you wanted to modify the HTML instead, jQuery also has a html() method for this purpose.
Final JSFiddle demo.
because you are adding che checkboxes dynamicly,
to enable the change event for those added later, use code below
$(document).on('change', 'input[type="checkbox"]', function() {
...
});
Change your jsfiddle code http://jsfiddle.net/Sz3BK/136/ like this...
Add <head></head> in HTML code at top..
and change on load to "No wrap - in head"
This code works fine for me:
$('input[name=test]').change(function(){
if($(this).is(':checked'))
{
alert("chk");
// Checkbox is checked.
}
else
{
alert("unchk");
// Checkbox is not checked.
}
});
Check the fiddle. Hope it helps.
The following code (*) for toggling the disabled attribute beetween two buttons works and you can check it at http://jsfiddle.net/cNSVX/3/.
I was wondering what is the best way to generalise this code in order to attach this behaviour to a couple of buttons.
Something like the following.
body.onload(togglingButton(elem1, elem2));
$('#filterOpened').click(function() {
$('#filterOpened').attr('disabled', 'disabled');
$('#filterClosed').removeAttr('disabled');
});
$('#filterClosed').click(function() {
$('#filterClosed').attr('disabled', 'disabled');
$('#filterOpened').removeAttr('disabled');
});
function togglingButton (elem1, elem2) {
if (elem2.attr('disabled')) {
elem1.attr('disabled', 'disabled');
elem2.removeAttr('disabled');
} else {
elem2.attr('disabled', 'disabled');
elem1.removeAttr('disabled');
}
};
You can do it like below with jQuery. Also if you are using jQuery 1.6+ then you should be using .prop() to toggle your disabled property.
Properties generally affect the dynamic state of a DOM element without changing the serialized HTML attribute. Examples include the value property of input elements, the disabled property of inputs and buttons, or the checked property of a checkbox. The prop method should be used to set disabled and checked instead of the .attr() method. The .val() method should be used for getting and setting value.
$('button').click(function(){ //<--- attaches click to all button's
$(this).prop('disabled',true); //<-- only disable the clicked button
$('button').not(this).prop('disabled',false); //<-- all button's but the clicked one should be enabled
});
here's an example fiddle http://jsfiddle.net/cNSVX/5/
If you are planning on excluding some buttons out of the toggling it would be a good idea to give them a class so you can select the ones you need/don't need easier
One simple way to do this would be to use jQuery's .data() function to link the two elements, then assign a single event handler to both:
function disableToggle(el1,el2) {
el1.data('partner',el2);
el2.data('partner',el1);
el1.add(el2).on('click',function(){
$(this).prop('disabled',true);
$(this).data('partner').prop('disabled',false);
});
}
$(function(){
var opened = $('#filterOpened');
var closed = $('#filterClosed');
disableToggle(opened,closed)
});
I've created a demo:
jsFiddle DEMO
I need to use jQuery to locate all DIV tags that have no attributes on them and apply a class to each. Here's a sample HTML:
<div id="sidebar">
<div>Some text goes here</div>
<div class="something">something goes here</div>
<div>Another div with no attributes.</div>
</div>
So, I need to take that and turn it into this:
<div id="sidebar">
<div class="myClass">Some text goes here</div>
<div class="something">something goes here</div>
<div class="myClass">Another div with no attributes.</div>
</div>
How do you locate elements of type div that have no attributes via jQuery? Thanks.
Here you go:
$('div', '#sidebar').filter(function () {
return this.attributes.length === 0;
})
Live demo: http://jsfiddle.net/phbU9/
The attributes property returns a list of all attributes set on the element. "Naked" elements have an empty attributes list.
Update: Be sure to read Tim's answer below which provides a solution for older versions of IE, since my own solution doesn't work in IE8 and below.
#Šime's answer is close but doesn't work in IE 6, 7 or 8, where an element's attributes collection has an entry for every possible attribute, not just those specified in the HTML. You can get round this by checking each attribute object's specified property.
Live demo: http://jsfiddle.net/timdown/6MqmK/1/
Code:
$("div").filter(function() {
var attrs = this.attributes, attrCount = attrs.length;
if (attrCount == 0) {
return true;
} else {
for (var i = 0; i < attrCount; ++i) {
if (attrs[i].specified) {
return false;
}
}
return true;
}
});
check this out:
http://jsfiddle.net/thilakar/CHux9/
You need to give some sort of selector, in this case Ive used your side bar but it can be anything. Then get the children that have no class attribute and add a new class. See JSFiddle for the example:
http://jsfiddle.net/HenryGarle/q3x5W/
$("#sidebar").children('div:not([class])').addClass('newClass');
So this would return the 2 elements with no class tag and leave the sidebar and div with the class completely unaffected.
You could use a combination of jQuery's has attribute selector and the not selector. For example:
$('div:not([class], [id])').addClass('myClass');
jsFiddle demonstrating this
With this approach, you need to explicitly specify the attributes to check the presence of. Sime's solution would apply the class to divs that do not have any attributes at all.
To expound upon Tim Down's answer, I recommend checking that the attrs var not null special cases where the html has comment tags, etc.
try $('div:not([class])').addClass('myClass');
it is a general approach because the class will apply to all the div that have no class
$('#sidebar div')` or more general `$('div'); //returns collections of divs
to answer the question:
$('#sidebar div').addClass('myClass');