Checking the checked status of a checkbox upon its click - javascript

I am trying to test the status of a checkbox upon its click.
My problem is that it always reports as true as it reports the status after the change event has taken place and not before.
Is there anyway I can test before the change.
Current code using jQuery - the checkboxes all of class 'package':
$(".package").click(function(){
if($(this).is(":checked")){
alert($(this).attr("checked"));
}
});
This always returns true even if selecting a checkbox that is not currently checked.
EDIT : Ok seems there was some old js interfering with the process, after cleaning that up the click function did indeed work. Thanks all.

Using the onchange event on a checkbox is not cross-browser (hello IE! And yes, even with jQuery).
The following works:
$('.package').click(function() {
console.log(this.checked) // There is no need for jQuery here
})
Logs 'true' when you check the checkbox, and 'false' when you uncheck it.
And seriously, using $(this).attr('checked') or $(this).is(':checked') is just jQueryception for nothing.

You can use the change event instead, this way you are sure the previous checked state is always the oposite of what you read now
$(".package").change(function() {
alert($(this).attr("checked"));
});

The click event fires before the actual textbox change takes place, you need to subscribe to the change event:
$(".package").change(function(){
if($(this).is(":checked")){
alert($(this).attr("checked"));
}
});
Edit: Try querying the actual Javascript object itself, should work
$(".package").change(function(){
if(this.checked){
alert(this.checked);
}
});

Related

How to Capture changing value of textbox

I have a webpage with a small survey. I want to pre populate some of the answers based on user inputs to previous question.
In the below code, if value of id QR~QID3 depends upon value of QID1_Total. However after the page loaded and even if the condition is met the textbox is not populated with correct value.
.addOnload(function()
{
if(document.getElementById("QID1_Total").value>15) {
document.getElementById("QR~QID3").value = "Good";
}
else{
document.getElementById("QR~QID3").value = "Average";
}
});
$("#QID1_Total").on("input", function() {
//statements goes here
});
use of on("input" will track every inputting event, include drop and paste.
know more about onInput : https://mathiasbynens.be/notes/oninput
Here is an Fiddle Example to know how trigger works :
https://jsfiddle.net/5sotpa63/
An Assumption
Let Us Say you are using a function, which holds this statement show Good and Average according to users Input.
var targetElem = document.getElementById("QID1_Total");
var showComment = (targetElem,value>15) ? "Good" : "Average";
document.getElementById("QR~QID3").value = showComment;
Above code is the shorter method of your own statement mentioned in your question.
Now on Change of the target QR~QID3 you need to load some content. you utilize the below code as follows.
$("#QR~QID3").on("input", function() {
//your next question loading statements goes here,
//statements to proceed when you show some comment Good or Average
}).trigger("input");
Hope! this could be helpful.
$('#QID1_Total').keydown(function () {
//ur code
});
as the mouse key is pressed in the input field the function is called
You need to add an event listener to the "QID1_Total" element.
If you want to run the check while the user changes the input, i.e. after each keypress use the oninput event.
If you want to run the check after the user has completed the input, use the onchange event. The onchange event will only fire after the input loses focus.
You can bind the event listeners by using the addEventListener() function like this:
document.getElementById("QID1_Total").addEventListener("input", function(){
//Code goes here
});
Here is a JSFiddle showing both methods.
You also have to use the parseInt() function on the textbox values before you can perform mathematical functions with them.

event.PreventDefault doesnt work until end of function

I have a checkbox on which i am trying to send an ajax request based on its position. It is true by default. I want to be able to click it, and get a dialog that asks me if I want to discard my changes,and this dialog depends on the fact that the checkbox is not yet false.
$("input[type='checkbox']").click(function(evt) {
evt.preventDefault();
alert(this.checked);
if(checkEdited()){
var result = confirm("Do you want to continue?");
}
});
function checkEdited(){
var checkbox = $("div.managerContent input[type='checkbox']");
if(!checkbox.checked){
return false;
}
else{
//check other stuff
}
}
And everytime, I am getting false in the alert. In the browser, when I click the checkbox the check goes away, i get the alert, and then the check comes back.. checkEdited() is also used in other places
Everywhere I look to find how to stop a checkbox change event and assign it a value later just tells me to use .click and e.prenventDeafult()
Any ideas? Thanks so much!
You should attempt to capture the event before the click is complete, you can do this with mousedown like so:
$("input[type='checkbox']").on('mousedown',function(evt) {
evt.preventDefault();
alert(this.checked);
});
Here is a demo with a working example of capturing it before it changes
JSFIDDLE DEMO

after using preventDefault, why can't i check a box with jquery?

How come the following code does not work. I prevent the default action on the event. Then I want to check the box anyway.
html
<input type="checkbox" class="checkbox" />
javsacript
$('.checkbox').click( function(e) {
e.preventDefault();
// some logic happens... now i may decide to check the box (in this case we want to check it for testing)
$('.checkbox').prop('checked',true);
});
You would think clicking the checkbox would still check the box.. but it doesnt. Check the fiddle to see what I mean.
http://jsfiddle.net/5KDH8/
I have also tried using the attr function without any luck.
You have to put the code that sets the "checked" property in a separate event loop:
setTimeout(function() { $('.checkbox').prop('checked', true); }, 1);
Either the browser or the library has to un-set the checkbox after the event handler returns, because it sets it in response to the click before the handler is invoked.
$('.checkbox').click( function(e) {
// do some logic that returns true or false
if (!mylogic) {
return false;
// returning false will prevent the checkbox to be checked.
}
});

Javascript code behaving differently based only on the presence of a couple of alert statements

I am using jQuery Autocomplete to do a product lookup. I am using the following code to enforce selection from a list:
$(".force-selection").blur(function(e) {
var value = $(this).val();
//check if the input's value matches the selected item
alert($(this).val());
alert($(this).data('selected-item'));
if(value != $(this).data('selected-item')) {
//they don't, the user must have typed something else
$(this)
.val('') //clear the input's text
.data('selected-item', ''); //clear the selected item
}
});
The above code ONLY works when the two alert statements are removed. Why would the behavior change based only upon the presence of a couple of alert statements?
Try switching to use the Autocomplete change event instead of the blur event.
Either as an init option when creating the Autocomplete:
$(".selector").autocomplete({
change: function(event, ui) { ... }
});
Or bind to the change event by type: autocompletechange.
$(".selector").bind("autocompletechange", function(event, ui) {
...
});
It could be caused by several issues.
If you're using Internet Explorer, the alert will cause the 'blur' event to fire on whatever field you're working in. In your sample code, it's obvious why that will cause issues. Otherwise, you're probably looking at a race condition issue.
Check out this fiddle in IE: http://jsfiddle.net/NsfKT/

Triggering a jquery action when the users mark a Checkbox

im very new in javascript and jquery. I have this checkbox:
<label for="editable">Editable </label><input name="editable" type="checkbox" id="edita"/>
And this jquery action:
$('#slickbox1').toggle(400);
return false;
I want to execute that action when the checkbox is checked. Thanks!
You could try:
$('#edita').change(
function() {
if ($(this).is(':checked')) {
$('#slickbox1').toggle(400);
}
});
Although it's worth noting that running the toggle() method only when it's checked (assuming that it starts off un-checked) involves the user clicking the input once to show it, and then again to remove the check and again to re-check it so that it hides as a result of the toggle().
It might be worth considering:
$('#edita').change(
function() {
if ($(this).is(':checked')) {
// checked
$('#slickbox1').show(400);
}
else {
// un-checked
$('#slickbox1').hide(400);
}
});
Which shows $('#slickbox1') if the check-box is checked, and hides it if not,
Or:
$('#edita').change(
function() {
$('#slickbox1').toggle(400);
});
Which toggles the $('#slickbox1') between show() and hide() when the input is checked and un-checked.
Edited to address the question raised by DomingoSL (the OP) in comments:
...can you please make an edit to see the procedure if now the triger is not a checkbox but a button?
There are two changes that need to be made to accommodate this:
a button has no change event, so it would have to use click() instead, and
a button has no :checked (or equivalent) state, so the if/else becomes redundant.
One way of doing it, though, and I'm assuming your element names remain the same since you've posted no information to the contrary, is:
$('#edita').click(
function(){
$('#slickbox1').toggle(400);
});

Categories

Resources