disable a CheckBox depending on dropdownlist - javascript

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!!!

Related

JS overides check in the checkbox on toggle [duplicate]

I'm using Jquery's toggle event to do some stuff when a user clicks a checkbox, like this:
$('input#myId').toggle(
function(){
//do stuff
},
function(){
//do other stuff
}
);
The problem is that the checkbox isn't being ticked when I click on the checkbox. (All the stuff I've put into the toggle event is working properly.)
I've tried the following:
$('input#myId').attr('checked', 'checked');
and
$(this).attr('checked', 'checked');
and even simply
return true;
But nothing is working. Can anyone tell me where I'm going wrong?
Edit - thanks to all who replied. Dreas' answer very nearly worked for me, except for the part that checked the attribute. This works perfectly (although it's a bit hacky)
$('input#myInput').change(function ()
{
if(!$(this).hasClass("checked"))
{
//do stuff if the checkbox isn't checked
$(this).addClass("checked");
return;
}
//do stuff if the checkbox isn't checked
$(this).removeClass('checked');
});
Thanks again to all who replied.
Use the change event instead of the toggle event, like such:
$('input#myId').change(function () {
if ($(this).attr("checked")) {
//do the stuff that you would do when 'checked'
return;
}
//Here do the stuff you want to do when 'unchecked'
});
While using the change event handler suggested by Dreas Grech is appropriate, it doesn't work well in IE 6 & 7, which doesn't fire the change event until the focus is blurred (that is, until you click outside the area of the checkbox). As QuirksMode say, "it's a serious bug".
You might want to use the click event handler, but that won't work with keyboard navigation. You need to register a keyup handler too...
See also this related question.
I haven't yet found a good cross-browser solution that supports both mouse clicks and keyboard activation of the checkboxes (and doesn't fire too many events).
Regarding your solution for checking whether the checkbox is checked or not, instead of adding your own checked class, you may use HTML's checked attribute:
$('input#myInput').change(function () {
if ($(this).attr("checked")) {
//do stuff if the checkbox is checked
} else {
//do stuff if the checkbox isn't checked
}
});
Any browser sets the checked attribute of an input element to the value "checked" if the checkbox is checked, and sets it to null (or deletes the attribute) if the checkbox is not checked.
why not using $.is() ?
$('input#myId').change(
function() {
if ($(this).is(':checked')) {
// do stuff here
} else {
// do other stuff here
}
});
This is an answer by MorningZ (I found it here) that makes totally sense:
The part you are missing is that "checkbox" is a jQuery object, not a
checkbox DOM object
so:
checkbox.checked sure would error because there is no .checked property of a jQuery
object
so:
checkbox[0].checked would work since the first item on a jQuery array is the DOM object
itself.
So in your change() function you can use
$(this)[0].checked
$('input#myId').toggle(
function(e){
e.preventDefault();
//do stuff
$(this).attr('checked', 'true');
},
function(e){
e.preventDefault();
//do other stuff
$(this).attr('checked', 'false');
}
);
this worked for me............ check it
$(":checkbox").click(function(){
if($(this).attr("id").split("chk_all")[1])
{
var ty = "sel"+$(this).attr("id").split("chk_all")[1]+"[]";
if($(this).attr("checked"))
{
$('input[name="'+ty+'"]').attr("checked", "checked");
}
else
{
$('input[name="'+ty+'"]').removeAttr("checked");
}
}
})
I did a similar approach but simply using the checked attribute such as
//toggles checkbox on/off
$("input:checkbox").change(
function(){
if(!this.checked){
this.checked=true;
}
else{
this.checked=false;
}
}
);
//end toggle
$("input[type=checkbox][checked=false]")// be shure to set to false on ready
$("input#Checkbox1").change(function() {
if ($(this).attr("checked")) {
$("#chk1").html("you just selected me")//the lable
} else {$("#chk1").html("you just un selected me") }
});
Try using a non-jquery function:
function chkboxToggle() {
if ($('input#chkbox').attr('checked'))
// do something
else
// do something else
}
then in your form:
<input id="chkbox" type="checkbox" onclick="chkboxToggle()" />
Try:
$(":checkbox").click(function(){
if($(this).attr("checked"))
{
$('input[name="name[]"]').attr("checked", "checked");
}
else
{
$('input[name="name[]"]').removeAttr("checked");
}
})

How to change button text based on user text input JQuery

I have a button and a JQuery autocomplete. I want to make it so that it works like this:
if(input=='') {
button.text = "hello";
}
else {
button.text = "world";
}
I dont know how to incorporate this in my script so that the button changes in real time depending on the state of the autocomplete input.
Any thoughts would be great. Thanks
You can just bind an event handler to the text field's keyup event like this:
$('#inputWrapper').on('keyup', '#tags', function() {
if($(this).val() == '') {
$('button.addButton').text('Hello');
} else {
$('button.addButton').text('World');
}
});
Here's an updated fiddle.

Script to disable select if option selected

How would you write a script to disable a select if you have two selects (both with ids) and an option in the first select is selected.
Since you have tagged the question with jQuery, I'll give you an idea of how to do it using jQuery:
$("#firstSelectId").change(function() {
var first = $(this);
$("#secondSelectId").prop("disabled", function() {
return first.val() === "whatever";
});
});
Note that the above assumes you want to enable the second select again if a different option was selected. Here's a working example.
How about:
$('#first').change(function() {
if ($(this).val() != '') { // '' is default value??
$('#second').attr('disabled', 'disabled');
} else {
$('#second').removeAttr('disabled');
}
});
use something like:
if($("#selectbox1 option:selected").val() == ...)
to see what was selected.
and then use
$("#selectbox2").attr('disabled', 'disabled');
to disable that other box.

jQuery - Clear form field with .change event

I am using the following jQuery code to switch div displays based on a change event tied to 3 radio buttons:
(function ($) {
Drupal.behaviors.change_form_fields = {
attach: function(context, settings) {
$('div.form-item-payment-method input').each(function() {
if (this.value != 'existing-bill') {
$('div#' + this.value).css('display', 'none');
}
});
$('div.form-item-payment-method input').change(function() {
show_class = this.value;
$('div.form-item-payment-method input').each(function() {
if (this.value != show_class) {
$('input#edit-' + this.value).val('');
$('div#' + this.value).css('display', 'none');
} else {
$('div#' + this.value).css('display', 'block');
}
});
});
}
}
}(jQuery));
This works fine and dandy, but I want to add some more to it.
If a user selects a radio button, I want to blank/clear out the form fields in the other groups. Like the onload (.each), they have divs around the display content.
I tried using .attr and .val, but the form fields would not clear when selecting another radio button. What am I missing? jQuery 1.4x+
val('') should do the trick, so there must be some other issue with either the selector, or the code not being run.
Use the radio buttons change event that should help you.
$("input[type=radio][name=groupname]").change(function(){
//Code the clear the form fields or other logic here.
});

jQuery checkbox click shows input field - doesn't work

I use a jQuery function to show certain hidden text fields once you select something from a select box.
This works fine for select boxes but I can't get it to work for a checkbox.
Here is the stripped code I tried (in a nutshell) but it's not working: http://jsbin.com/uwane3/2/
Thanks for your help, I rarely use JS so my knowledge is small.
I have found 2 errors in your code:
your Checkbox has no value so you cant get more than an empty result form ".val()"
you have not bind a eventhandler to the checkbox.
http://jsbin.com/uwane3/3
$('#cf3_field_9').live('click', function(e){
if (e.target == $('#cf3_field_9')[0] && e.target.checked) {
alert('The following line could only work if the checkbox have a value.');
$.viewMapcf3_field_9[$(this).val()].show();
} else {
$.each($.viewMapcf3_field_9, function() { this.hide(); });
}
});
You have no events registered to your checkbox.
Register a click, or change handler like this:
$('#cf3_field_9').click(function(){
if ($(this).attr("checked")) {
$.viewMapcf3_field_9[$(this).val()].show();
} else {
$.each($.viewMapcf3_field_9, function() { this.hide(); });
}
});
http://api.jquery.com/category/events/

Categories