jQuery - radio button on click and not on change - javascript

I'm trying to find a solution to an issue I have between click and change.
I need to capture the click event and not change.
I'll explain the situation:
I have a radio button list with 3 items.
Each click I need to clean a div. However, If i'm posting back and return to the client with an error(submit, server validation check failed), the change event is fired once again (obviously), and the div is cleaned.
Is there a way to distinguish between click and the checked state?
I hope I have made myself clear.
Edit:
Added some code:
$("input[name*='SelectedOwner']").on('change',
function () {
var radioId = $(this).val();
if (radioId === "2" || radioId === "3") {
$("#div1").hide();
$("#divclean :input").removeAttr("disabled");
} else {
$("#div1").show();
$("#divclean :input").attr("disabled", true);
}
});
$("input[name*='SelectedOwner']").on('click', function () {
//Clean the output at each change
$("#divclean :input").val("");
});
Thanks.

$('input[name="choose"]').click(function(e) {
if ($(this).data('clicked')) {
$('#theDiv').text('You have REclicked "'+ $(this).val() + '" value');
}
else {
$('input[name="choose"]').data('clicked', false);
$(this).data('clicked', true);
$('#theDiv').text('First time you click "'+ $(this).val() + '" value');
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="theDiv"></div>
A
<input type="radio" name="choose" value="a" />
B
<input type="radio" name="choose" value="b" />
C
<input type="radio" name="choose" value="c" />

You should to bind the change event to every radio button:
$("#r1, #r2, #r3").change(function () { }
With jQuery is also possible:
if ($("#r1").is(":checked")) {}
More informations:
JQuery $(#radioButton).change(...) not firing during de-selection
I hope this helps...
Good Luck!

Related

Check checkbox based on variable value

I'm struggling with a checkbox. I want the checkbox to be checked depending on a variable coming from the database. I can see the value in my console, so it's dynamically filled, but I can't have the checkbox checked.
I tried 2 things:
$(document).ready(function() {
$('input[name="OPTIN_NEWSLETTER_STARTER_INDEPENDANT"]').each(function(index) {
if ($(this).val() ==
"%%OPTIN_NEWSLETTER_STARTER_INDEPENDANT%%")
($(this).prop('checked', true));
});
And
$(document).ready(function() {
var checkBox =
[
["OPTIN_NEWSLETTER_STARTER_INDEPENDANT",
"%%OPTIN_NEWSLETTER_STARTER_INDEPENDANT%%"],
];
for (var i = 0; i < checkBox.length; i++) {
if (checkBox[i][1] == "Yes") {
if ($('input[name="' + checkBox[i][0] + '"]'))
{
$('input[name="' + checkBox[i][0] +
'"]').prop("checked", true).change();
}
}
};
This is my html checkbox:
<label class="yesNoCheckboxLabel">
<input type="checkbox"
name="OPTIN_NEWSLETTER_STARTER_INDEPENDANT" id="control_COLUMN136"
label="OPTIN_NEWSLETTER_STARTER_INDEPENDANT"
value="%%OPTIN_NEWSLETTER_STARTER_INDEPENDANT%%"
checked="">OPTIN_NEWSLETTER_STARTER_INDEPENDANT</label>
It would be great to have someone's insights, thanks!
Kind regards,
Loren
I tested your case locally and It's working fine may be you are lacking some where else and make sure use attr in order to set value for jquery 1.5 or below
For jquery 1.5 or below
($(this).prop('checked', true));
$(document).ready(function() {
$('input[name="vehicle1"]').each(function(index) {
if ($(this).val() ==
"vehicle1")
($(this).prop('checked', true));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="checkbox" name="vehicle1" value="vehicle1"> I have a bike<br>
<input type="checkbox" name="vehicle1" value="vehicle1"> I have a car
</form>
and last thing make sure that value must be same for this condition
$(this).val() == "vehicle1"

checkbox $.change is being triggered by itself and looping because it is being modified inside $.change

I have a group of checkboxes that when you click ONE, they should ALL be checked.
When a user clicks one checkbox, it checks all the other checkboxes starting with that class name. What I want is for the user to click a checkbox, and $(".atpSelections").change is triggered only once per click.
Here's the code:
$(".atpSelections").change(function() {
console.log("CHANGED");
//Check ALL other checkboxes starting with that class name:
var className = $(this).attr("class");
className=className.replace("atpSelections ", "");
className=className.trim();
className=className.split("-");
//Get current checkbox state
var currentState = $(this).attr("checked");
//Now loop through all other checkboxes starting
//with the same class name and check them:
$("input[class*='"+className[0]+"-']").each(function(i){
//THIS IS TRIGGERING "$(".atpSelections").change"!!
if(currentState && currentState=="checked")
{
$(this).prop('checked', true);
}else
{
$(this).prop('checked', false);
}
});
});
The Problem
The problem is that when the user clicks one checkbox, the $(".atpSelections").change method gets triggered over and over because $(this).prop('checked', true); triggers $(".atpSelections").change again, and it just goes round and round.
So 1 click to a checkbox triggers 100s "change" events, when I only want it triggered once.
How do I alter the checkbox's state inside $(".atpSelections").change without triggering $(".atpSelections").change again?
Attempts
I tried changing $(".atpSelections").change to $(".atpSelections").click but it had the same issue. I think $(this).prop('checked', true); triggers the click event.
Solution
I used #James 's answer and changed
var currentState = $(this).attr("checked");
to
var currentState = $(this).prop("checked") ? "checked" : "";
and it worked perfectly! Thanks.
Here's the JSFiddle: https://jsfiddle.net/zL7amo0y/
The problem is with your currentState variable. Please do a console.log on it. I'm guessing it's undefined?
Below is your code fixed in both jQuery and Vanialla JS.
JQuery:
$(".atpSelections").change(function() {
var currentState = $(this).prop("checked");
console.log(currentState);
$("input[name='checkboxToCheck']").each(function(i){
if(currentState)
{
$(this).prop('checked', true);
}else
{
$(this).prop('checked', false);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="myForm">
<label for="checkbox1">Main Checkbox:</label>
<input class="atpSelections" value="checkbox1" type="checkbox" id="checkbox1" />
<label for="checkbox2">Checkbox2:</label>
<input name="checkboxToCheck" value="checkbox1" type="checkbox" id="checkbox1" />
<label for="checkbox3">Checkbox3:</label>
<input name="checkboxToCheck" value="checkbox1" type="checkbox" id="checkbox1" />
</form>
Vanilla JS:
var checkbox = document.getElementById("checkbox1")
var checkboxToCheck = document.getElementsByName("checkboxToCheck");
checkboxToCheck = [].slice.call(checkboxToCheck);
function checkAllBoxes() {
checkboxToCheck.forEach((element) => {
if (checkbox.checked) {
element.checked = true;
} else {
element.checked = false;
}
});
}
checkbox.addEventListener("change", checkAllBoxes);
<form name="myForm">
<label for="checkbox1">Main Checkbox:</label>
<input value="checkbox1" type="checkbox" id="checkbox1" />
<label for="checkbox2">Checkbox2:</label>
<input name="checkboxToCheck" value="checkbox1" type="checkbox" id="checkbox1" />
<label for="checkbox3">Checkbox3:</label>
<input name="checkboxToCheck" value="checkbox1" type="checkbox" id="checkbox1" />
</form>
I'm thinking know what is your problem, I got it with a plugin of checkboxes too.
Try this
$(".atpSelections").on('change.custom', function(e) {
console.log("CHANGED CUSTOM");
//Check ALL other checkboxes starting with that class name:
var className = $(this).attr("class");
className=className.replace("atpSelections ", "");
className=className.trim();
className=className.split("-");
//Get current checkbox state
var currentState = $(this).attr("checked");
//Now loop through all other checkboxes starting
//with the same class name and check them:
$("input[class*='"+className[0]+"-']")
.off('change.custom')
.each(function(i){
//THIS IS TRIGGERING "$(".atpSelections").change"!!
if(currentState && currentState=="checked"){
$(this).prop('checked', true);
}else{
$(this).prop('checked', false);
}
});
});
Normally it's okay :)

Popups for checking/unchecking a checkbox

I have prompts that produce a popup when a box is ticked and unticked. There looks to be a line of redundant code, but when removed the functions no longer work. So maybe not so redundant:-) But the #id doesn't match to anything (currently set as CAPS to not match)
Any ideas why this is interfering?
$('#checkbox').click(function() {
if ($("#checkbox").is(':checked')) {
if (confirm('Are you sure you want to CONFIRM the order?')) {
$('#CHECKBOX').click();
}
}
});
$("#checkbox").on('change', function() {
this.checked = !this.checked ? !confirm('Do you really want to change this to NOT RECEIVED?') : true;
});
http://jsfiddle.net/5nd1wj54/1/
Here is what I think you mean
$('#checkbox').click(function() {
if (this.checked) {
this.checked = confirm('Are you sure you want to CONFIRM the order?'));
}
else {
this.checked = !confirm('Do you really want to change this to NOT RECEIVED?');
}
});
Use classes instead ids, so now redundant code needed. You can store informations in the data attribute of a HTML element. jsFiddle.
I've add a class to every checkbox what should be examined.
$(".checkIt").on('change', function() {
if ($(this).is(':checked')) {
confirm('Do you really want to change ' + $(this).data('id') + ' to NOT RECEIVED?');
}
});
HTML
<input type="checkbox" data-id="checkbox1" class="checkIt" />
<input type="checkbox" data-id="checkbox2" class="checkIt" />
<input type="checkbox" data-id="checkbox3" class="checkIt" />

Get radio button previous state Click event/Uncheck the radio if previously checked

How can I see if a Radio button was already checked in a click event?
Actually what I want to do is that, if the clicked radio was previously checked, and user clicks the same radio again, then un-check it.
But the code below always evaluates the if condition t true :P
$('input.radiooption').click(function(g) {
if ($(this).is(":checked")) {
console.log("already checked, now uncheck it");
} else {
console.log("Not checked");
}
});
P.S.
The thing is,
When I click an unchecked Radio button, it gets CHECKED
When I click an already checked button, it gets CHECKED
So, I want to know a way to determine the previous state of a radio button inside click event.
JS FIDDLE
Keep a track of the previous state with temp variable:
var prv;
var markIt = function(e) {
if (prv === this && this.checked) {
this.checked = false;
prv = null; //allow seemless selection for the same radio
} else {
prv = this;
}
};
$(function() {
$('input.radiooption').on('click', markIt);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type='radio' name='group' class='radiooption' />
<input type='radio' name='group' class='radiooption' />
<input type='radio' name='group' class='radiooption' />
<input type='radio' name='group' class='radiooption' />
<input type='radio' name='group' class='radiooption' />
Here you go:
var makeRadiosDeselectableByName = function(name){
$('input[name=' + name + ']').click(function() {
if($(this).attr('previousValue') == 'true'){
$(this).attr('checked', false)
} else {
$('input[name=' + name + ']').attr('previousValue', false);
}
$(this).attr('previousValue', $(this).attr('checked'));
});
};
Here is full example: http://jsfiddle.net/EtNXP/1467/

Enable/Disable a button on select of radio button in jquery

I have a page in which there are 2 radio buttons and a next button. I have made next button disabled and it is enabled only when I select any radio button. But now when I go to another page and come back to this page the next button comes as disabled although the radio button is already selected. PFB the code
$(document).ready(function () {
$('#commandButton_1_0').attr('disabled', 'true');
$('input:radio[name=a_SignatureOption]').click(function () {
var checkval = $('input:radio[name=a_SignatureOption]:checked').val();
if (checkval == '1' || checkval == '2') {
$('#commandButton_1_0').removeAttr('disabled');
}
});
});
Try
$(document).ready(function() {
$('input:radio[name=a_SignatureOption]').click(function() {
var checkval = $('input:radio[name=a_SignatureOption]:checked').val();
$('#commandButton_1_0').prop('disabled', !(checkval == '1' || checkval == '2'));
});
});
Demo: Fiddle
I took time to understand your problem,
This can be solved by unchecking the radio while loading the page.
$(document).ready(function () {
$('input:radio[name=a_SignatureOption]').prop('checked', false);
$('#commandButton_1_0').attr('disabled', 'true');
$('input:radio[name=a_SignatureOption]').click(function () {
var checkval = $('input:radio[name=a_SignatureOption]:checked').val();
if (checkval == '1' || checkval == '2') {
$('#commandButton_1_0').removeAttr('disabled');
}
});
});
check out JSFiddle, btw redirect to other site and press back button to find the difference.
Hope you understand.
// Try this.............
$(document).ready(function () {
$("input:radio[name=a_SignatureOption]").removeAttr('checked');
$('#commandButton_1_0').attr("disabled","disabled");
$('input:radio[name=a_SignatureOption]').click(function () {
var checkval = $('input:radio[name=a_SignatureOption]:checked').val();
if (checkval == '1' || checkval == '2') {
$('#commandButton_1_0').removeAttr("disabled","disabled");
}
});
});
It is simple as your question is
<form name="urfrm">
<input type="radio" value="1" name="a_SignatureOption"> Yes<br>
<input type="radio" value="2" name="a_SignatureOption"> No<br>
<input type="submit" id="butn" name="butn" value="next" disabled><br>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
//This will check the status of radio button onload
$('input[name=a_SignatureOption]:checked').each(function() {
$("#butn").attr('disabled',false);
});
//This will check the status of radio button onclick
$('input[name=a_SignatureOption]').click(function() {
$("#butn").attr('disabled',false);
});
});
</script>
The easiest solution I can think of - albeit somewhat belatedly, is:
// selects all input elements, whose name is 'a_SignatureOption' and whose
// type is 'radio'
// binds a change event-handler, using 'on()':
$('input[name=a_SignatureOption][type="radio"]').on('change', function(){
// sets the 'disabled' property of the button to 'true' if zero radio inputs
// are checked, or to false if one is checked:
$('#commandButton_1_0').prop('disabled', $('input[name=a_SignatureOption][type="radio"]:checked').length === 0);
// triggers the change event-handler on page load:
}).change();
References:
Attribute-equals ([attribute="value"]) selector.
change().
on().
prop().
On load of document you need to check whether radio button is clicked or not
$(document).ready(function() {
$('input:radio[name=a_SignatureOption]').each(function() {
checked(this);
});
$('input:radio[name=a_SignatureOption]').click(function() {
checked(this);
});
function checked(obj){
if($(obj).is(':checked')) {
$('#commandButton_1_0').removeAttr('disabled');
}else{
$('#commandButton_1_0').attr('disabled', 'true');
}
}
});
You forgot to check the buttons at the beginning.
$(document).ready(function () {
$('#commandButton_1_0').attr('disabled', 'true');
if( $('input[name=a_SignatureOption]:checked' ).size() > 0 ) {
$('#commandButton_1_0').removeAttr('disabled');
}
$('input[name=a_SignatureOption]').click(function () {
if( $('input:radio[name=a_SignatureOption]:checked' ).size() > 0 ) {
$('#commandButton_1_0').removeAttr('disabled');
}
});
});
By the way, I always suggest to add classes to form elements and work with those, instead of using [name="..."]. It's quicker and simplier and you can change input names (if necessary) without touching js
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(document).ready(function () {
$('#commandButton_1_0').attr('disabled', 'true');
$('input:radio[name=a_SignatureOption]').click(function () {
var checkval = $('input:radio[name=a_SignatureOption]:checked').val();
alert(checkval)
if (checkval == '1' || checkval == '2') {
$('#commandButton_1_0').removeAttr('disabled');
}
else {
$('#commandButton_1_0').attr('disabled', 'disabled');
}
});
});
</script>
</head>
<body>
<input type="radio" name="a_SignatureOption" value="1" /> value1
<br />
<input type="radio" name="a_SignatureOption" value="2"/> value2
<br />
<input type="radio" name="a_SignatureOption" value="3" checked="checked"/> value3
<br />
<input type="button" id="commandButton_1_0" value="Next"/>
</body>
</html>

Categories

Resources