Call javascript function when specific radio become unselected - javascript

I have some radio inputs and I would like to call a JS function only in the case where the id3 radio is selected and becomes unselected.
I searched, but I found only solutions, where only checked/unchecked status is checked:
$("input:radio").change(function() {
if ($("#id3").is(":checked")) {
alert('checked');
} else {
alert('unchecked');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="shipping_method" value="1" id="id1" data-refresh="5" class="">
<input type="radio" name="shipping_method" value="2" id="id2" data-refresh="5" class="">
<input type="radio" name="shipping_method" value="3" id="id3" data-refresh="5" class="">

You will need to keep track of when you last clicked it, to see if you need to say that it was unselected.
Plain JS
This is fairly simple to do in pure JavaScript. You can utilize the data-* attribute design to store the state of when an element was last checked.
let targetEl = document.getElementById('id3');
Array.from(document.querySelectorAll('input[type="radio"]')).forEach(radioEl => {
radioEl.addEventListener('change', function(e) {
if (e.target.id === targetEl.id && e.target.checked) {
alert(e.target.id + ' - checked');
e.target.setAttribute('data-waschecked', true);
} else if (targetEl.getAttribute('data-waschecked') === 'true') {
alert(targetEl.id + ' - unchecked');
targetEl.setAttribute('data-waschecked', false);
}
});
});
<input type="radio" name="shipping_method" value="1" id="id1" data-refresh="5">
<input type="radio" name="shipping_method" value="2" id="id2" data-refresh="5">
<input type="radio" name="shipping_method" value="3" id="id3" data-refresh="5">
jQuery
This advanced solution allows you to monitor multiple radio buttons. It is written mostly in jQuery.
const trackableIds = [ 'id1', 'id3' ];
$('input[type="radio"]').on('change', function(e) {
let $target = $(e.target),
isTrackable = trackableIds.includes($target.attr('id'));
if (isTrackable && $target.is(':checked')) {
alert($target.attr('id') + ' - checked');
$target.attr('data-waschecked', true);
}
trackableIds.filter(trackId => trackId !== $target.attr('id'))
.forEach(trackId => {
let $trackable = $('#' + trackId);
if ($trackable.attr('data-waschecked') === 'true') {
alert($trackable.attr('id') + ' - unchecked');
$trackable.attr('data-waschecked', false);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="shipping_method" value="1" id="id1" data-refresh="5">
<input type="radio" name="shipping_method" value="2" id="id2" data-refresh="5">
<input type="radio" name="shipping_method" value="3" id="id3" data-refresh="5">
As a jQuery plugin
Nearly identical behavior to the jQuery above, but as a plugin. There are even custom callback function options for checking/unchecking.
(($) => {
$.fn.trackRadio = function(ids, opts) {
this.on('change', function(e) {
let $target = $(e.target), isTrackable = ids.includes($target.attr('id'));
if (isTrackable && $target.is(':checked')) {
opts.onCheckFn($target);
$target.attr('data-waschecked', true);
}
ids.filter(trackId => trackId !== $target.attr('id')).forEach(trackId => {
let $trackable = $('#' + trackId);
if ($trackable.attr('data-waschecked') === 'true') {
opts.onCheckFn($trackable);
$trackable.attr('data-waschecked', false);
}
});
});
}
})(jQuery);
$('input[type="radio"]').trackRadio(['id1', 'id3'], {
onCheckFn : function($radio) {
alert($radio.attr('id') + ' - checked');
},
onUncheckFn : function($radio) {
alert($radio.attr('id') + ' - unchecked');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="shipping_method" value="1" id="id1" data-refresh="5">
<input type="radio" name="shipping_method" value="2" id="id2" data-refresh="5">
<input type="radio" name="shipping_method" value="3" id="id3" data-refresh="5">

What you can do is add a watcher variable to find out whether you are deselecting the radio button.
var isChecked = false;
$("input:radio").change(function () {
if ($("#id3").is(":checked")) {
isChecked = true;
} else {
if (isChecked) {
alert("Unchecked");
isChecked = false;
}
}
});
CodePen: https://codepen.io/ashfaq_haq/pen/LYYjLrv?editors=1010

Related

For each input if they are changed to checked store input ID of checked input in variable

I would like to store the ID of the input that is currently checked in variable selectedLevelId.
$("[id^=level_]").each(function() {
$(this).change(function() {
if ($(this).is(':checked')) {
var selectedLevelId = $(this).prop('id');
}
});
});
document.getElementById('levelVal').innerHTML=selectedLevelId;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input id="level_4432" name="level_id" type="radio" value="4432">
<input id="level_4235" name="level_id" type="radio" value="4235">
<input id="level_1454" name="level_id" type="radio" value="1454">
<input id="level_9823" name="level_id" type="radio" value="9823">
<div id="levelVal">
</div>
You have the output of your logic outside the .change() event so JS doesn't know what's happening inside the event. Just put the logic inside and it will work:
var selectedLevelId;
$("[id^=level_]").each(function() {
$(this).change(function() {
if ($(this).is(':checked')) {
selectedLevelId = $(this).prop('id');
document.getElementById('levelVal').innerHTML = selectedLevelId;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="level_4432" name="level_id" type="radio" value="4432">
<input id="level_4235" name="level_id" type="radio" value="4235">
<input id="level_1454" name="level_id" type="radio" value="1454">
<input id="level_9823" name="level_id" type="radio" value="9823">
<div id="levelVal">
</div>
There are 2 solutions
1 - change it inside the on change event
2 - create an interval that checks for new value every "n" ms
// 1-
/*let selectedLevelId;
$("[id^=level_]").each(function() {
$(this).change(function() {
if ($(this).is(':checked')) {
document.getElementById('levelVal').innerHTML = $(this).prop('id');
}
});
});
*/
// OR
// 2-
let selectedLevelId;
$("[id^=level_]").each(function() {
$(this).change(function() {
if ($(this).is(':checked')) {
selectedLevelId = $(this).prop('id');
}
});
});
setInterval(function(){
document.getElementById('levelVal').innerHTML = selectedLevelId;
}, 100);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input id="level_4432" name="level_id" type="radio" value="4432">
<input id="level_4235" name="level_id" type="radio" value="4235">
<input id="level_1454" name="level_id" type="radio" value="1454">
<input id="level_9823" name="level_id" type="radio" value="9823">
<div id="levelVal">
</div>

Uncheck all checkboxes if "Other" checkbox is checked and get value

So, I have 4 checkboxes:
Heating
AC
Cold Chain
Others
The condition is, you can multiple check the three: Heating, AC, and Cold Chain. But when you check on "Other", the three will be unchecked. And when you check again on any of the three, the Other checkbox will be unchecked.
When the Others is checked, a "Please specify" input text will appear.
And in the summary, Looking for solutions in Others - [value]
This is my fiddle
$(document).ready(displayCheckbox);
CountSelectedCB = [];
function displayCheckbox() {       
$("input:checkbox").change(function() {                 
selectedCB = [];        
notSelectedCB = [];                
CountSelectedCB.length = 0;        
$("input:checkbox").each(function() {            
if ($(this).is(":checked")) {                
CountSelectedCB.push($(this).attr("value"));            
}        
});                
$('input[name=solutions]').val(CountSelectedCB).blur();    
});
}   
$(document).ready(displayRadiobox);
CountSelectedRB = [];
function displayRadiobox() {       
$("input:radio").change(function() {                 
selectedRB = [];        
notSelectedRB = [];                
CountSelectedRB.length = 0;        
$("input:radio").each(function() {            
if ($(this).is(":checked")) {                
CountSelectedRB.push($(this).attr("value"));            
}        
});                
$('input[name=existing]').val(CountSelectedRB).blur();     
});
}
$('#solutions, #existing').bind('keyup blur', function() {            
$('#summary').val('You are looking for solutions in ' +                               $('#solutions').val() +                               (' \n') +                              'Are you using an existing customer? ' +                               $('#existing').val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div> Looking for a solutions in:<br>
<input type="checkbox" value="Heating">Heating<br>
<input type="checkbox" value="Ac">AC<br>
<input type="checkbox" value="Cold Chain">Cold Chain<br>
<input type="checkbox" value="Others">Others<br>
</div>
<input name="specify" type="text" id="specify" style="display: none">
<input name="solutions" type="text" id="solutions">
<div><br>Are you an exisiting customer?<br>
<input type="radio" value="Yes" name="radio">Yes<br>
<input type="radio" value="No" name="radio">No
</div>
<input name="existing" type="text" id="existing">
<br><br> Summary:
<br>
<textarea type='text' id="summary"></textarea>
Made a simple example for you how you can do this using the prop() and siblings() functions.
Added some classes for better selectors.
$('#wrapper .some-checkbox').on('change', function() {
var $this = $(this);
if ($this.prop('checked')) {
if ($this.is('.some-others')) {
$this.siblings().prop('checked', false);
}
else {
$this.siblings('.some-others').prop('checked', false);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="wrapper">
<input class="some-checkbox" type="checkbox" value="Heating">Heating<br>
<input class="some-checkbox" type="checkbox" value="Ac">AC<br>
<input class="some-checkbox" type="checkbox" value="Cold Chain">Cold Chain<br>
<input class="some-checkbox some-others" type="checkbox" value="Others">Others<br>
</div>
You need to check if the checkbox Others is checked, then uncheck the other checkboxes with $('<your-checkbox->').prop('checked', false);
For example:
$(document).ready(displayCheckbox);
CountSelectedCB = [];
function displayCheckbox(){    
    $("input:checkbox").change(function() {          
        selectedCB = [];
        notSelectedCB = [];
        
        CountSelectedCB.length = 0;
        $("input:checkbox").each(function() {
            if ($(this).is(":checked")) {
                CountSelectedCB.push($(this).attr("value"));
if ($(this).attr("value") === "Others") {
CountSelectedCB = []; // reset result
$("input:checkbox").each(function() {
if ($(this).attr("value") !== "Others") {
$(this).prop('checked', false); // uncheck
}
});
$('input[name=solutions]').hide(); // toggle input
$('input[name=specify]').show(); // toggle input
}
            }
        });
        
        $('input[name=solutions]').val(CountSelectedCB).blur();
    });
}    
$(document).ready(displayRadiobox);
CountSelectedRB = [];
function displayRadiobox(){    
    $("input:radio").change(function() {          
        selectedRB = [];
        notSelectedRB = [];
        
        CountSelectedRB.length = 0;
        $("input:radio").each(function() {
            if ($(this).is(":checked")) {
                CountSelectedRB.push($(this).attr("value"));
            }
        });
        
        $('input[name=existing]').val(CountSelectedRB).blur(); 
    });
}
$('#solutions, #existing').bind('keyup blur', function() {
        
    $('#summary').val('You are looking for solutions in ' + 
                             $('#solutions').val() + 
                             (' \n') +
                             'Are you using an existing customer? ' + 
                             $('#existing').val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div> Looking for a solutions in:<br>
<input type="checkbox" value="Heating">Heating<br>
<input type="checkbox" value="Ac">AC<br>
<input type="checkbox" value="Cold Chain">Cold Chain<br>
<input type="checkbox" value="Others">Others<br>
</div>
<input name="specify" type="text" placeholder="Please specify" id="specify" style="display: none">
<input name="solutions" type="text" id="solutions">
<div><br>Are you an exisiting customer?<br>
<input type="radio" value="Yes" name="radio">Yes<br>
<input type="radio" value="No" name="radio">No
</div>
<input name="existing" type="text" id="existing">
<br><br>
Summary:<br>
<textarea type='text' id="summary"></textarea>
Well, I modified your displayCheckbox() function. Please try like this. I think your problem will be solved.
function displayCheckbox(){    
$("input:checkbox").change(function() {
selectedCB = [];
notSelectedCB = [];
CountSelectedCB.length = 0;
if($('input:checkbox[value="Others"]').is(":checked")){
$('input:checkbox').not(this).prop('checked', false);
CountSelectedCB.length = 0;
CountSelectedCB.push($(this).attr("value"));
}else{
$("input:checkbox").each(function() {
if ($(this).is(":checked")) {
CountSelectedCB.push($(this).attr("value"));
}
});
}
$('input[name=solutions]').val(CountSelectedCB).blur();
});
}
Thank you.
  
I've updated your Fiddle code. Please see this, it will solve your problem.
Here is the snippet:
$(document).ready(displayCheckbox);
CountSelectedCB = [];
function displayCheckbox() {       
$("input:checkbox").change(function() {                 
selectedCB = [];        
notSelectedCB = [];
selectedValue = $(this).attr("value");                
CountSelectedCB.length = 0;
if (selectedValue === "Others" && $(this).is(":checked")) {
uncheckAllCheckBox();
$(this).prop('checked', true);
CountSelectedCB.push(selectedValue);
} else {
$("input:checkbox").each(function() {
if ($(this).attr("value") === "Others")
$(this).prop('checked', false);
if ($(this).is(":checked")) {
CountSelectedCB.push($(this).attr("value"));
}
});
}                        
$('input[name=solutions]').val(CountSelectedCB).blur();    
});
}
function uncheckAllCheckBox() {
$("input:checkbox").each(function() {
$(this).prop('checked', false);
CountSelectedCB.length = 0;
});
}
$(document).ready(displayRadiobox);
CountSelectedRB = [];
function displayRadiobox() {       
$("input:radio").change(function() {                 
selectedRB = [];        
notSelectedRB = [];                
CountSelectedRB.length = 0;        
$("input:radio").each(function() {            
if ($(this).is(":checked")) {                
CountSelectedRB.push($(this).attr("value"));            
}        
});                
$('input[name=existing]').val(CountSelectedRB).blur();     
});
}
$('#solutions, #existing').bind('keyup blur', function() {            
$('#summary').val('You are looking for solutions in ' +                               $('#solutions').val() +                               (' \n') +                              'Are you using an existing customer? ' +                               $('#existing').val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div> Looking for a solutions in:<br>
<input type="checkbox" value="Heating">Heating<br>
<input type="checkbox" value="Ac">AC<br>
<input type="checkbox" value="Cold Chain">Cold Chain<br>
<input type="checkbox" value="Others">Others<br>
</div>
<input name="specify" type="text" id="specify" style="display: none">
<input name="solutions" type="text" id="solutions">
<div><br>Are you an exisiting customer?<br>
<input type="radio" value="Yes" name="radio">Yes<br>
<input type="radio" value="No" name="radio">No
</div>
<input name="existing" type="text" id="existing">
<br><br> Summary:
<br>
<textarea type='text' id="summary"></textarea>
Updated JSFiddle Code

javascript change and send multiple checkbox values

H, I have 4 checkboxes that i need to set values when clicked and unclicked. I have code that works for the first one but struggling to make it work with the other 3?
The code is
<label><input type="checkbox" name="colorCheckbox" value="red"> Return journey required?</label>
<div align="left"> <label><input type="checkbox" name="signs" id="signs"> Non sign written</label></div>
<div align="left"> <label><input type="checkbox" name="disabled" id="disabled"> Disabled access</label></div>
<div align="left"> <label><input type="checkbox" name="female" id="female"> Female driver</label></div>
and the js that works for the first on is :
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
var inputValue = $(this).attr("value");
$("." + inputValue).toggle();
if (this.checked){
document.getElementById("return_required").value = "YES";
}
else {
document.getElementById("return_required").value = "NO";
}
});
});
Because they don't have a value like the first one. They have an id.
You are getting the input value and working on it, so if the input don't has a value, you won't be able to select it.
var inputValue = $(this).attr("value"); // Offending line, because only your first input has a value.
$("." + inputValue).toggle();
The easiest way would be to check the name of the clicked element using this.name and manually match it to the checkboxes, then code the logic for each checkbox. An example is provided below:
$(document).ready(function() {
$('input[type="checkbox"]').click(function() {
var inputValue = $(this).attr("value");
$("." + inputValue).toggle();
if (this.name == "colorCheckbox")
if (this.checked) {
document.getElementById("return_required").value = "YES";
} else {
document.getElementById("return_required").value = "NO";
}
else if (this.name == "signs") {
console.log("signs"); // replace with logic
} else if (this.name == "disabled") {
console.log("disabled"); // replace with logic
} else if (this.name == "female") {
console.log("female"); // repalce with logic
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><input type="checkbox" name="colorCheckbox" value="red"> Return journey required?</label>
<div align="left"> <label><input type="checkbox" name="signs" value="signs"> Non sign written</label></div>
<div align="left"> <label><input type="checkbox" name="disabled" value="disabled"> Disabled access</label></div>
<div align="left"> <label><input type="checkbox" name="female" value="female"> Female driver</label></div>
<br>
<input id="return_required" value="NO"></input>

array of checkbox value checked and unchecked

I have this function, when I checked one or more checkbox the function load the value of the checked checkbox...but when I unchecked one or more check box the function show an empty array.
this is the function:
$(document).ready(function () {
$('input[type="checkbox"]').change(function () {
var mycheck = new Array();
if ($(this).is(':checked')) {
$("#line-checkbox-1:checked").each(function () {
mycheck.push($(this).val());//aggiungo value del checked
});
alert(mycheck)
} else {
var itemtoRemove = $(this);
mycheck.splice($.inArray(itemtoRemove, mycheck), 1); //rimuovo il value del dechecked
alert(mycheck);
}
});
This is HTML of the checkbox:
<div class="col-lg-3">
<input tabindex="17" id="line-checkbox-1" type="checkbox" name="servizi" value="3">
</div>
Try This Simple Script, this works for you:
HTML
<input type="checkbox" name="options[]" value="1" />
<input type="checkbox" name="options[]" value="2" />
<input type="checkbox" name="options[]" value="3" />
<input type="checkbox" name="options[]" value="4" />
<input type="checkbox" name="options[]" value="5" />
JQUERY
$(document).ready(function ()
{
$('input[type="checkbox"]').change(function ()
{
var arr = $.map($('input:checkbox:checked'), function(e,i) {
return +e.value;
});
alert(arr);
});
});
Its probably because you are using id to reference the checkboxes and since you are creating the array from scratch everytime user changes a checkbox. you should recheck the list everytime a checkbox is changed. That means you dont need that if.( if($(this).is(":checked") )
$('.checkboxes input[type="checkbox"]').change(function () {
var mycheck = new Array();
$(".checkboxes input[type='checkbox']:checked").each(function () {
if ($(this).is(':checked')) {
mycheck.push($(this).attr("id") + ": is " + $(this).val()); //aggiungo value del checked
}
});
alert(mycheck);
});
here is a fiddle if i understand correctly what you are trying to do

Enable Disable Button if any of checkbox is checked

I have Check All and Check Non Section.
I want to take decision , if any of the checkbox is checked, enable Delete button otherwise disable it.
Plus I want to get all the values of checked checkboxes when click on Delete button coma seperated.
Here is my fiddle:
http://jsfiddle.net/48ZRu/2/
Here is my code:
HTML:
<input type="button" class="check" value="Check All" /> <input type="button" value="Delete" disabled /> <br/>
<input type="checkbox" class="cb-element" value="1" /> Checkbox 1 <br/>
<input type="checkbox" class="cb-element" value="2"/> Checkbox 2 <br/>
<input type="checkbox" class="cb-element" value="3"/> Checkbox 3 <br/>
JS:
$('.check:button').click(function()
{
var checked = !$(this).data('checked');
$('input:checkbox').prop('checked', checked);
$(this).data('checked', checked);
if(checked == true)
{
$(this).val('Uncheck All');
}
else
if(checked == false)
{
$(this).val('Check All');
}
});
Try
$('.check:button').click(function () {
var checked = !$(this).data('checked');
$('input:checkbox').prop('checked', checked);
$('.delete:button').prop('disabled', !checked)
$(this).data('checked', checked);
if (checked == true) {
$(this).val('Uncheck All');
} else if (checked == false) {
$(this).val('Check All');
}
});
$('input:checkbox').change(function () {
$('.delete:button').prop('disabled', $('input:checkbox:checked').length == 0)
})
$('.delete:button').click(function () {
var array = $('input:checkbox:checked').map(function () {
return this.value
}).get();
console.log(array, array.join())
})
Demo: Fiddle
Give a id to delete button. Lets say if the id is delete -
$("input[type=checkbox]").on("change", function(){
if ($("input[type=checkbox]:checked").length > 0)
{
$("#delete").removeAttr('disabled','disabled');
}
else
{
$("#delete").attr('disabled','disabled');
}
});
try this
var checkedSize = $('input:checked').size()
$(':input:button[value=Delete]').attr("disabled",checkedSize === 0);
$(function() {
var delbtn = $("input:button[value=Delete]");
$("input:checkbox").change(function() {
if($("input:checkbox:checked").length)
delbtn.removeAttr("disabled");
else
delbtn.attr("disabled","disabled");
});
delbtn.click(function() {
var s=$("input:checkbox:checked").map(function(e,i) { return e.value; }).join(",");
// s now has the values, comma separated
});
});
this one should fit all your needs:
$('.cb-element').change(function(){
var checked = !$(this).is(":checked");
if(checked)
{
$("#uncheck").removeAttr("disabled");
}
else {
$("#uncheck").attr("disabled","disabled");
}
});
$('#checkall').click(function(){
$('.cb-element').attr("checked","checked");
$("#uncheck").removeAttr("disabled");
});
$('#uncheck').click(function(){
var resultArr = [];
$.each($('.cb-element'),function(){
if($(this).is(":checked")){
resultArr.push($(this).val());
}
})
alert(resultArr.join(","))
})
<input type="button" class="check" id="checkall" value="Check All" /> <input type="button" id="remove" value="Delete" /> <br/>
<input type="checkbox" class="cb-element" value="1" /> Checkbox 1 <br/>
<input type="checkbox" class="cb-element" value="2" /> Checkbox 2 <br/>
<input type="checkbox" class="cb-element" value="3" /> Checkbox 3 <br/>
$('#remove').attr('disabled', 'disabled');
$(document).ready(function() {
$('.cb-element').click(function() {
if($(this).prop('checked'))
{
$('#remove').attr('disabled', false);
}
else
{
$('#remove').attr('disabled', true);
}
});
$('.check:button').click(function()
{
var checked = !$(this).data('checked');
$('input:checkbox').prop('checked', checked);
$(this).data('checked', checked);
if(checked == true)
{
$(this).val('Uncheck All');
$('#remove').attr('disabled', false);
}
else if(checked == false)
{
$(this).val('Check All');
$('#remove').attr('disabled', true);
}
});
});

Categories