Remove Div Attribute when radio button is selected - javascript

I'm very new to JavaScript, not really sure what I'm doing. I found some useful code that removes/inserts a Div's attributes when a certain value is selected from a dropdown list. I'd like to modify this code so that the attribute is altered when a radio button is selected.
Here is the code I have at the moment:
function pageLoad(sender, args) {
if (args.get_isPartialLoad()) {
var rangeType = $('#<%= DateRangeList.ClientID%>').val();
if (rangeType == 6) {
$('#DatePeriodRow').removeAttr("style");
}
else {
$('#DatePeriodRow').attr("style", "display: none;");
}
}
}
$(document).ready(function () {
$('#<%= DateRangeList.ClientID %>').live("change", function() {
var rangeType = $('#<%= DateRangeList.ClientID %>').val();
if (rangeType == 6) {
$('#DatePeriodRow').removeAttr("style");
}
else {
$('#DatePeriodRow').attr("style", "display: none;");
}
});
})
I've been trying various ways of rebuilding this code to suit my needs but no luck thus far. I've also done quite a bit of Googling to no avail. I often receive the "Propery/Value is null or undefined" message, and I'm not to sure how to go about debugging the java side of things.
Any and all help would be greatly appreciated!

If you're trying to show hide and element, Raki's answer will do. You could also express it this way:
$('#DatePeriodRow').hide(); // Hide Div
$('#DatePeriodRow').show(); // Show Div
First things first though, if your Property/Value is undefined or null you probably have a problem with your selectors. I.e. the following line:
$('#<%= DateRangeList.ClientID %>')
The <%= ... %> looks like ASP, if this is intended to be run inside that environment perhaps that code is not evaluating correctly which is giving you the wrong jQuery selector.
One More Thing
Check which version of jQuery you're using, .live() is deprecated, newer versions use .on

instead of using $('#DatePeriodRow').removeAttr("style"); use
$('#DatePeriodRow').css("display", "none"); in order to hide div and
$('#DatePeriodRow').css("display", "block"); to display div

ASP Radio-button list is rendered as a table which contains html inputs with type "radio". So you need to add "input" to selector. The code below assigns handler to each radio-button when document is loaded and also checks if one of the buttons has been checked already. If it was - it fires "change" event to trigger the handler. Hope it helps.
$(document).ready(function ()
{
$('#<%=DateRangeList.ClientID%> input').bind("change",
function ()
{
if ($(this).val() == "6") {
$("#DatePeriodRow").show();
}
else {
$("#DatePeriodRow").hide();
}
});
var checkedButton = $('#<%=DateRangeList.ClientID%> input[checked]').first();
if (checkedButton.val())
{
checkedButton.trigger("change");
}
});

Related

JQuery select elements in <span> that doesn't exist initially

I've been looking for so long and found several answers that suggest using .on() as in $('.idOfMyElemenet').on() works even for elements that don't exist yet. But this doesn't seem to be finding the element. Am I doing something wrong?
The highest level <span> (in screenshot) does not exist until I click on a drop-down. Ultimately I'm trying to trigger an event when the user clicks on any of the <li> (aka selects an option from the drop-down).
$(document).ready(function () {
var test = "#select2-id_customer-results";
$(test).on("click", function() {
console.log('hello')
})
})
EDIT:
Thanks to Drew Baker - I think his second solution is the way to go. But not quite there yet...
From the select2 documentation
All public events are relayed using the jQuery event system, and they
are triggered on the <select> element that Select2 is attached to.
So I tried listening to it via the id (which doesn't seem to exist but would probably be id_customer) and the class. The class I added below did not work. Is there a way to listen to this using Jquery?
$(document).ready(function () {
// console.log($('#id_customer'));
$('.modelselect2 form-control select2-hidden-accessible').on('select2:select', function (e) {
var data = e.params.data;
console.log(data);
});
});
I'll answer your question, but then give you a better solution.
First, you need to make sure the thing you are attaching .on() to actually exists. I typically use a containing DIV or failing that body or html will work.
Secondly you are missing a parameter that tells jQuery the thing you are looking to watch to be clicked on. In this case, I'm assuming it is the UL tag with the ID you provided.
This should do what you want:
$(document).ready(function () {
$('body').on("click", "#select2-id_customer-results", function() {
console.log('hello')
})
})
But a better solution would be to use the Select2 API to have it tell you when something is selected. This will be way more reliable and should make your code work after upgrades to Select2.
Something like this:
$('select[name="customer"]').on('select2:select', function (e) {
var data = e.params.data;
console.log(data);
});
NOTE: #mySelect2 is probably not what you have. Use whatever ID you used to initialize Select2 in jQuery.
You can read more about that API here: https://select2.org/programmatic-control/events
if your element is dynamically generated and you want to target that specific element. You need to specify a static container/parent element to indicate where it belongs.
Try this:
$( '#dynamicallyAddedElement' ).on( 'click', '#wrapper', function () { ... });
//where #wrapper is a static parent element in which you add the dynamic links.
So, you have a wrapper which is hard-coded into the HTML source code:
PS. Hope I helped in some way.
If you need to trigger an event when click on <li> elements, you have to use that elements id or class as the selector. Check the below code:
$(document).ready(function () {
var test = ".select2-results__option";
$(test).on("click", function() {
console.log('hello')
})
})
It turns out this is an old bug in django-auto-complete.
The code below works. I have no idea why but now I can move on.
Note: the 'name' is the value of the select2 select element (see screenshot at bottom)
document.querySelector('select[name="customer"]').onchange=function() {
console.log("myselect2name changed");
};

Checkbox and click event handling

I'm trying to set a textbox to 'readonly', add a class, and put a text into the textbox at that moment when I check the checkbox. Moreover, I'm also trying to remove 'readonly' attribute from the textbox, add a class, and delete text in the textbox.
I have
$('#CheckBoxSectionCode').click(function () {
if ($(this).is(':checked')) {
$('#TextBoxSectionCode').attr('readonly', 'readonly');
$('#TextBoxSectionCode').addClass('disabled');
$('#TextBoxSectionCode').text(document.getElementById('TextBoxSectionName').val);
}
else {
$('#TextBoxSectionCode').attr('readonly', false);
$('#TextBoxSectionCode').addClass('abled');
$('#TextBoxSectionCode').text('');
}
});
This code doesn't work for me.
Thanks,
Phillip
Thanks everyone for answers.
According to your comments and answers, I've changed my code but it's still not working.
$('#CheckBoxSectionCode').click(function () {
if ($(this).is(':checked')) {
$('#TextBoxSectionCode').prop('readonly', true);
$('#TextBoxSectionCode').addClass('disabled');
$('#TextBoxSectionCode').text('disabled');
}
else {
$('#TextBoxSectionCode').prop('readonly', false);
$('#TextBoxSectionCode').removeClass('disabled').addClass('enabled');
$('#TextBoxSectionCode').text('');
}
});
I'm using chrome browser to run this code, and using developer tools in chrome and put a break point at the code above to see what's happening in the jquery. However, when I click the check box to check/uncheck, nothing happens there.
document.getElementById('TextBoxSectionName').val this is wrong. You really should cache your jQuery object so it's not navigating the DOM over and over. Then you mix in native JS and .val is not a DOM property or method, nor is it a jQuery property, it should be .value for a DOM object or .val() for a jQuery object.
Obligatory explanation by #Archy Wilhes:
"Just to clarify; when #SterlingArcher says caching the jQuery object,
she/he means doing something like var obj = $('#TextBoxSectionCode')
then calling the functions using the variable like this:
obj.attr(...); obj.addClass(...). Every time you do a $(something) you
are calling a function in jQuery that looks for the DOM."
since everytime you are adding the class the element is going to end up having both the two classes. Consider removing the other class before adding one. For example,
$(selector).removeClass('disabled').addClass('enabled')
Try with change event instead of click:
$('#CheckBoxSectionCode').change(function () {
if ($(this).is(':checked')) {
$('#TextBoxSectionCode').attr('readonly', 'readonly');
$('#TextBoxSectionCode').addClass('disabled');
$('#TextBoxSectionCode').text(document.getElementById('TextBoxSectionName').val);
}
else {
$('#TextBoxSectionCode').attr('readonly', false);
$('#TextBoxSectionCode').addClass('abled');
$('#TextBoxSectionCode').text('');
}
});
You could do the following way.
//Cache reference to DOM as DOM scan is expensive!
var textBox = $('#TextBoxSectionCode');
$('#CheckBoxSectionCode').click(function () {
//Use prop as opposed to attr
textBox.prop("readOnly", false).removeClass('disabled').addClass('abled').text("");
if ($(this).is(':checked')) {
textBox.prop("readOnly", true).removeClass('abled').addClass('disabled').text($("#TextBoxSectionName").val());
}
});

Hide / Display div based on checkbox click. Works in jsFiddle, but won't on my site. Any ideas?

Hide / Display div based on checkbox click. Works in jsFiddle, but won't on my site. Any ideas?
What I'm looking to do is have multiple payment methods (CC, Paypal, etc, etc.) and based on the one you've checked, I'll display the relevant payment information for that method.
Here is the relevant jsFiddle link:
http://jsfiddle.net/mxRCz/88/
My JS is:
$('#CCMethod').change(function(){
if (this.checked) {
$('#CCPay').fadeIn('slow');
} else {
$('#CCPay').fadeOut('slow');
}
});
My site staging area is at: https://rsatestamls.kaliocommerce.com:444/checkout.aspx
It's because your script
$('#CCMethod').change(function(){
if ($(this).is(':checked')) {
$('#CCPay').fadeIn('slow');
} else {
$('#CCPay').fadeOut('slow');
}
});
is running before #CCMethod is declared. Wrap it in a doc-ready:
$(function() {
('#CCMethod').change(function(){
if ($(this).is(':checked')) {
$('#CCPay').fadeIn('slow');
} else {
$('#CCPay').fadeOut('slow');
}
});
});
I'd recommend to use click event instead of change, change is buggy in old IE (jQuery probably handles this bug, but it's kinda good practice anyway). So try if click works for you.
If you don't care about IE<9, take a look at :checked pseudoselector. This option doesn't require javascript. Take a look here: http://jsfiddle.net/y9cQD/ (show/hide animation could be added via transition)
P.S. just noticed answer from J Torres - could be the cause.
Change the line:
if (this.checked) {
for this:
if ($(this).is(':checked')) {
To check if a checkbox is checked, you must use the ':checked' jQuery selector.

jqGrid checkbox events

I have a jqGrid it has a checkbox in the rows. I need to be able to change the value depending of if it is being checked or unchecked. Using this in the $(document).ready block does not work. I have tried multiple solutions that I have found on the forum and nothing seems to work. Any suggestions?
$('#glReportCodesGrid').children("input:checkbox").click(function () {
var y = $(this).val();
if (y == 'false') {
$(this).val('true');
}
else { $(this).val('false'); }
});
You need to use the following selector to find the checkboxes:
jQuery(".jqgrow td input", "#glReportCodesGrid").click(function () {
You would need to call the above from one of the grid events that is triggered after the grid is initialized.
Alternatively, you can use jQuery.delegate to dynamically bind the event handler when the elements are created:
jQuery(document).delegate(
'#glReportCodesGrid .jqgrow td input',
'click',
function () { ... });
The question jqgrid-with-an-editable-checkbox-column has some related information that you may find helpful.

How to detect changes for the inner elements of an ASP.NET AJAX control?

Within a custom ASP.NET AJAX control, I'm trying to get all of the inner inputs of the element that represents the container, and detect their changes.
The following works only in IE 9 and FF:
if (this.get_watchChanges()) {
$(this.get_element()).find(":input").change(function() {
//mark dirty
});
}
Looking for input elements with the type of text and checkbox is not working for me at all.
What's a good cross-browser way to detect a change for inner elements of a parent element?
I realize this is quite old, just stumbled on it and thought I'd through something up for the next guy. Would something like this work?
<script type="text/javascript">
var isDirty = false;
$(document).ready(function() {
isDirty = false;
$("input, input[#type=checkbox]").change(function() {
isDirty = true;
});
});
</script>
I ended up adding something targeting the various types of controls (since I was using Telerik). I can't post the result, but I ended up doing something like:
$(".RadDatePicker").each(function() { /* attach to date change event */ });
And so on for each control (targeting them by their CSS class. The complexity came because of the ASP.NET AJAX framework, and how the JavaScript APIs worked.

Categories