jQuery.steps skip a step - javascript

I am using the jQuery.steps plugin (http://www.jquery-steps.com/) to guide the users in an internal webpage.
So far so good, now I am facing a little issue, I do have 5 Steps at the moment, what I need to achieve now is: If in the first step a special value from a dropdown is selected, I have to skip the steps 2 and 4 since these are not required at this moment.
Do you guys may have any solution for this?
I hope you get my question and please let me know if you do need additional information.
Thanks!

In the jquery.steps.js
add class to <ul role=\"tablist\" class=\"tablist\"></ul> (line 1037)
change functions goToNextStep & goToPreviousStep to
var length_custom;
function goToNextStep(wizard, options, state)
{
length_custom = $('ul.tablist li.skip').length;
var newIndex = increaseCurrentIndexBy(state, 1);
var anchor = getStepAnchor(wizard, newIndex),
parent = anchor.parent(),
isSkip = parent.hasClass("skip");
if(isSkip){
goToStep(wizard, options, state, newIndex + length_custom)
}else{
return paginationClick(wizard, options, state, newIndex);
}
}
function goToPreviousStep(wizard, options, state)
{
var newIndex = decreaseCurrentIndexBy(state, 1);
var anchor = getStepAnchor(wizard, newIndex),
parent = anchor.parent(),
isSkip = parent.hasClass("skip");
if(isSkip){
goToStep(wizard, options, state, newIndex - length_custom)
}else{
return paginationClick(wizard, options, state, newIndex);
}
}
Then add these functions at the bottom of your file
$.fn.steps.skip = function (i) {
var wizard = this,
options = getOptions(this),
state = getState(this);
if (i < state.stepCount) {
var stepAnchor = getStepAnchor(wizard, i);
stepAnchor.parent().addClass("skip");
refreshSteps(wizard, options, state, i);
}
};
$.fn.steps.unskip = function (i) {
var wizard = this,
options = getOptions(this),
state = getState(this);
if (i < state.stepCount) {
var stepAnchor = getStepAnchor(wizard, i);
stepAnchor.parent().removeClass("skip");
refreshSteps(wizard, options, state, i);
}
};
Now, initialize which step you want to skip
$("#wizard").steps('skip', index);
$("#wizard").steps('skip', index);// if you want to skip more than one step
$("#wizard").steps('skip', index);// if you want to skip more than one step
Disable skip
$("#wizard").steps('unskip', index);
$("#wizard").steps('unskip', index);// if you want to unskip more than one step
$("#wizard").steps('unskip', index);// if you want to unskip more than one step

There are events called onStepChanging , onStepChanged which could be passed to the form.steps . You can write a function to validate your form and steps in that and based on the currentIndex,newIndex you can trigger the next tab.
I am attaching here the link for the same which would help you.

I came up with a solution based on ajl80 answer.
But I had to change the goToNextStep & goToPreviousStep to:
var length_custom;
function goToNextStep(wizard, options, state)
{
var valid = false;
var i = 0;
while (!valid) {
i++;
var newIndex = increaseCurrentIndexBy(state, i);
var anchor = getStepAnchor(wizard, newIndex),
parent = anchor.parent(),
isSkip = parent.hasClass("skip");
if (!isSkip) valid = true;
}
return paginationClick(wizard, options, state, newIndex);
}
function goToPreviousStep(wizard, options, state)
{
var valid = false;
var i = 0;
while (!valid) {
i++;
var newIndex = decreaseCurrentIndexBy(state, i);
var anchor = getStepAnchor(wizard, newIndex),
parent = anchor.parent(),
isSkip = parent.hasClass("skip");
if (!isSkip) valid = true;
}
return paginationClick(wizard, options, state, newIndex);
}

Related

refresh drop down list after button click in web app

I have a web app with one drop down list and 2 buttons. The drop down list get values from a sheet. The buttons write back in the sheet. The script I have works fine with that:
<script>
$(function() {
$('#txt1').val('');
google.script.run
.withSuccessHandler(updateSelect)
.getSelectOptions();
});
function updateSelect(opt)
{
var select = document.getElementById("sel1");
select.options.length = 0;
for(var i=0;i<opt.length;i++)
{
select.options[i] = new Option(opt[i],opt[i]);
}
}
function listS() {
const selectElem = document.getElementById('sel1')
const index = selectElem.selectedIndex;
if (index > -1) {
const e = document.getElementById("sel1");
const value = e.options[index].value;
const body = { index: index, value: value };
google.script.run.withSuccessHandler(yourCallBack).yourServerSideFunc(body);
}
}
document.getElementById("but1").addEventListener("click",listS);
function yourCallBack(response) {
}
</script>
In Java script:
function getSelectOptions()
{
var ss=SpreadsheetApp.openById('1onuWoUKh1XmvEAmKktwJekD782BFIru-MDA0omqzHjw');
var sh=ss.getSheetByName('Database');
var rg=sh.getRange(2,1,sh.getLastRow()-1,8);
var vA=rg.getValues();
var useremail = Session.getActiveUser().getEmail();
var opt=[];
for(var i=0;i<vA.length;i++)
{
if(vA[i][1] == "Pending Approval"){
if(vA[i][7]+"#xxx.com" == useremail || vA[i][7]+"#xxx.com" == useremail) {
opt.push(vA[i][3]+" REQ ID: "+vA[i][0]);
}
}
};
if (opt.length == 0) {opt.push("You do not have pending requests")};
return opt;
}
function doGet() {
var output = HtmlService.createHtmlOutputFromFile('list');
return output;
}
function yourServerSideFunc(body) {
var value = body["value"];
var ss = SpreadsheetApp.openById('1onuWoUKh1XmvEAmKktwJekD782BFIru-MDA0omqzHjw');
var sh = ss.getSheetByName('Database');
var rg=sh.getRange(1,1,sh.getLastRow()-1,4);
var vA=rg.getValues();
var str = "Approved";
for(var i=0;i<vA.length;i++)
{
if(vA[i][3]+" REQ ID: "+vA[i][0] == value) {
sh.getRange(i+1, 2).setValue(str);
}
};
return ContentService.createTextOutput(JSON.stringify({message: "ok"})).setMimeType(ContentService.MimeType.JSON);
Now I am trying to regenerate the drop down list values after the button is clicked. I tried to add
var output = HtmlService.createHtmlOutputFromFile('list');
return output;
in yourServerSideFunc(body) function to regenerate the HTML but does not work. I have tried to force a HTML refresh, but also did not work.
How can I easily re-trigger the generation of the drop down list items? Worst case scenario it is ok to refresh the whole page, but it should be simple to regenerate the drop down list since I have already the code for it.
I ended up with this work around.
function listS() {
const selectElem = document.getElementById('sel1')
const index = selectElem.selectedIndex;
if (index > -1) {
const e = document.getElementById("sel1");
const value = e.options[index].value;
const body = { index: index, value: value };
google.script.run.withSuccessHandler(yourCallBack).yourServerSideFunc(body);
//ADDED:
var select = document.getElementById("sel1");
select.options[index] = new Option("Approved! Please refresh","Approved! Please refresh");
selectElem.selectedIndex = index;
}
}
It does not really meet the original goal to refresh the list from the sheet. It would be great if someone else posted a solution to call the server function. I tried to add google.script.run.doGet() and similar, but it seems that it does not call the server side functions properly.

Save on localstorage appended checkbox state

I have this function:
function test() {
var a = document.getElementById('test');
var b = document.createElement('input');
b.type = 'checkbox';
b.addEventListener( 'change', function() {
if(this.checked) {
//do something and save the state (checked)
} else {
//do something else and save the state(not checked)
}
}
and I want to save the state of the checkbox on localstorage from the appended checkbox, what is the best way to do it?
so if you are appending multiple checkboxes and you want to probably set all of their data separately you are going to need to have a different id for each checkbox so when you append a new one I would increment the ids
//function that appends new checkbox
var i = 0;
function appendCheckBox(){
i++
checkBoxId = 'checkbox' + i;
document.getElementById('checkbox-container').innerHTML = `<input type="checkbox" id="${checkBoxId}" onclick="handleCheckBoxClick(this)"></input>`;
}
//function to handle checkbox click you would probably want to make it check if
//the checkbox is already checked if it is set value to unchecked
function handleCheckBoxClick(ev){
var checkBoxId = ev.id;
localStorage.setItem(checkBoxId, 'checked')
}
You can use :
Setting storage :
localStorage.setItem('checkbox', b.checked);
Getting storage :
var checkVal=localStorage.getItem('checkbox');
You'll have to do a bit of work. localStorage doesn't work in a snippet here, so a working example of the example code can be found # this JSFiddle
localStorage.setItem("Checkboxes", "{}");
const showCurrentCheckboxStates = () =>
document.querySelector("pre").textContent = `Checkboxes saved state ${
JSON.stringify(JSON.parse(localStorage.getItem("Checkboxes")), null, " ")}`;
const saveCheckboxState = (val, id) => {
localStorage.setItem("Checkboxes",
JSON.stringify({
...JSON.parse(localStorage.getItem("Checkboxes")),
[`Checkbox ${id}`]: val })
);
showCurrentCheckboxStates();
};
const createCheckbox = id => {
let cb = document.createElement('input');
cb.type = 'checkbox';
cb.dataset.index = id;
cb.title = `Checkbox ${id}`;
document.body.appendChild(cb);
// save the initial state
saveCheckboxState(0, id);
};
document.addEventListener("click", evt =>
evt.target.dataset.index &&
saveCheckboxState(+evt.target.checked, evt.target.dataset.index)
);
for (let i = 1; i < 11; i += 1) {
createCheckbox(i);
}

isotope items disappearing when resize browser

I hacked an isotope combofilter with checkboxes, but here is the problem with the isotope items; They are disappearing when resizing browser window.
I dont why they are not displaying when I change the size of the browser!
Please so help!!
Normaly I use isotope V2. Here in JSFiddle, there is np with the window resizing however I used isotope v1..
I am driving crazy, when items disappeared I need to trigger by clicking a select button, then its going fine.
var $containerii;
var filters = {};
jQuery(document).ready(function () {
var $containerii = $('.isotope').isotope({
itemSelector: '.isotope-item'
});
getContent: '.isotope-item li'
var $filterDisplay = $('#filter-display');
$containerii.isotope();
// do stuff when checkbox change
$('#options').on('change', function (jQEvent) {
var $checkbox = $(jQEvent.target);
manageCheckbox($checkbox);
var comboFilter = getComboFilter(filters);
$containerii.isotope({ filter: comboFilter });
$filterDisplay.text(comboFilter);
});
});
function getContent() {
var items = document.getElementById("containerii")
}
function getComboFilter(filters) {
var i = 0;
var comboFilters = [];
var message = [];
for (var prop in filters) {
message.push(filters[prop].join(' '));
var filterGroup = filters[prop];
// skip to next filter group if it doesn't have any values
if (!filterGroup.length) {
continue;
}
if (i === 0) {
// copy to new array
comboFilters = filterGroup.slice(0);
} else {
var filterSelectors = [];
// copy to fresh array
var groupCombo = comboFilters.slice(0); // [ A, B ]
// merge filter Groups
for (var k = 0, len3 = filterGroup.length; k < len3; k++) {
for (var j = 0, len2 = groupCombo.length; j < len2; j++) {
filterSelectors.push(groupCombo[j] + filterGroup[k]); // [ 1, 2 ]
}
}
// apply filter selectors to combo filters for next group
comboFilters = filterSelectors;
}
i++;
}
var comboFilter = comboFilters.join(', ');
return comboFilter;
}
function manageCheckbox($checkbox) {
var checkbox = $checkbox[0];
var group = $checkbox.parents('.option-set').attr('data-group');
// create array for filter group, if not there yet
var filterGroup = filters[group];
if (!filterGroup) {
filterGroup = filters[group] = [];
}
var isAll = $checkbox.hasClass('all');
// reset filter group if the all box was checked
if (isAll) {
delete filters[group];
if (!checkbox.checked) {
checkbox.checked = 'checked';
}
}
// index of
var index = $.inArray(checkbox.value, filterGroup);
if (checkbox.checked) {
var selector = isAll ? 'input' : 'input.all';
$checkbox.siblings(selector).removeAttr('checked');
if (!isAll && index === -1) {
// add filter to group
filters[group].push(checkbox.value);
}
} else if (!isAll) {
// remove filter from group
filters[group].splice(index, 1);
// if unchecked the last box, check the all
if (!$checkbox.siblings('[checked]').length) {
$checkbox.siblings('input.all').attr('checked', 'checked');
}
}
}
If your using isotope v2, try this:
var $containerii = $('.isotope').isotope({
itemSelector: '.isotope-item',
isResizeBound: true
});
v1.5, this:
ADDENDUM
I don't see anything disappearing, just the col-md-10 shifting down when you resize your window. I changed the layout to avoid the shift and it seems to resize as it should.
jsfiddle
Thank you so much for helps and valuable responses. Finally I solved my problem by using trigger isotope on window resize at the end of the code.
$(window).on('resize', function () {
$containerii = $('.isotope');
triggerIsotope();
});

How to find the number of form elements that are getting passed to e.parameter in GAS?

In Google App Scripts (GAS), I want to be able to add and remove TextBox and TextArea elements to a FlexTable (that's being used as a form) and not worry about how many there are. I've named the text elements based on a counter to make this process easier.
So, is there a way to get the number of inputs (TextBox + TextArea) passed to e.parameter after the form is submitted?
Here's the relevant code from the FlexTable:
function doGet() {
var app = UiApp.createApplication();
var flex = app.createFlexTable().setId('myFlex');
var counter = 0;
var row_counter = 0;
...
var firstnameLabel = app.createLabel('Your FIRST Name');
var firstnameTextBox = app.createTextBox().setWidth(sm_width).setName('input' + counter).setText(data[counter]);
flex.setWidget(row_counter, 1, firstnameLabel);
flex.setWidget(row_counter, 2, firstnameTextBox);
row_counter++;
counter++;
var lastnameLabel = app.createLabel('Your LAST Name');
var lastnameTextBox = app.createTextBox().setWidth(sm_width).setName('input' + counter).setText(data[counter]);
flex.setWidget(row_counter, 1, lastnameLabel);
flex.setWidget(row_counter, 2, lastnameTextBox);
row_counter++;
counter++;
...
var submitButton = app.createButton('Submit Proposal');
flex.setWidget(row_counter, 2, submitButton);
var handler = app.createServerClickHandler('saveProposal');
handler.addCallbackElement(flex);
submitButton.addClickHandler(handler);
var scroll = app.createScrollPanel().setSize('100%', '100%');
scroll.add(flex);
app.add(scroll);
return app;
}
And here's the code for the ClickHandler (notice that I currently have 39 elements in my FlexTable):
function saveProposal(e){
var app = UiApp.getActiveApplication();
var userData = [];
var counter = 39;
for(var i = 0; i < counter; i++) {
var input_name = 'input' + i;
userData[i] = e.parameter[input_name];
}
So, is there a way to get the number of elements (in this case 39) without manually counting them and assigning this value to a variable?
I'm new at this stuff and I'd appreciate your help.
Cheers!
The simplest way is to add a hidden widget in your doGet() function that will hold the counter value like this :
var hidden = app.createHidden('counterValue',counter);// don't forget to add this widget as a callBackElement to your handler variable (handler.addCallBackElement(hidden))
then in the handler function simply use
var counter = Number(e.parameter.counterValue);// because the returned value is actually a string, as almost any other widget...
If you want to see this value while debugging you can replace it momentarily with a textBox...
You can search for arguments array based object.
function foo(x) {
console.log(arguments.length); // This will print 7.
}
foo(1,2,3,4,5,6,7) // Sending 7 parameters to function.
You could use a while loop.
var i = 0;
var userData = [];
while (e.parameter['input' + i] != undefined) {
userData[i] = e.parameter['input' + i];
i++;
};
OR:
var i = 0;
var userData = [];
var input_name = 'input0';
while (e.parameter[input_name] != undefined) {
userData[i] = e.parameter[input_name];
i++;
input_name = 'input' + i;
};

How to change a button from another function?

var ButtonFarmAtivada = new Array();
function X() {
var tableCol = dom.cn("td"); //cell 0
//create start checkbox button
ButtonFarmAtivada[index] = createInputButton("checkbox", index);
ButtonFarmAtivada[index].name = "buttonFarmAtivada_"+index;
ButtonFarmAtivada[index].checked = GM_getValue("farmAtivada_"+index, true);
FM_log(3,"checkboxFarm "+(index)+" = "+GM_getValue("farmAtivada_"+index));
ButtonFarmAtivada[index].addEventListener("click", function() {
rp_farmAtivada(index);
}, false);
tableCol.appendChild(ButtonFarmAtivada[i]);
tableRow.appendChild(tableCol); // add the cell
}
1) is it possible to create the button inside an array as I'm trying to do in that example? like an array of buttons?
2) I ask that because I will have to change this button later from another function, and I'm trying to do that like this (not working):
function rp_marcadesmarcaFarm(valor) {
var vListID = getAllVillageId().toString();
FM_log(4,"MarcaDesmarcaFarm + vListID="+vListID);
var attackList = vListID.split(",");
for (i = 0; i <= attackList.length; i++) {
FM_log(3, "Marca/desmarca = "+i+" "+buttonFarmAtivada[i].Checked);
ButtonFarmAtivada[i].Checked = valor;
};
};
For number 1) yes, you can.
function createInputButton(type, index) { // um, why the 'index' param?
// also, why is this function called 'createInputButton'
// if sometimes it returns a checkbox as opposed to a button?
var inputButton = document.createElement("input");
inputButton.type = type; // alternately you could use setAttribute like so:
// inputButton.setAttribute("type", type);
// it would be more XHTML-ish, ♪ if that's what you're into ♫
return inputButton;
}
I don't really understand part 2, sorry.

Categories