I'm using a checkbox to create a toggle switch as shown in this tutorial
The switch lives in a form where questions can be added dynamically. On submission the form posts as array of each answer back to the page to be processed however as the off switch doesn't pass a value back to the form the answers get out of sync with the answers for the other text fields. Is there any way to set a value for the off switch, i.e. when a check box is left unchecked?
I've tried to use the following to set my off checkboxes to off however it just seems to animate all the switches to on on form submission, anyone any ideas as to what I'm doing wrong?
$('form').submit(function(e){
var b = $("input:checkbox:not(:checked)");
$(b).each(function () {
$(this).val(0); //Set whatever value you need for 'not checked'
$(this).attr("checked", true);
});
return true;
});
You probably want to use Javascript to set a value for each checkbox "switch" in one of two ways:
Option 1: in the html of the switch elements/checkboxes, set the value attribute to zero by default. Then add a javascript click handler for the toggle to check its current value and toggle to the opposite state/value.
Option 2: add Javascript to the form's submit handler (on submit) that checks for any switch elements which have no values and set them to zero before processing form.
Either way should pass a value at all times, and your form should be able to keep track of all input states.
This snippet did the trick, as Anson suggested this finds all the checkboxes and sets them to either on or off on form submission:
$('form').submit(function () {
$(this).find('input[type="checkbox"]').each( function () {
var checkbox = $(this);
if( checkbox.is(':checked')) {
checkbox.attr('value','1');
} else {
checkbox.after().append(checkbox.clone().attr({type:'hidden', value:0}));
checkbox.prop('disabled', true);
}
})
});
Related
I am using ng-multiselect-dropdown,and I have to load the data based on the selected list.
Hence,I am using "onDropDownClose" event to get all the selected values and load the other data based on the selected multiple values.
<ng-multiselect-dropdown
[placeholder]="'Select Project'"
[settings]="dropdownSettings"
[data]="projects"
[required]='requiredField'
[(ngModel)]="selectedItems"
name="projectName"
[ngClass]='setClass()'
#projectName="ngModel"
(onSelect)="onItemSelect($event)"
(onSelectAll)="onSelectAll($event)"
(onDropDownClose)="saveFunction($event)">
But the close event is triggering all the time even I click outside the dropdown always.
Is there any alternate approach it? Please help.
This should be fixed at their end but until then you can use this trick:
In addition to (onDropDownClose), listen to a click event on ng-multiselect-dropdown
// this act as a differentiator between other calls(bug) and an intended call
(click)="dropDownSelect = true".
In your component, declare your variable and use it like this:
dropDownSelect = false;
saveFunction($event) {
if (this.dropDownSelect) {
// close the opening to subsequent actions
this.dropDownSelect = false;
// Perform action;
};
}
How can you tell if a SelectionInput checkbox item is checked in a callback? I have the following:
section.addWidget(CardService.newSelectionInput()
.setType(CardService.SelectionInputType.CHECK_BOX)
.setFieldName("chkSaveAttachments")
.addItem("Save Attachments", "chkSaveAttachmentsValue", true));
I have a button on my card that triggers a callback. From the callback, all I can access is the value ("chkSaveAttachmentsValue") but I can't tell whether the box is checked or unchecked.
function saveCallback(e) {
Logger.log(e.formInput.chkSaveAttachments); //prints "chkSaveAttachmentsValue"
Logger.log(e.formInput.chkSaveAttachments.chkSaveAttachmentsValue) //undefined
Logger.log(e.formInput.chkSaveAttachments.chkSaveAttachmentsValue.selected) //undefined
}
As stated here, formInputs property would be helpful here.
For multi-valued widgets such as checkboxes, you can read each value from formInputs instead.
In formInputs, all the selected options will be there in an array(e.formInputs.chkSaveAttachments).
Hence, in your saveCallback function, you can check as
e.formInputs.chkSaveAttachments.indexOf('chkSaveAttachmentsValue') > -1
You can get the state of checkbox by looking at the formInput in the onChange callback.
CardService.newSelectionInput()
.setType(CardService.SelectionInputType.CHECK_BOX)
.setFieldName("chkSaveAttachments")
.addItem("Save Attachments", "chkSaveAttachmentsValue", true).setOnChangeAction(selectionAction)
var selectionAction = CardService.newAction().setFunctionName("selectionAction").setParameters({"obj": obj});
function selectionAction(e) {
//formInput value comes only when it is selected.
var selected = !!e.formInput.chkSaveAttachments;
// you can set and access paramters in the onchange action for further use.
if(selected) {
// cache the state using cacheservice
} else {
// cache the state using cacheservice
}
}
I am new to coding and I would like to make a button that increment the count by 1 when a user clicks on it. I also would like to know how can I restrict it to be clicked only once. It is similar to the facebook like button but I want to create my custom button that would do the same thing but will just be shown in my website.
Here is the thing, using jQuery. The HTML part would be as under
<button>Click Me</button>
The jQuery code, that would be added to the <script> tag in <head> section.
var click = "1"; // set the variable
$('button').click(function () { // click on button
$(this).text('Clicked ' + click + ' times'); // write the variable value in it
click ++; // increment the variable
}
http://jsfiddle.net/afzaal_ahmad_zeeshan/jRXBr/4/ (For testing; as per Pippin's suggestion)
To disable it, use
$('button').click(function () { // click on button
$(this).prop('disabled', true); // set its disabled property to true
}
http://jsfiddle.net/afzaal_ahmad_zeeshan/jRXBr/1/ (For testing)
You can test the codes, using the fiddles that I have created, and you will understand how they work! :)
I have an array of divs which can be selected (change background colour on click to signify that to the user).
I want a way to submit the ids of all of these divs to my app, though can't see a 'nice' way of doing this; at the moment the only thing I can see to do is have a button that onclick triggers a javascript function that gets the id's and sends them back to my server in a POST.
Is there a way of creating a multiple select input on a form which uses divs instead of checkboxes or a multi-select list, or a better way of doing what I'm attempting?
Assuming you add the class selected when a user 'selects' the div:
var data = {};
$(".classOfDivs.selected").each(function(){
data[$(this).prop('id')] = 'true';
}
$.ajax({
url : 'ajaxPage.php',
type : 'POST',
dataType : 'text',
cache: false,
data: data,
success : function(text){alert('Saved: '+text);},
error: function(){alert('Did not reach server');}
});
Use the success function to process the returned text as needed. dataType can be changed to html, JSON, etc. See the .ajax() documentation.
Have a hidden input for each div, all with the same name but with a different id. When a div is clicked update the corresponding hidden input with the id. Then when you submit through a standard form POST all of those values will be available through the name you specified.
Since this is an app, what you could do is store everything in HTML5 localstorage using the JQuery javascript library.
Here's how to do it step by step:
Create a jquery array
on click, get div id and store it in the array with a key/value pair
if clicked again, remove it from the array
have some event listener like a "submit" button to store the value of your array to localstorage
Here is a jsfiddle I had that has exactly what you are talking about: http://jsfiddle.net/CR47/bqfXN/1/
It goes into a little more depth but the jquery should be exactly what you need.
The reason this is better than submitting with POST or using ajax is because since you say this is an app, you will be able to use this method offline, where as post or ajax would require a connection to a server running php.
var skinCare=[]; //the array
$('.skinCare').click(function(){ //onclick
var value = event.target.className.split(" ")[0]; //get classname, you would get id
var index = skinCare.indexOf(value); //gets where the location in
//the array this code is
if($(this).hasClass('selected')){ //when a div is clicked it gets
//$('.skinCare').removeClass('selected'); //the class "selected" and adds
skinCare.splice(index, 1); //to array, then another click
} else if($.inArray(value, skinCare) == -1){ //removes it from array
skinCare.push(value);
}
});
$('.submitbutton').click(function(){
localStorage.setItem('Skin Care', JSON.stringify(skinCare));
});
Primer: An HTML checkbox can be set as indeterminate, which displays it as neither checked nor unchecked. Even in this indeterminate state, there is still an underlying boolean checked state.
When an indeterminate checkbox is clicked, it loses its indeterminate state. Depending on the browser (Firefox), it can additionally toggle the checked property.
This jsfiddle illustrates the situation. In Firefox, clicking either of the checkboxes once causes them to toggle their initial underlying checked state. In IE, the checked property is left alone for the first click.
I would like all browsers to behave the same, even if this means additional javascript. Unfortunately, the indeterminate property is set to false before the onclick handler (or onchange and jquery change) is called, so I can't detect whether it's called for a click on an indeterminate checkbox or not.
The mouseup and keyup (for spacebar toggle) events show the prior indeterminate state, but I'd rather not be that specific: it seems fragile.
I could maintain a separate property on the checkbox (data-indeterminate or similar), but I wanted to know if there's a simple solution I'm missing, and/or if other people are having similar issues.
If you would like to have an inderterminate checkbox which becomes checked on all browsers on click (or at least on IE, Chrome and FF5+), you need to initialise the checked attribute correctly, as shown here http://jsfiddle.net/K6nrT/6/. I have written the following functions to help you:
/// Gives a checkbox the inderminate state and the right
/// checked state so that it becomes checked on click
/// on click on IE, Chrome and Firefox 5+
function makeIndeterminate(checkbox)
{
checkbox.checked = getCheckedStateForIndeterminate();
checkbox.indeterminate = true;
}
and the interesting function which relies on feature detection:
/// Determine the checked state to give to a checkbox
/// with indeterminate state, so that it becomes checked
/// on click on IE, Chrome and Firefox 5+
function getCheckedStateForIndeterminate()
{
// Create a unchecked checkbox with indeterminate state
var test = document.createElement("input");
test.type = "checkbox";
test.checked = false;
test.indeterminate = true;
// Try to click the checkbox
var body = document.body;
body.appendChild(test); // Required to work on FF
test.click();
body.removeChild(test); // Required to work on FF
// Check if the checkbox is now checked and cache the result
if (test.checked)
{
getCheckedStateForIndeterminate = function () { return false; };
return false;
}
else
{
getCheckedStateForIndeterminate = function () { return true; };
return true;
}
}
No image tricks, no jQuery, no extra attributes and no event handling involved. This relies only on simple JavaScript initialisation (note that the "indeterminate" attribute cannot be set in the HTML markup, so JavaScript initialisation would have been required anyway).
This solved my problem
$(".checkbox").click(function(){
$(this).change();
});
I am not sure that will using function to set value for indeterminate checkboxes will be good solutions because:
you will have to change every place where you are using them,
if user submit form without clicking on check-boxes, value that
your backend will receive will be different depending of browser.
But I like clever way to determinate how browser works.
So you could check isCheckedAfterIndeterminate() instead usual window.navigator.userAgent.indexOf('Trident') >= 0 to see is it IE (or maybe other browser that works in unusual way).
So my solution will be:
/// Determine the checked state to give to a checkbox
/// with indeterminate state, so that it becomes checked
/// on click on IE, Chrome and Firefox 5+
function isCheckedAfterIndeterminate()
{
// Create a unchecked checkbox with indeterminate state
var test = document.createElement("input");
test.type = "checkbox";
test.checked = false;
test.indeterminate = true;
// Try to click the checkbox
var body = document.body;
body.appendChild(test); // Required to work on FF
test.click();
body.removeChild(test); // Required to work on FF
// Check if the checkbox is now checked and cache the result
if (test.checked) {
isCheckedAfterIndeterminate = function () { return false; };
return false;
} else {
isCheckedAfterIndeterminate = function () { return true; };
return true;
}
}
// Fix indeterminate checkbox behavoiur for some browsers.
if ( isCheckedAfterIndeterminate() ) {
$(function(){
$(document).on('mousedown', 'input', function(){
// Only fire the change event if the input is indeterminate.
if ( this.indeterminate ) {
this.indeterminate = false;
$(this).trigger('change');
}
});
});
}
Well make your own clickable image and use some java(script) to make it behave like that.
I doubt dough how many users would understand this state, so be carefull where you use it.