jQuery/Javascript Checkbox - javascript

i want do something like this with a checkBox. if the user clicks on the checkbox, it should change its state (checked -> unchecked and vv. ).
my code:
$('#checkBoxStandard').change(function() {
clickedFormBoxen('standard');
});
function clickedFormBoxen(active){
if(active == 'standard'){
if( $('#checkBoxStandard').is(":checked")){
$('#checkBoxStandard').prop("checked", false);
}else{
$('#checkBoxStandard').prop("checked", true);
}
console.log('ac: '+$('#checkBoxStandard').is(':checked'));
}
Unfortunately, the checkbox will not be unchecked again. The fist time, the checkbox is getting checked, but if i click on it again, nothing happens, it's still checked.
I wish to use this code so i can change the state of the checkbox by function call and not just by user interaction.
Please help me and sorry for my english^^

Try
$('#checkBoxStandard').removeAttr("checked");

You mean something like this? (jsFiddle)
HTML
<input type="checkbox" id="checkbox">
<label for="checkbox">Hey,check me!</label>
JavaScript
var respond = true;
function manualCheck(state)
{
respond = false;
$('#checkbox').prop("checked", state);
}
$('#checkbox').change(function ()
{
if (!respond)
{
respond = true;
return;
}
// Your code
}

As i've mentionend in my comment to your question, with your function clickedFormBoxen you effectively revert the effect of a user interaction on the checkbox element. Thus it seems that you have to call the change handler from a click handler on your checkbox element (i've streamlined the code a bit):
function clickedFormBoxen(active) {
if (active == 'standard') {
$('#checkBoxStandard').prop("checked", !($('#checkBoxStandard').prop("checked")));
}
}
$(document).ready( function(){
$('#checkBoxStandard').change( function(e) {
clickedFormBoxen('standard');
1;
});
$('#checkBoxStandard').click(function(e) {
$('#checkBoxStandard').change();
1;
});
});

Related

How to prevent multiple code execution on checkbox click in jQuery?

On my page I have a checkboxes like this:
<input id="check0" type="checkbox">
Each time user check or uncheck it I want to execute some jQuery code. Here's sample of this code:
$("input[type=checkbox]").click(function () {
if ($(this).is(':checked')) {
// Calculate something here
}
else {
// Or calculate something here
}
});
Here's the problem: if user will click on checkbox multiple time really quick, some of the code will be executed multiple times, because it will trigger click function every time, but browser will not change 'check' status that quick!
How to prevent this?
I thought to put something like:
$("input[type=checkbox]").click(function () {
if ($(this).is(':checked')) {
// Disable checkbox
$(this).disabled = true;
// Calculate something here
// Enable it back
$(this).disabled = false;
}
else {
// Or calculate something here
}
});
How can I make my code to execute exact in this sequence? Disable > then execute code > then enable back?
Thanks
You should use on change, not on click. Then check the prop checked. If checked, run code. If you want to disable, use attr.
Try this...
$("#check0").on("change", function () {
if($(this).prop("checked") == true){
alert("hey now");
$(this).attr("disabled","disabled");
} else {
//nothing
}
});
http://jsfiddle.net/Eddieflux/z3xfcmgk/

js checkbox NOT set a custom value if not checked

I am working on a form that someone else created that passes through information to Salesforce. But regardless of where it sends values to, the checkbox doesnt seem to behave as it should.
No matter checking or unchecking the checkbox, it will always output the 'xxx' value.
The javascript sets the value of another checkbox inside salesforce based on the first checkbox. If that checkbox is checked, set the 'optin' value to true, if not false.
I feel I need another line of code that says: if checkbox is checked then value=xxx. if not checked, nothing. Then based on that, the other if else can be run.
here is the html:
<input type="checkbox" value="xxx" id="industry_optin" name="industry_optin"> YES
This is the js: (it is part of a bigger part of js, so there is no close bracket)
$(document).ready(function() {
$('#industry_optin').on('change', function() {
if ($(this).prop('checked') === true) {
$('#optin').prop('checked', true);
} else {
$('#optin').prop('checked', false);
}
});
Your code has errors because of }); ending of code.
$(document).ready(function() {
$('#industry_optin').on('change', function() {
if ($(this).prop('checked') === true) {
$('#optin').prop('checked', true);
} else {
$('#optin').prop('checked', false);
}
});
});
Fiddle

Trigger functions from checkbox on click by clicking on a button

I have a couple of checkboxes and a button. When I click on checkbox - function is triggered. This is the desired behavior but I want to trigger it by clicking on the button. I want to have the possibility to first select checkboxes (I tried with return false and event.preventDefault but these completely switch the selection off) and then by clicking the button - trigger functions from checkboxes. Here is a link to jsfiddle:
http://jsfiddle.net/j93k2xns/6/
So for instance: I can select 3 checkboxes (nothing should happen) and after I click the button - three alerts should appear.
The code:
HTML:
<input type="checkbox" name='check[]' id="first">first</input>
<input type="checkbox" name='check[]'>second</input>
<input type="checkbox" name='check[]'>third</input>
<input type="checkbox" name='check[]'>fourth</input>
<input type="button" value="validate" id="val-button">
JS:
var check_state;
$(document).on('click','input[name="check[]"]', function(e){
if(check_state === true) {
alert('a');
} else {
return false;
}
});
$(document).on('click','#val-button', function(){
check_state = true;
});
There are a few interpretations to his question. If I'm reading it correctly, he wants to bind an arbitrary function to the checkboxes. Clicking the button should fire this event. This is how you can achieve that using custom events in jQuery:
$(function () {
$("input[name='check[]']").bind("myCustomButtonClick", function() {
if(this.checked) {
alert('a');
}
});
})
$(document).on('click','#val-button', function(){
$("input[name='check[]']").trigger("myCustomButtonClick");
});
And the associated jsfiddle: http://jsfiddle.net/3yf7ymos/
$(document).on('click','#val-button', function(){
$( 'input[name="check[]"]' ).each(function( index ) {
if($(this).is(':checked')) {
alert("a");
return true;
}
});
});
If you want to do something when the user checks a checkbox, add an event listener:
$('input[type="checkbox"]').click(function() {
if ($(this).is(':checked')) {
// do something
}
});
If the idea is run a couple of functions after the inputs are checked by clicking on a button:
function myFunction() {
if ($('input[id="something"]:checked').length == 0) {
// do something
} else if ($('input[id="something_2"]:checked').length == 0) {
// do something
}
//and so on..
}
$('#val-button').click(function() {
myFunction();
});
I have a similar inquiry. I have a number of check boxes. Each checkbox is linked to a different URL that opens a PDF form. I want my team to be able to select which forms they need by ticking the checkbox. Once they have done that, I would like a button to trigger the opening of each form based on which check box is checked. I have it so the checkbox upon being checked opens the form right away but it is very distracting. Its preferable they all get opened at once by a "button". Help. I am quite new to JavaScript so may need additional clarity.

hide div when no checkbox is checked

I am trying to show hidden text if at least one checkbox is checked and hide it if none are checked. I have a multiple checkboxes.The hidden text isn't showing when I check the checkooxes. Any help?
Here is fiddle http://jsfiddle.net/HDGJ9/1/
<input type="checkbox" name="ch[]">
<input type="checkbox" name="ch[]">
<input type="checkbox" name="ch[]">
<input type="checkbox" name="ch[]">
<div class="txt" style="display:none">
if($('input[name="ch[]"]').is(':checked'))
$(".txt").show(); // checked
else
$(".txt").hide(); // unchecked
Enclose/wrap your code with event handler like
$('input[name="ch[]"]').on('change', function () {
//your code
});
JSFiddle
You can just check the length of checked checkboxes...
var $checkboxes = $(':checkbox');
$checkboxes.on('change', function(){
$('.txt').toggle( $checkboxes.filter(':checked').length > 0 );
});
Nothing is executing your javascript code. There are many ways to execute, and also many ways to achieve the result you want. You can assign it to a click or change event like so:
$("input[name='ch[]']").click(function() {
if($('input[name="ch[]"]').is(':checked'))
$(".txt").show(); // checked
else
$(".txt").hide(); // unchecked
});
Here is an updated fiddle that checks your function everytime you click.
In your code, the test for checked/unchecked boxes occurs only once, when the page loads. You should run this check every time the value of any of the checkboxes changes. Something like
function refresh() {
if ($('input[name="ch[]"]').is(':checked')) {
$(".txt").show(); // checked
} else {
$(".txt").hide(); // unchecked
}
}
$('input:checkbox').change(refresh);
JSFiddle: http://jsfiddle.net/MHB8q/1/
You are selecting all four checkbox elements here, you need to only select one that is checked, and see if you get a result:
if($('input[name="ch[]"]').filter(':checked').length){
$(".txt").show(); // checked
} else {
$(".txt").hide(); // unchecked
}
Demo: http://jsfiddle.net/HDGJ9/10/
$('input[name="ch[]"]').on('change', function() {
if ($(this).is(':checked')) {
$('.txt').css('display', 'block');
}
else {
var checked = false;
$('input[name="ch[]"]').each(function(i, el) {
if ($(el).is(':checked')) checked = true;
});
if (!checked) $('.txt').css('display', 'none');
}
});
Version with the least amount of event handlers:
$(document).on("change", ":checkbox", function(){
var isAtLeastOneCheckboxChecked = $(':checkbox').filter(":checked").length > 0;
if (isAtLeastOneCheckboxChecked)
$('.txt').show();
else
$('.txt').hide();
});
Fiddle: http://jsfiddle.net/3d79N/

jQuery - cancel change event on confirmation dialog for a Dropdown

I have a dropdown and I have the jQuery change function.
I would like to implement the change of the selected item as per the Confirmation dialog.
If confirms true i can proceed for selected change otherwise I have keep the existing item as selected and cancel the change event.
How can I implement this with jQuery?
jquery Function
$(function () {
$("#dropdown").change(function () {
var success = confirm('Are you sure want to change the Dropdown ????');
if (success == true) {
alert('Changed');
// do something
}
else {
alert('Not changed');
// Cancel the change event and keep the selected element
}
});
});
One thing to remember change function hits only after selected item changed
So better to think to implement this on onchange - but it is not available in jquery. Is there any method to implement this?
Well, as Vinu has rightly pointed out, jQuery's change event is only triggered once the value of the select has actually been changed. You would be better off doing something like this:
var prev_val;
$('#dropdown').focus(function() {
prev_val = $(this).val();
}).change(function() {
$(this).blur() // Firefox fix as suggested by AgDude
var success = confirm('Are you sure you want to change the Dropdown?');
if(success)
{
alert('changed');
// Other changed code would be here...
}
else
{
$(this).val(prev_val);
alert('unchanged');
return false;
}
});
Something like what I did here?
http://jsfiddle.net/Swader/gbdMT/
Simply save the value as soon as a user clicks the select box, and revert back to this value if the onchange confirmation returns false.
Here is the code from my fiddle:
var lastValue;
$("#changer").bind("click", function(e) {
lastValue = $(this).val();
}).bind("change", function(e) {
changeConfirmation = confirm("Really?");
if (changeConfirmation) {
// Proceed as planned
} else {
$(this).val(lastValue);
}
});
Use following code,I have tested it and its working
var prev_val;
$('.dropdown').focus(function() {
prev_val = $(this).val();
}).change(function(){
$(this).unbind('focus');
var conf = confirm('Are you sure want to change status ?');
if(conf == true){
//your code
}
else{
$(this).val(prev_val);
$(this).bind('focus');
return false;
}
});
Below code is implemented for radio button.I think this code with minor changes can be used for drop down also.
<input type="radio" class="selected" value="test1" name="test1"
checked="checked" /><label>test1</label>
<input type="radio" name="test1" value="test2" /><label>
test2</label>
<input type="radio" name="test1" value="test3" /><label>
test3</label>
</div>
$("input[name='test1']").change(function() {
var response = confirm("do you want to perform selection change");
if (response) {
var container = $(this).closest("div.selection");
//console.log(container);
//console.log("old sel =>" + $(container).find(".selected").val());
$(container).find(".selected").removeClass("selected");
$(this).addClass("selected");
//console.log($(this).val());
console.log("new sel =>" + $(container).find(".selected").val());
}
else {
var container = $(this).closest("div.selection");
$(this).prop("checked", false);
$(container).find(".selected").prop("checked", true);
}
});
As far as I know you have to handle it yourself, this might help:
<select onFocus="this.oldIndex = this.selectedIndex" onChange="if(!confirm('Are you sure?'))this.selectedIndex = this.oldIndex">
Simply do it like
$("#dropdown").change(function () {
var success = confirm('Are you sure want to change the Dropdown ????');
if (success == true) {
// do something
}
else {
return false; // will set the value to previous selected
}
});
Blurring, focusing and storing previous values seems a bit cumbersome. I solved this problem by attaching my listener not to the select, but to the option:
$("#id").on('mousedown','option',confirmChange);
then,
function confirmChange(e){
var value = $(this).val(),
c = confirm('Are you sure you want to change?');
if(c)
$(this).parent().val(value);//can trigger .change() here too if necessary
else
e.preventDefault();
}
Of course optimizations can be done, but this is the general idea.

Categories

Resources