i made two dynamic dropdown list State and city
City dropdown will depend of selected option of state
problem is when all is good and okay to submit .it resets the city drop down
and does not submit
javascript code for making those dynamic drop down is
these function are onchange events
// remove all previous options
function removeOptions(selectbox) {
for (let i = selectbox.options.length - 1; i >= 0; i--) {
selectbox.remove(i);
}
}
// function to make city drop down according to selected state
function cityFunction(){
// get input value and text
const stateobj = document.getElementById('stateDropDown');
const valueState = stateobj.options[stateobj.selectedIndex].text;
const selectedOption = stateobj.options[stateobj.selectedIndex].value;
// making required arrays
let sindhArray = [ 'Select City', 'Karachi', 'Hyderabad', 'Mirpur khas', 'Sukkhar', 'Shikarpur' ];
let KhyberArray = [ 'Select City', 'gilgit', 'Qalat', 'Balakoot', 'Sawat', 'Peshwar' ];
let punjabArray = [ 'Select City', 'Lahore', 'Fasialabad', 'Qasoor', 'SheikhuPura', 'Gujrat' ];
let balochArray = [ 'Select City', 'Quetta', 'Chaman', 'Khuzdar', 'Turbat', 'Gawdar' ];
// if value is punjab or any select cities according to that state
if (valueState == 'Punjab') {
// removing all previous present options
removeOptions(document.getElementById('cityDropDown'));
let cityD = document.querySelector('#cityDropDown');
let index = 0;
for (let ele of punjabArray) {
var opt = document.createElement('option');
opt.value = index;
opt.innerHTML = ele; // whatever property it has
document.getElementById('cityDropDown').value = cityD.appendChild(opt);
index++;
}
}
if (valueState == 'Sindh') {
removeOptions(document.getElementById('cityDropDown'));
let cityD = document.querySelector('#cityDropDown');
let index = 0;
for (let ele of sindhArray) {
var opt = document.createElement('option');
opt.value = index;
opt.innerHTML = ele; // whatever property it has
document.getElementById('cityDropDown').value = cityD.appendChild(opt);
index++;
}
}
if (valueState == 'Balochistan') {
removeOptions(document.getElementById('cityDropDown'));
let cityD = document.querySelector('#cityDropDown');
let index = 0;
for (let ele of balochArray) {
var opt = document.createElement('option');
opt.value = index;
opt.innerHTML = ele; // whatever property it has
document.getElementById('cityDropDown').value = cityD.appendChild(opt);
index++;
}
}
if (valueState == 'khyber Pakhtunkhwa') {
removeOptions(document.getElementById('cityDropDown'));
let cityD = document.getElementById('cityDropDown');
let index = 0;
for (let ele of KhyberArray) {
var opt = document.createElement('option');
opt.value = index;
opt.innerHTML = ele; // whatever property it has
document.getElementById('cityDropDown').value = cityD.appendChild(opt);
index++;
}
}
}
for city form validation onchange event is
function cityDown() {
const cityObj = document.getElementById('cityDropDown');
const cityText = cityObj.options[cityObj.selectedIndex].text;
const valueOfCity = cityObj.options[cityObj.selectedIndex].value;
let citiesArray = [
'Quetta',
'Chaman',
'Khuzdar',
'Turbat',
'Gawdar',
'Lahore',
'Fasialabad',
'Qasoor',
'SheikhuPura',
'Gujrat',
'gilgit',
'Qalat',
'Balakoot',
'Sawat',
'Peshwar',
'Karachi',
'Hyderabad',
'Mirpur khas',
'Sukkhar',
'Shikarpur'
];
if ( valueOfCity == 0) {
document.getElementById('cityErr').innerText = 'City is required';
document.getElementById('cityDropDown').focus();
return valueOfCity;
}
if (citiesArray.indexOf(cityText) < 0) {
document.getElementById('cityErr').innerText = 'Select City';
document.getElementById('cityDropDown').focus();
return valueOfCity;
} else {
document.getElementById('cityErr').innerText = '';
return valueOfCity;
};
}
main function is
// validation f0rm function
function validateForm() {
// creating variable then sanitize them
isTrueorFalse = false;
document.getElementById('Address').disabled = isTrueorFalse;
document.getElementById('stateDropDown').disabled = isTrueorFalse;
document.getElementById('stateDropDown').style.background = '#FFF';
document.getElementById('cityDropDown').disabled = isTrueorFalse;
document.getElementById('cityDropDown').style.background = '#FFF';
const stateVal = stateDrag();
const cityV = cityDown();
const userAddress = form.Address.value;
//States must not be unselected
if (stateVal == 0 || stateVal == '') {
document.getElementById('stateErr').innerText = 'State is required.';
document.getElementById('stateDropDown').focus();
return false;
}
if (stateVal < 0) {
document.getElementById('stateErr').innerText = 'State is required.';
document.getElementById('stateDropDown').focus();
return false;
}
document.getElementById('addressErr').innerText = '';
document.getElementById('cityDropDown').focus();
console.log(cityV);
if (cityV == 0 || cityV == '') {
document.getElementById('cityErr').innerText = 'State is required.';
document.getElementById('cityDropDown').focus();
return false;
}
document.getElementById('cityErr').innerText = '';
document.getElementById('signupForm').submit();
}
here that demo
https://jsbin.com/jeguwakolo/1/edit?html,css,js,console,output
onsubmit was calling that function again and was resetting the city dropdown.
To solve this i just removed that function from stateDrag() and
in html i did this
<select oninput ="return stateDrag()" onchange="return cityFunction()">
after this i didnt get same problem and scripting was working fine thank you for everyone
Related
i'm new in servicenow and I have to add this filter "document_id.number STARTS WITH BKNG"
as a query, how can i do in servicenow?
this is my code:
// only show 30 in header menu dropdown
var max = 30;
var t = data;
t.items = [];
t.count = 0;
var u = getMyApprovals();
// use record watchers to tell header when to update dropdown counts
t.record_watchers = [];
t.record_watchers.push({'table':'sysapproval_approver','filter':'approverIN' + u.toString() + '^state=requested'});
var z = new GlideRecord('sysapproval_approver');
z.addQuery("approver", u);
z.addQuery("state", "requested");
z.addQuery("document_id.number", "STARTSWITH", "BKNG")
z.orderByDesc('sys_updated_on');
z.setLimit(max);
z.query();
var link = {};
link.title = gs.getMessage('View all approvals');
link.type = 'link';
link.href = '?id=approvals';
link.items = [];
t.items.push(link);
while (z.next()) {
var a = {};
var rec = getRecordBeingApproved(z);
if (!rec.isValidRecord()) // nothing being approved - hmmm
continue;
a.short_description = rec.short_description + "";
if (rec.getRecordClassName() == "sc_request") {
var items = new GlideRecord("sc_req_item");
items.addQuery("request", rec.getUniqueValue());
items.query();
if (items.getRowCount() > 1)
a.short_description = items.getRowCount() + " requested items";
else if (items.getRowCount() == 1) {
items.next();
a.short_description = items.getValue("short_description");
}
}
$sp.getRecordValues(a, z, 'sys_id,sys_updated_on');
a.number = rec.getDisplayValue();
a.__table = z.getRecordClassName();
a.type = 'approval';
t.items.push(a);
t.count++;
}
function getRecordBeingApproved(gr) {
if (!gr.sysapproval.nil())
return gr.sysapproval.getRefRecord();
return gr.document_id.getRefRecord();
}
i tried doing z.addQuery ("document_id.number", "STARTSWITH", "BKNG")
but it doesn't works.
i don't know how to do.
You can't dot-walk the document_id field when using .addQuery() as it is not a reference filed. Instead, you can use the Approval for (sysapproval) reference field like so:
z.addQuery("sysapproval.number", "STARTSWITH", "BKNG");
I getting form data in my console like this:
{item[0][sku]: 'EC1000-WMK', item[0][qty]: '1', item[1][sku]: 'POP-11', item[1][qty]: '1', form_key: 'ZuQxqBMHmidjUxEt'}
form_key: "ZuQxqBMHmidjUxEt"
item[0][qty]: "1"
item[0][sku]: "EC1000-WMK"
item[1][qty]: "1"
item[1][sku]: "POP-11"
This is how the above data created:
$.fn.getFormData = function(){
var data = {};
var dataArray = $(this).serializeArray();
console.log(data);
console.log(dataArray);
for(var i=0;i<dataArray.length;i++){
console.log(dataArray);
data[dataArray[i].name] = dataArray[i].value;
}
return data;
}
but I want to make it like:
[
{ "sku": "EC1000-WMK", "qty": "1" }
{ "sku": "POP-11", "qty": "1" }
]
Use Input fields name be like
<input name="item.0.sku" />
<input name="item.0.qty" />
<input name="item.1.sku" />
<input name="item.2.qty" />
& then use this function
Here is the function which converts all form inputs to JSON format
const jsonSerialize = ($this) => {
$this = $this.find('input, select');
let data = {};
for (let i = 0; i < $this.length; i++) {
let el = $this[i];
let val = el.value;
if (!val) val = "";
let fullName = el.getAttribute("name");
if (!fullName) continue;
let fullNameParts = fullName.split('.');
let prefix = '';
let stack = data;
for (let k = 0; k < fullNameParts.length - 1; k++) {
prefix = fullNameParts[k];
if (!stack[prefix]) {
stack[prefix] = {};
}
stack = stack[prefix];
}
prefix = fullNameParts[fullNameParts.length - 1];
if (stack[prefix]) {
let newVal = stack[prefix] + ',' + val;
stack[prefix] += newVal;
} else {
stack[prefix] = val;
}
}
return data
}
let $form = $('form');
params = jsonSerialize($form)
Hope may this work for you
I want my filters variable to update, my guess is it's re-initializing as the set value every time the function is called, whenever i try to declare it outside of the function I get a lexical error, how can I make sure it keeps the value assigned to it after a button has clicked
export function categoryRender(){
let filter = 'RICK'
console.log(filter)
const all = document.getElementById('all');
all.onclick = function(){
filter = 'ALL'
render(filter);
}
categories = categories.sort();
const filterContainer = document.getElementById("filter-container");
filterContainer.innerHTML = "";
const allFilterImg = document.getElementById('all-image');
if (filter === 'ALL'){
allFilterImg.setAttribute('src', './images/checked.jpeg')
}else{
allFilterImg.setAttribute('src', './images/unchecked.png')
console.log('unchecked all firing')
}
for (let i = 0; i < categories.length; i++){
const line = document.createElement("span");
const filterButton = document.createElement("img");
const filterLabel = document.createElement("h2");
filterContainer.appendChild(line);
line.appendChild(filterButton);
line.appendChild(filterLabel);
line.setAttribute('id', categories[i]);
line.classList.add('filter-line');
filterLabel.innerHTML = categories[i];
if (filter === categories[i]){
filterButton.setAttribute('src', './images/checked.jpeg')
}else{
filterButton.setAttribute('src', './images/unchecked.png')
}
line.onclick = function(){
filter = categories[i];
render(filter)
}
}
}
I'm trying to use local storage so that my invites stay on the page when refreshed. How would I go about implementing this into my code. I really don't know where to start and I'm really struggling with it. Please cans someone just show me how to implement this into my code. Ive been creating child elements and appending them to the UL in the HTML.
const form = document.getElementById("registrar");
const input = form.querySelector("input");
const mainDiv = document.querySelector(".main");
const ul = document.getElementById("invitedList");
const div = document.createElement('div');
const filterLabel = document.createElement('label');
const filterCheckBox = document.createElement('input');
filterLabel.textContent = "Hide those who havent responded";
filterCheckBox.type = 'checkbox';
div.appendChild(filterLabel);
div.appendChild(filterCheckBox);
mainDiv.insertBefore(div, ul);
/*
This creates a checkbox to see you has confirmed if they are coming
to the event or not.
*/
filterCheckBox.addEventListener("change", (e) => {
const isChecked = e.target.checked;
const lis = ul.children;
if (isChecked) {
for (let i = 0; i < lis.length; i += 1) {
let li = lis[i]
if (li.className === 'responded') {
li.style.display = '';
} else {
li.style.display = 'none';
}
}
} else {
for (let i = 0; i < lis.length; i += 1) {
let li = lis[i]
li.style.display = '';
}
}
});
/*
This function creates new list items (the invites).
*/
createLi = (text) => {
createElement = (elementName, property, value) => {
const element = document.createElement(elementName);
element[property] = value;
return element;
}
appendElement = (elementName, property, value) => {
const element = createElement(elementName, property, value);
li.appendChild(element);
return element;
}
const li = document.createElement("li");
appendElement("span", "textContent", text);
appendElement("label", "textContent", "Confirmed")
.appendChild(createElement("input", "type", "checkbox"));
appendElement("button", "textContent", "edit");
appendElement("button", "textContent", "remove");
return li;
}
}
form.addEventListener("submit", (event) => {
event.preventDefault();
const text = input.value;
input.value = "";
const li = createLi(text);
ul.appendChild(li);
});
ul.addEventListener("change", () => {
const checkbox = event.target;
const checked = checkbox.checked;
const listItem = checkbox.parentNode.parentNode;
if (checked) {
listItem.className = "responded";
} else {
listItem.className = "";
}
});
ul.addEventListener("click", (e) => {
if (e.target.tagName === 'BUTTON') {
const button = e.target;
const li = button.parentNode;
const ul = li.parentNode;
const action = button.textContent;
const nameActions = {
remove: () => {
ul.removeChild(li);
},
edit: () => {
const span = li.firstElementChild;
const input = document.createElement('input');
input.type = 'text';
input.value = span.textContent;
li.insertBefore(input, span);
li.removeChild(span);
button.textContent = 'Save';
},
Save: () => {
const input = li.firstElementChild;
const span = document.createElement('span');
span.textContent = input.value;
li.insertBefore(span, input);
li.removeChild(input);
button.textContent = 'edit';
}
};
nameActions[action]();
}
});
I only can give you an idea for this, if you are planning to save any big data to localStorage, you can save your data to string and remake it to JSON object!
Here's an exmaple for saving data set
var toSave = [ ];
var whatToSave = (Your invites data List, maybe a "text" var for your code?, organize
to array or loop for your "UL" tag)
for(var i=0;i<whatToSave.length;i++){
var obj = [];
obj[i] = {
text:whatToSave[i].text,
data1:whatToSave[i].data1,
data2:whatToSave[i].data2,
...
}
toSave.push(obj[i]);
}
var saveToString = JSON.stringify(toSave);
localStorage.setItem('invites', saveToString); //your invite data saved in local
storage
....
//after refreshing or when you need to use your saved data
var cameBack = JSON.parse(localStorage.getItem('invites'));
//this will return same data again
//and make function to make UL using retured data array
you don't really need to for loop and push if you already organized needed data to array, just wrote it to make you understand an idea to save data in localStorage. I don't know if this will help you but get an idea and implement it to your project :)
Using Asp.Net and Java Script
from Datatime control i am picking mulitple data which should add the combo box.
Java Script
function closed(cal) {
$("#txtIndividualDays").val("");
var noDays = 0;
var ddlDate = document.getElementById("sIndividualDays");
var opt;
ddlDate.options.length = 0;
MA.length = 0;
var countDays = 0;
for (var i in cal.multiple) {
countDays++;
}
var arrDays = new Array(countDays);
countDays = 0;
if (arrDays.length == 0) {
opt.text = "Select Date";
opt.value = "-1";
$("#txtIndividualDays").val($("#txtIndividualDays").val() + opt.text + ";");
}
for (var i in cal.multiple) {
arrDays[countDays] = i;
countDays++;
}
for (var i in arrDays.sort()) {
var d = cal.multiple[arrDays[i]];
var isWeekend = false;
var isHoliday = false;
if (d) {
var _date;
_date = d.print("%m/%d/%Y");
opt.text = d.print("%m/%d/%Y");
opt.value = d.print("%m/%d/%Y");
MA[MA.length] = d;
document.getElementById("txtIndividualDays").value += opt.text + ";";
}
}
document.getElementById("txtWorkingDays").value = noDays;
var control = $("#sIndividualDays");
var itemCount = $("#sIndividualDays option").length;
cal.hide();
return true;
};
The above script is showing error, while selecting a single date. What wrong in my script.
Need scrip help
I am not sure that these lines are correct:
var opt;
..............
opt.text = "Select Date";
opt.value = "-1";
...........
I suggest you change to: var opt = new Object();