I have a page with a set of checkbox's, that I want to run a Javascript function on when there is a change (I have done something very similar with dropdown's - and that worked)
However with the checkbox's I have three problems:
my onChange event only runs "sometimes" (you have to change the focus between the different checkbox controls
when it does run it is returning the result of the previous checkbox (not the one just clicked on)
the jQuery always return the value true
Checkbox creation
<%= Html.CheckBox("sl-" + row.Id, value, new { onChange = "SuitabilityChecked("+row.Id+", "+key+")"})%>
Javascript
function SuitabilityChecked(providerId, parentRecordId) {
var params = {};
params.providerId = providerId;
params.parentRecordId = parentRecordId;
var value = $("#sl-" + providerId).val();
params.value = value;
$.getJSON("SuitabilityChecked", params, null);
};
Browsers are funny about radio buttons and check boxes and can delay the onchange until focus change. Try adding an onclick event to blur or call the change event directly.
Maybe something like this using jQuery Live (untested, off the top of my head):
$(':checkbox').live('click', function() { $(this).change(); });
What's happening:
Checkbox A clicked
Checkbox B clicked
Checkbox A has lost focus and fires onChange
Which makes it seem as if Checkbox B is returning the result of Checkbox A. If you were to press Tab after clicking Checkbox B in this scenario, you'd notice that its onChange would fire.
Related
I'm confused on how JavaScript handles Change Events and am looking for some insight.
Let's say we have two HTML controls; a Checkbox and a Button and I want to use JS to display a message that says how many times the Checkbox has changed from checked to not-checked.
<input type="checkbox" id="cb" />
<button id="btn">Change Checkbox</button>
<div id="msg"></div>
The JS can look something like this:
var count = 0;
var cb = document.getElementById("cb");
var btn = document.getElementById("btn");
var msg = document.getElementById("msg");
cb.addEventListener("change", cb_onChange);
btn.addEventListener("click", btn_onClick);
// Change the state of the Checkbox when user clicks the Button
function btn_onClick() {
cb.checked = !cb.checked;
}
// The state of the Checkbox has changed, so increment the change count and display it
function cb_onChange() {
msg.innerHTML = "Checkbox changed " + count+++" times";
}
Test it out here http://jsfiddle.net/26RWh/
Notice that the OnChange event of the Checkbox is NOT dispatched when the Checkbox is programmatically set at cb.checked = !cb.checked. - i.e. The cb_onChange listener is only executed if/when the user manually clicks the Checkbox.
How come the OnChange event isn't fired when I change the state in code?
This is the way events on input-elements work in javascript.
If you want the callback to be executet you need to manually fire the change-event on the checkbox.
There are questions about this:
do it in pure JavaScript
and with help of jquery
when the browser identifies a change event in checkbox, it sets the checked propery to !checked and calls the subscribed functions which you can assume happens in one function(f1) and which is called when the event occurs. In this case you are not calling the function f1 but just setting the property.
I have a click event handler attached to a group of radio inputs, and want to see if I am clicking on the radio button that is already selected (has property 'checked' set). I figured the event handler would act in a daisy chained fashion (first calling my event handler on the click and then continuing down the chain to the default behavior of the click). Apparently this is not the case, because when I evaluate if the property 'checked' is true on the radio button I just clicked, it always returns true in my click event handler.
The click has already been processed by the default behavior and has already applied the 'checked' property to the radio button I just clicked. Again, I figured my click event handler would be processed prior to that default behavior. What's even more odd is that even when I prevent the default behavior, it still returns true for the 'checked' property. I assume this is because the 'checked' property is being processed by the 'change' event, so preventing the default behavior on my click event handler is not affecting anything.
$("input[type='radio']").click(function(e) {
e.preventDefault();
alert($(this).prop("checked")); // always returns true; i want prop value immediately prior to click
});
How can I achieve what I'm after? That is, to see whether or not the radio button that was just clicked on was the one already checked. Thanks.
Based on the response of #Jeffman , I was able to get something to work for what I needed to do. I have custom buttons, only one of which can be selected (hence the use of radio buttons). However, if you click on the one that's already selected, it should deselect and select the default value instead.
Things I had to do. Handle mousedown events on the radio labels. If I am clicking on the already selected radio, set the default button to be 'checked'. Else I just select the button that has been clicked on. I had to disable the 'click' event on these buttons, as that would override my irregular handling of the radio buttons (for some reason the selection would snap back to the one that was clicked when I overrode it and chose the default one manually). This also meant I would need to manually trigger the change event, as I do the custom radio button styling there.
$(".radios > label").mousedown(function(e) {
var l = $(this); // label
var t = l.parent(); // container for radio group
var i = l.find("input"); // input element of this label
if(i.prop("checked")) { // clicking on the already selected button
t.find(".default_radio input").prop("checked", true).trigger("change");
} else {
i.prop("checked", true).trigger("change");
}
}).bind('click',false);
$("input[type='radio']").change(function(e) {
// style the buttons here
});
Save radio status before click via mousedown
var was_checked;
$( "#radio" ).mousedown(function() {
was_checked = $(this)[0].checked;
});
$( "#radio" ).click(function() {
$(this).attr('checked', !was_checked);
});
i think you should also return false. not only preventDefault
Here is a sample code that would do the trick
<script>
$(function() {
var radios = {};
$("input[type='radio']").each(function() {
radios[$(this).uniqueId().attr('id')] = false;
});
function resetRadioState() {
$("input[type='radio']").each(function() {
radios[$(this).attr('id')] = $(this).is(':checked');
});
}
resetRadioState();
$("input[type='radio']").click(function(e) {
alert(radios[$(this).attr('id')]);
resetRadioState();
});
})
</script>
<input type="radio" name="group[]"/>
<input type="radio" name="group[]" checked/>
I used this code to change the class of an html-element when an onclick-event occurs. The change occurs(i.e. the text color changes) but the change is not stable, it goes back to the styling of its previous class, and my javascript code doesn't seem to have any effect.
function submitrequest(){
var x = document.forms["signupform"]["name"].value;
if(x.toString().length <= 0){
var y = document.getElementById("nametd");
y.className = 'change';
}
}
What should I do to make this effect permanent?
You do not have to define a click-handler to notice that a button of a form was clicked.
A form can have an submit-button:
and when this button is clicked an submit event is fired for the form.
Furthermore when an user do not clicks on the button and just presses enter then a submit-event is fired too. So you handle both situations automatically.
I suggest that you define you function that way:
window.onload = function(){
document.getElementById('signupform').addEventListener('submit',function(e){
changeClassOfNametd();
e.preventDefault(); // this prevents the side from being reloaded by the script.
});
};
function changeClassOfNametd(){
var nameValue = document.forms["signupform"]["name"].value;
if(nameValue){ // when value is "" (zero, no signs) it is false anyway
var y = document.getElementById("nametd");
y.className = 'change';
//y.classList.toggle('change'); you can toggle classname "change" too
// which works that way class="unchange" -> class="unchange change"
// you have to define appropriate css-classes for toggle.
}
}
The Code above works whereever you put it into your html-file.
By the name of the function it is called on a form submission.
Because the form submits and it goes back to the original that was set when the new page loads.
If you want to maintain that, you would have to apply the class on the next page load. Most developers will do that with the serverside. If you do not actually want the form to submit, cancel it.
I have a javascript function that sets a variable everytime a checkbox is clicked:
function handleClick(cb) {
alert('entered function');
setTimeout(function () {
if (cb.checked ) {
$("#IsChecked").val('true');
}
else
$("#IsChecked").val('false');
alert('now my value is: '+ $("#IsChecked").val());
}, 0);
}
Heres my checkbox:
<input id="MyCheckBox" type="checkbox" value="true" onclick="handleClick(this);"
name="MyCheckBox" checked="checked">
This works great everytime the checkbox is checked. But now i need to know if the checkbox is checked when the user clicks a button and has never touched the checkbox before. So i do this:
$(document).ready(function () {
$("#IsChecked").val('default');
$('#btnCheck').click(function (e) {
var isComplete = $("#IsChecked").val();
if (isComplete == 'default') {
var cb = $('#MyCheckBox');
handleClick(cb);
alert('after handleClick ischecked is: ' + $("#IsChecked").val());
}
});
});
When i click my button and the checkbox is checked by default, i get these alerts in this order:
entered function
after handleClick ischecked is: default
now my value is: false
If i check the checkbox to toggle it, i get these alerts as expected:
entered function
now my value is: false
In my handleClick event, the setTimeout is there because of IE so i cant get rid of it. How can i check to see if a checkbox is checked without having to click the checkbox itself? Thanks
How can i check to see if a checkbox is checked without having to click the checkbox itself?
$('#MyCheckBox').prop('checked') will tell you anytime whether the checkbox is checked or not.
However if you not only want to test its status, but also execute your handleClick function, then note that the function expects a DOM element, not a jQuery object as argument.
If you pass a jQuery object to your function, then cb.checked will always evaluate to false, since jQuery objects don't have a checked property (only DOM elements have).
You'd have to change your function call to:
handleClick(cb.get(0));
to extract the DOM element from the jQuery object.
How can i check to see if a checkbox is checked without having to click
You can find out if checkbox is checked in javascript with click event by using val() method
$("#MyCheckBox").is(':checked')
If you want to check that checkbox is checked from the button click event.
$("#IsChecked").is(':checked'); //returns boolean
Im trying to call a function when the value of any form value changes.
This is my code:
function reload()
{
tmp = findSWF("chart");
x = tmp.reload("chart.php", false);
}
function findSWF(movieName) {
if (navigator.appName.indexOf("Microsoft")!= -1) {
return window["ie_" + movieName];
} else {
return document[movieName];
}
}
$(".formclass").change(function() {
reload();
});
If i make a link with an onclick action, it works, but using the last .change action, nothing happens.
Ideally, i could also pass the name and value of what has changed to that url
the change event only kicks in when you changed the value AND the control loses focus for text controls:
The change event is sent to an element
when its value changes. This event is
limited to elements,
boxes and
elements. For select boxes,
checkboxes, and radio buttons, the
event is fired immediately when the
user makes a selection with the mouse,
but for the other element types the
event is deferred until the element
loses focus.
if you want to trigger the function as the user types in the control, try keydown() or keypress()