Improving use of radio buttons to enable/disable form fields - javascript

I have two radio buttons, and two corresponding form fields. Depending on which radio button is selected, one form field gets disabled and the other gets enabled.
My code works, but I think it can be improved. Right now I have two separate processes. One checks to see which radio button is selected when the page loads and disables the appropriate field. The other responds to changes by the user after the page has loaded. I believe it can be simplified but I don't know how.
$(document).ready(function() {
if ($("#element_link_link_type_internal").is(':checked')) {
$("#element_link_url").attr("disabled","disabled");
} else {
$("#element_link_page_id").attr("disabled","disabled");
}
});
$(document).ready(function() {
$("#element_link_link_type_internal").click(function(){
$("#element_link_page_id").attr("disabled","");
$("#element_link_url").attr("disabled","disabled");
}),
$("#element_link_link_type_external").click(function(){
$("#element_link_page_id").attr("disabled","disabled");
$("#element_link_url").attr("disabled","");
});
});
Thanks!

You can test the checked state within the onchange handler, and simply invoke the onchange handler (which I believe you should be using instead of onclick) once when the page loads:
$(document).ready(function() {
$("#element_link_link_type_internal").change(function() {
$("#element_link_page_id").attr("disabled", !this.checked);
$("#element_link_url").attr("disabled", this.checked);
}).change(); // invoke once to set up initial state
});

This is untested and based on your comments/answer:
jQuery < 1.6:
$(document).ready(function() {
var $type = $('input[name="element_link[link_type]"]'),
$pageId = $("#element_link_page_id"),
$url = $("#element_link_url");
$type.change(function() {
if ($type.filter(":checked").val() === "internal") {
$pageId.removeAttr("disabled");
$url.attr("disabled", "disabled");
} else {
$url.removeAttr("disabled");
$pageId.attr("disabled", "disabled");
}
}).change();
});
jQuery >= 1.6
$(document).ready(function() {
var $type = $('input[name="element_link[link_type]"]'),
$pageId = $("#element_link_page_id"),
$url = $("#element_link_url");
$type.change(function() {
var isDisabled = ($type.filter(":checked").val() === "internal");
$pageId.prop("disabled", !isDisabled);
$url.prop("disabled", isDisabled);
}).change();
});

#karim79, your answer got me started but it didn't work when the 2nd radio button was selected. It only worked when the 1st radio button was selected.
I came up with this, and it seems to do the trick. I'd welcome anyone to offer additional improvements though. JavaScript blows my mind.
$(document).ready(function() {
$("input[name='element_link[link_type]']").change(function() {
var v = $("input[name='element_link[link_type]']:checked").val()
$("#element_link_page_id").attr("disabled", v == 'internal' ? "" : "disabled");
$("#element_link_url").attr("disabled", v == 'internal' ? "disabled" : "" );
}).change(); // invoke once to set up initial state
});

Related

Uncheck a Checkbox using Jquery

I have a page with a list of check boxes, when a check box is checked I am updating the number of check boxes selected in side a p tag. This is all working.
The problem I have is when the user selects more than 5 checkboxes I want to use Jquery to unselect it.
This is what I have so far, the first if else works but the first part of the if doe
$("input").click(function () {
if ($("input:checked").size() > 5) {
this.attr('checked', false) // Unchecks it
}
else {
$("#numberOfSelectedOptions").html("Selected: " + $("input:checked").size());
}
});
Any ideas?
Firstly you should use the change event when dealing with checkboxes so that it caters for users who navigate via the keyboard only. Secondly, if the number of selected checkboxes is already 5 or greater you can stop the selection of the current checkbox by using preventDefault(). Try this:
$("input").change(function (e) {
var $inputs = $('input:checked');
if ($inputs.length > 5 && this.checked) {
this.checked = false;
e.preventDefault();
} else {
$("#numberOfSelectedOptions").html("Selected: " + $inputs.length);
}
});
Example fiddle
Note I restricted the fiddle to 2 selections so that it's easier to test.
You need this $(this).prop('checked', false);
You should be saying
$(this).attr('checked', false)
instead of
this.attr('checked', false)
You need this $(this).prop('checked', false);
Also this is a javascript object, if you want to use jquery you should prefer $(this).

Fixing toggle all behavior in checkbox element

I'm trying to toggle all checkboxes on a table and my code works but has a few issues and I don't find how to get ride of them. So here is the code:
$(function () {
$('#toggleCheckbox').on('click', function () {
var $toggle = $(this).is(':checked');
$("#codigoArancelarioBody").find("input:checkbox").click();
});
});
Take a look at this Fiddle I setup for testing and do this tests:
Mark the first checkbox (the one at table heading level) the rest of them inside #codigoArancelarioBody get checked and this is right
Mark first the checkbox at the first row (the only at table body level) and then mark the toggleAll you will see how things goes wrong since if I check the toggleAll them all should remain checked and that's the wrong part on my code
How I can fix this? Also I'll like to add a class 'removedAlert' to those TR I mark, how?
You need two click event handlers, one for the check/uncheck all box and one for the other ones
JS
$('#toggleCheckbox').on('click', function () {
var $toggle = $(this).is(':checked');
$("#codigoArancelarioBody").find("input:checkbox").prop("checked", $toggle);
});
$("#codigoArancelarioBody input:checkbox").on('click', function () {
if (!$(this).is(':checked')) {
$('#toggleCheckbox').prop("checked", false);
} else if ($("#codigoArancelarioBody input:checkbox").length == $("#codigoArancelarioBody input:checkbox:checked").length) {
$('#toggleCheckbox').prop("checked", true);
}
});
DEMO
since the same code will be applied in a lot of places on my code and
to avoid DRY, I'll like to pass the selector as a parameter in all
your code solution could you edit your post to achieve this?
$toggleCheckBox = $('#toggleCheckbox');
$checkBoxTbody = $("#codigoArancelarioBody");
$toggleCheckBox.on('click', function () {
var $toggle = $(this).is(':checked');
$checkBoxTbody.find("input:checkbox").prop("checked", $toggle);
});
$checkBoxTbody.find("input:checkbox").on('click', function () {
if (!$(this).is(':checked')) {
$toggleCheckBox.prop("checked", false);
} else if ($checkBoxTbody.find("input:checkbox").length == $checkBoxTbody.find("input:checkbox:checked").length) {
$toggleCheckBox.prop("checked", true);
}
});
DEMO
If you don't need the "click" event for something else you can do this:
$(function () {
$('#toggleCheckbox').on('change', function () {
var toggle = $(this).is(':checked');
$("#codigoArancelarioBody").find("input:checkbox").prop('checked', toggle ).closest('tr').addClass('removedAlert');
});
});
The code is actually executing what you told it to do, i.e. every time I click the checkbox on top click to other checkboxes. This way if a box is checked it will uncheck itself, because it won't mind if the top is checked or not.
What you really want is "when I check the box on top, check all the others, when I uncheck it, then uncheck all the others", which is sort of different as you see.
Try this:
$(function () {
// best practice: always store the selectors you access multiple times
var checkboxes = $("#codigoArancelarioBody").find("input:checkbox"),
toggleAll = $('#toggleCheckbox');
toggleAll.on('click', function () {
// is the top checkbox checked? return true, is it unchecked? Then return false.
var $toggle = $(this).is(':checked');
// .prop('checked', true) makes it checked, .prop('checked', false) makes it unchecked
checkboxes.prop('checked', $toggle);
});
});
see: http://jsfiddle.net/gleezer/nnfg80x1/3/

Related dropdown menu issue

I'm polishing up a bit of jquery I wrote that works on 2 dropdown boxes. Basically, when the first dropdown is changed, it filters the second dropdown to show only the applicable choices. If the first choice (value: "none|") is chosen in the first dropdown, it shows no choices in the second
It works great, most of the time. Here's the issue: If you select the first choice in the first dropdown, the second dropdown clears out. But if you then choose another option in the first dropdown, the second stays empty when it shouldn't.
I'd appreciate if you can help me figure this out. You can find the dropdown boxes here: http://goinspire.com/jwrp-hotel-registration/.
PS: If it makes a difference (but I think it doesn't), it's a WordPress site and the form is generated by GravityForms.
PS: here's the code:
tripFilter = function () {
var tripClass = '.hotel-trip select',
hotelClass = '.hotel-name select',
unusedClass = '.unused-options select';
jQuery(tripClass).change(function(){
//testFunc();
var tripSelect = jQuery(tripClass),
trip = tripSelect.val(),
hotelSelect = tripSelect.parents('form').find(hotelClass);
if (trip === "none|"){
jQuery(hotelClass+" > option").each(function() {
jQuery(this).clone().appendTo(unusedClass);
jQuery(this).remove();
});
} else {
tripnum = trip.match(/JWRP (\d*)/)[1];
//var hotelChoices = [];
jQuery(unusedClass+" > option").each(function() {
jQuery(this).clone().appendTo(hotelClass);
jQuery(this).remove();
});
jQuery(hotelClass+" > option").each(function() {
hotelMatch = jQuery(this).val().match(/(\d*) /);
//console.log(hotelMatch);
if (hotelMatch === null || hotelMatch[1] != tripnum){
jQuery(this).clone().appendTo(unusedClass);
jQuery(this).remove();
//console.log("not a match!");
};
});
}
});
};
jQuery(document).ready(function () {
tripFilter();
});
jQuery(document).bind('gform_post_render', function(event, form_id){
if(form_id == 38) {
tripFilter();
}
});
If I have understood properly, first dropdowm guides second.
So, I think you might just add a listener on "change" event of first dropdown, to perform your function every time the value of first input goes through some change.
Try this way:
$(document).ready(function(){
$('#38').bind('change', tripFilter)
});

Toggle Show and Enable Textfiled When Certain Radio Button is Selected

I would like to be able to have an input field (initially hidden and disabled) to be shown and enabled every time the "Other" radio button is selected, and ofcoure to be hidden and disabled when a different radio button is selected . I have gotten this script to show and hide the textfield appropriately, but Id like to know how I can get enabling and disabling to happen with it
$('input[name="x_description"]').bind('change',function(){
var showOrHide = ($(this).val() == "Other") ? true : false;
$('#other_program_text').toggle(showOrHide);
});
I know that this is how to show the field and enable the textfield, but cant figure out how to put it all together,
$(this).show().prop('disabled', false);
Thanks in advance,
Dan
$('input[name="x_description"]').bind('change',function(){
if ( showOrHide == true ) {
$('#other_program_text').show().prop('disabled',false);
} else if ( showOrHide == false ) {
$('#other_program_text').hide().prop('disabled',true);
}
});
You want to use the $(this).attr() function to set properties on an HTML element. With one parameter it'll read the passed param, with two it'll set it.
Like $(this).attr("enabled", true)
You can use "click" method
$('input[name="x_description"]').click(function() {
if($('#radio_button').is(':checked')) {
alert("it's checked"); //do your stuff
}
});
If your content are dynamically generated then use "live" method
$('input[name="x_description"]').live('click',function() {
if($('#radio_button').is(':checked')) {
alert("it's checked"); //do your stuff
}
});

disable a CheckBox depending on dropdownlist

I'm working on a asp.net mvc3 application with DropDownLists and CheckBoxes and so on.
I wrote a javascript to disable a CheckBox if a defined option of a dropdownlist is selected:
$(function() {
$('#dropdownlistId').change(function() {
if (this.value == '1st option') {
$('#checkboxId').attr('disabled', disabled);
} else {
$('#checkboxId').removeAttr('disabled', disabled);
}
});
});
this works fine, but the script reacts only on a change of the dropdownlist
so if '1st option' is on the top of the dropdownlist and so automatically selected as default, the script doesn't disable the checkbox. Only if the user select another option and select '1st option' once again...
Please help me :)
PS: the script also doesn't work if I use my keyboard to switch the dropdownlist options instead of my mouse
So it would be very kind if you could help my to improve the script, because I really can't do javascript :/
$(function() {
var $cb = $('#checkboxId');
$('#dropdownlistId').change(function() {
if (this.value == '1st option') {
$cb.prop('disabled', true);
} else {
$cb.prop('disabled', false);
}
}).trigger('change');
});
The difference in triggering change event after adding halnderl. About your second question - Using keyboard the 'change' event will be triggered when select will lose focus ('blur').
You could do something like this:
function setCheckBox() {
if (this.value == '1st option') {
$('#checkboxId').attr('disabled', disabled);
} else {
$('#checkboxId').removeAttr('disabled', disabled);
}
}
$(function() {
setCheckBox();//do this on load..
$('#dropdownlistId').change(function() {
setCheckBox();//and on change
});
});
When you define your CheckBox control, use disabled attribute to disable it by default. That way it will be disabled already and there is no need to add more javascript to disable it from the get go.
It would look something like this:
#Html.CheckBoxFor(model => model.IsCheckBox, new { #disabled = "true" })
$(function() {
var $cb = $('#checkboxId');
$('#dropdownlistId').change(function() {
if (this.value == '1st option') {
$cb.attr('disabled', disabled);
} else {
$cb.removeAttr('disabled', disabled);
}
}).trigger('change');
});
works like a charm now
thank you guys
Your code seems to be little incorrect depends on your need because your calling the disable function on change of that dropdown list you need to write it in document.ready like this
$(document).ready(function () {if(document.getElementById("dropdownlistId").value="1stoption")
{
document.getElementById('checkboxId').style.visibility = 'hidden';
}
else
{//do something whatever you wish here in else condition
}
}
Hope it helps!!!

Categories