Disable one group of select elements with checkbox using javascript / jquery - javascript

I have a one or more groups of select elements. I need to disable one at a time but both are being disabled. I am using a checkbox to activate the disable action. I am using javascript / jquery.
$(document).ready(function(){
$('#hour-check').change(function() {
$('select').prop('disabled', this.checked);
});
});
JSFiddle LINK

You're using the same id for each check box. These should be unique, or preferably, use a class.
You should also wrap the tables in a containing class to make traversing the DOM easier.
<div class="table-container">
<p>
<input type='checkbox' class="hour-check"> 24hr
</p>
...
Once you've done this you can use the following to disable the appropriate selects:
$('.hour-check').change(function() {
$(this).parents('.table-container').find('select').prop('disabled', this.checked)
});
See https://jsfiddle.net/d58euhas/

Related

How to grab ID of element which ID has been dynamically given?

I’m trying to make a simple show when checkbox is checked kind of section but am unable to get a hold of the element because the IDs of the element are assigned dynamically by PHP.
The element will be inside a foreach loop so there will be multiple instances of it with dynamically given IDs.
example:
//Laravel blade template
<element id="attrb{{ $elem->id }}> "></element>
//Javascript
if ($("#attrb*ID").is(":checked")) {
$("#attrbs-container").show();
} else {
$("#attrbs-container").hide();
}
With Jquery
$('input[id^="attrb"]').change(function(e){
if($(this).is(':checked')) console.log($(this).prop('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="attrb1" value="1" />
Run, and check the box. You can replace console.log with your .show or whatever.
The selector input[id^="attrb"] means an input with an id that ^= starts with attrb. You could also use input[type="checkbox"] if these are the only checkboxes you have, but it's less specific.
Change vs Click
change fires when the data (state) of the element changes. click will trigger anytime you click. In this case it probably doesn't matter too much which you use. A better example of change vs click is using radio buttons, and clicking an already checked radio. Checkboxes un-click when checked, radio buttons not so much. I'm just in a habit of using change over click for state changes.
$('input[id^="attrb"]').click(function(e){
if($(this).is(':checked')) console.log($(this).prop('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" id="attrb1" value="1" />
Run and click the radio 2x. It fires 2 times.
$('input[id^="attrb"]').change(function(e){
if($(this).is(':checked')) console.log($(this).prop('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" id="attrb1" value="1" />
Do the same thing here, but with change. That's the difference.
DYNAMIC vs Dynamic
What I mean here is DYNAMIC is something that changes at run time on the client, Dynamic is static HTML where the ID changes on the server side only. For DYNAMIC you want to use on like this
$(someparent).on('change', 'input[id^="attrb"]', function(e){ ... });
Where someparent is a static element that doesn't change at runtime. This will use event delegation and "bubbling" to find the content that was changed on the client side.
I don't think you meant DYNAMIC but I included it just in case.
Cheers!
you could create a function with a callback if you're assigning the id with javascript (after an ajax request)
function addID(add, callback)
Then use the funciton:
addId(function(){
//dynamically add ID
}, function(){
// callback function
if ($(“#attrb*ID”).is(":checked")) {
$(“#attrbs-container").show();
} else {
$(“#attrbs-container").hide();
}
})

Don't trigger JQuery on a disabled checkbox

I have a form with checkboxes. When users click on label, I have custom checkbox icon that gets swapped. That works fine, but I also have disabled checkboxes in the form, and I don't wan't the click event to be triggered when you click on the disabled ones. How do I do that?
JQuery:
$('input[type=checkbox] + label').click(function() {
$(this).toggleClass('checkbox-pressed');
});
HTML:
<input type="checkbox" id="A"><label for="A">Option 1</label>
<input disabled type="checkbox" id="B"><label for="B">Option 2 - don't trigger JQ</label>
Use :not(:disabled) to select only those checkboxes that aren't disabled.
$('input[type=checkbox]:not(:disabled)').click(function() {
...
});
Documentation: :not() and :disabled
You should rather use .on(). Otherwise it won't work for checkboxes that become disabled after the page loads up initially (say, because of some user action):
$(document).on('click', 'input[type=checkbox]:not(:disabled)', function() {
...
});
You can use the :enabled selector like this:
$(':checkbox:enabled').click(function() {
// Your code here...
});
it would be easier to use :checked in jQuery
you can find more here.

Show a text box based on select box value

I am wondering if someone could help me understand how I can achieve this. I want to show two input boxes only when a certain value in a select box is chosen using javascript (inc jquery).
My select box has this value:
<select name="menu-168" class="wpcf7-validates-as-required">
<option value="Residential">Residential</option>
<option value="Commercial">Commercial</option>
</select>
My input box has this value:
<input type="text" name="text-708" value="" class="wpcf7-validates-as-required" size="40">
In Pseudo code I am after something like this:
<if select name="menu-168" value = "Commerical">
<add css property ".hidden" to input name="text-708">
</if>
My javascript knowledge is so poor, would anyone mind showing me how this is done? This is a JSfiddle with the relevant HTML:
http://jsfiddle.net/K9zGP/
This is using jQuery:
if ($("select[name='menu-168']").val() == "Commercial") {
$("input[name='text-708']").addClass("hidden");
}​
On a side note, i would advise you to use class instead of names for referencing HTML elements. Class selection is much faster than attributes.
You can use .on() to attach a listener on the select, to listen for a change event. With the change-event listener you can act whenever someone changes the selected option. Then you can use .toggle() to show/hide the input, depending on what the user has chosen in the select-list.
Something like this:
​$(function(){
$("select[name='menu-168']").on("change", function (){
$("input[name='text-708']").toggle($(this).val() !== "Commercial");
});
});​
Working example
In this example I use attribute selectors to select your elements, because there is nothing more exact to go on, but you could get slightly better performance by adding ID's to the relevant elements and use those for the selectors instead.
$('#menu-168').on('change', function(){
($this).val() = "Commericial" ?
$('input[name='text-708']').show() : $('input[name='text-708']').hide();
}
})

Jquery checkboxes within containing table selector question

My current code:
<script type="text/javascript">
function checkAll(checked) {
$("input[type='checkbox']:not([disabled='disabled'])").attr('checked', checked);
}
</script>
<input type="checkbox" id="cbxSelectAll" onclick="checkAll(this.checked);" />
The short version:
How do I modify the function call and method above to check all checkboxes inside a table containing the checxbox form element.
The long version:
I am creating a WebUserControl containing a grid view in asp.net that is going to have a delete option. I would like the delete to be a series of checkboxes with one a box in the header to select all of them. What this amounts to for non ASP.NET people is a table with a header row that has a checkbox and every row also has a checxbox.
I have used the above code to check all boxes on the entire page. That won't work here though because I want to have multiple of these on the page at once each working independently. I know I could use a selector to select all the boxes if I ID'd the table but that would require some coding to name the table uniquely and then put that name in the script block.
Really what I would like is to modify the script above to check all checkboxes in the containing table of the "select all" box. The table containing the checkbox could be nested within others but I don't see any being nested within it, or if there are and the nested table also contains checxboxes I don't care if they also get selected.
Thanks for your help.
First, don't mix your HTML and your Javascript. Use event handler binding instead.
Second, use closest to get the nearest ancestor element of a particular type:
$(document).ready(function(){
$('#cbxSelectAll').click(function() {
$(this)
.closest('table') // get the parent table element
.find("input:checkbox:enabled") // find children that match the selector
.attr('checked', this.checked); // set their checked value
});
});
Change your inline attribute to this:
<input type="checkbox" id="cbxSelectAll" onclick="checkAll.call(this);" />
And your checkAll() to this:
function checkAll() {
$(this).closest('table').find("input:checkbox:enabled").attr('checked', this.checked);
}
Using .call(), it is called from the context of the element clicked.
Then the jQuery gets the closest()(docs) <table> and finds the inputs using the checkbox-selector(docs) and the enabled-selector(docs) .
Then when using the attr()(docs) method, you can use this.checked to set the checkboxes to the current state of the one checked.
You can find the table containing the select all using .closest
function checkAll(checked) {
var $table = $(this).closest('table');
$table.find("input[type='checkbox']:not([disabled='disabled'])")
.attr('checked', checked);
}
If there might be several nested tables it's often easiest to specify the one you want with a class, e.g. $(this).closest('table.tableOfCheckboxes'); where you add class tableOfCheckboxes to the table you want to find.

jQuery way to handle select lists, radio buttons and checkboxes

When I handle HTML form elements with jQuery, I always end up with an ugly mix of jQuery syntax and plain JavaScript like, e.g.:
function doStuff($combo){
if( $combo.get(0).options[$combo.get(0).selectedIndex].value=="" ){
var txt = "";
}else{
var txt = $combo.get(0).options[$combo.get(0).selectedIndex].text;
}
var $description = $combo.closest("div.item").find("input[name$=\[description\]]");
$description.val(txt);
}
Are there standard jQuery methods to handle typical operations on elements like <select>, <input type="radio"> and <input type="checkbox">?
With typical, I mean stuff like reading the value of the selected radio button in a group or replacing elements in a selection list. I haven't found them in the documentation but I admit that method overloading can make doc browser kind of tricky.
Update
Thanks everyone. Once in the right track, I figured out myself the rest of the stuff. E.g., I can handle a <select> list like any other DOM tree:
$("select")
.empty()
.append('<option value="">(Pick one)</option><option value="a">Option A</option><option value="b">Option B</option>');
Yes, you should be able to simplify your code a lot. Here are a few examples of working with form elements:
<input type="text">
$(':text') // select all text boxes
$('input#example').val(); // gets value of a text box
<input type="checkbox">
$(':checkbox') // selects all checkboxes
$('input.example:checked') // selects all ticked checkboxes with class 'example'
$('#example').is(':checked'); // true if checkbox with ID 'example' is ticked
<input type="radio">
$(':radio') // selects all radio buttons
$(':radio:checked').each( function() {
$(this).val(); // gets value of each selected radio button
});
$('input:radio[name="asdf"]'); // gets particular group of radio buttons
<select>
$('select#example').change( function() {
// this part runs every time the drop down is changed
$(this).val(); // gets the selected value
});
See also http://api.jquery.com/category/selectors/form-selectors/ for more selectors.
Since you want the text and not the value, use .text() for that <option> (find it using the :selected selector), like this:
function doStuff($combo){
var txt = $combo.children("option:selected").text();
$combo.closest("div.item").find("input[name$=\[description\]]").val(txt);
}
If you wanted the value part of <option value="4" selected>Four</option> then you could use .val(), like this:
var val = $combo.val();
For <select> elements, you should be able to just get the value (with .val()). For radio buttons, you can do this:
$('input:radio[name=whatever]:checked').val()
Checkboxes are similar:
$('#checkboxId:checked').val()
Those two will be null if things are unchecked (though with radio buttons it's kind-of evil for that to be the case).
edit see Nick's answer for getting the text of a selected option instead of the value (basically call .text() instead of .val()).
For selects you can use the val() method. In case of multiple select the val() method returns an array of the selected options.
For checkboxes and radio you can grab all the selected checkboxes using the :checked selector.
You'll find all the details as well as examples at the jQuery site : http://api.jquery.com/val/
For Select elements, you should be able to just get the value (with .val()). For radio buttons, you can do this:
$('input:radio[name=whatever]:checked').val()
Checkboxes are similar:
$('#checkboxId:checked').val()
Those two will be null if things are unchecked (though with radio buttons it's kind-of evil for that to be the case).
edit see Nick's answer for getting the text of a selected option instead of the value (basically call .text() instead of .val()).
Ignore formatting....i havent done that..;)

Categories

Resources