I'm trying to change the options that appear in my select box named session when a certain option is picked in my select box named movie.
Here's the script I've got so far.
<script>
var optionList = document.getElementsByName("movie")[0];
var movieList = ["AC", "CH", "AF", "RC"];
for(var i = 0; i < movieList.length; i++){
var movie = movieList[i];
var option = document.createElement("option");
option.textContent = movie;
option.value = movie;
optionList.appendChild(option);
}
</script>
<script>
var sessionList = document.getElementsByName("session")[0];
var actionSession = ["WED-09", "THU-09", "FRI-09", "SAT-09", "SUN-09"];
var childrenSession = ["MON-01", "TUE-01", "WED-06", "THU-06", "FRI-06", "SAT-12", "SUN-12"];
var foreignSession = ["MON-06", "TUE-06", "SAT-06", "SUN-06"];
var romanticSession = ["MON-09", "TUE-09", "WED-01", "THU-01", "FRI-01", "SAT-06", "SUN-06"];
if(document.getElementsByName("movie")[0].value === movieList[0])
{
for(var i = 0; i < actionSession.length; i++){
var session = actionSession[i];
var option = document.createElement("option");
option.textContent = session;
option.value = session;
sessionList.appendChild(option);
}
}
</script>
Consider changing the Sessions to an object, like so:
var sessions = {
"AC": ["WED-09", "THU-09", "FRI-09", "SAT-09", "SUN-09"],
"CH": ["MON-01", "TUE-01", "WED-06", "THU-06", "FRI-06", "SAT-12", "SUN-12"],
"AF": ["MON-06", "TUE-06", "SAT-06", "SUN-06"],
"RC": ["MON-09", "TUE-09", "WED-01", "THU-01", "FRI-01", "SAT-06", "SUN-06"]
}
This way, you can use the onchange of your select tag to get the value of the selected option and reference the list of sessions for the appropriate movie list as such:
var category = document.getElementByName("movie").value;
var currentSession = sessions[category];
for(var i = 0; i < currentSession.length; i++){
var session = currentSession[i];
var option = document.createElement("option");
option.textContent = session;
option.value = session;
sessionList.appendChild(option);
}
Objects in javascript can be referenced as "key" => "value" pairs simply by following the syntax:
object = { "key": value }, and value's type can be anything - even another Object!
You can even declare object keys like such:
var sessions = {};
sessions['AC'] = [...];
sessions['CH'] = [...];
sessions.AF = [...];
sessions.RC = [...];
That's right - all of the above declarations can be referenced as sessions['xx']
Hope this simplifies things a bit.
You could create a dictionary mapping elements of movieList to lists of <option> elements, maybe?
You might call the dictionary sessionOptions. You would then change all the children of #session at once - so this would go in your onchange handler for sessionList:
var sessionList = document.getElementsByName("session")[0];
var chosenMovie = "..."; // "AC", for instance
// Remove all elements from sessionList
while(sessionList.firstChild) {
sessionList.removeChild(sessionList.firstChild);
}
// Add the chosen movie options
var chosenMovieOptions = sessionOptions[chosenMovie];
for(var i = 0; i < chosenMovieOptions.length; i++) {
sessionList.appendChild(chosenMovieOptions[i]);
}
You would also want to make a mapping of movie codes to session lists:
var SESSION_LISTS = {
"AC": ["WED-09", "THU-09", "FRI-09", "SAT-09", "SUN-09"],
"CH": ["MON-01", "TUE-01", "WED-06", "THU-06", "FRI-06", "SAT-12", "SUN-12"],
"AF": ["MON-06", "TUE-06", "SAT-06", "SUN-06"],
"RC": ["MON-09", "TUE-09", "WED-01", "THU-01", "FRI-01", "SAT-06", "SUN-06"]
};
Then, to build sessionOptions, for each "session string list" (such as actionSession), you would loop through the session list and create elements:
var currentSession = "..."; // currentSession is the current session list - "AC", for instance
var currentSessionOptions = SESSION_LISTS[currentSession];
sessionOptions[currentSession] = [];
for(var i = 0; i < currentSessionOptions.length; i++){
var session = currentSessionOptions[i];
var option = document.createElement("option");
option.textContent = session;
option.value = session;
sessionOptions[currentSession].append(option);
}
But then you would do this for every sublist in SESSION_LISTS, so you would put this code in some initializer function:
var sessions = Object.keys(SESSION_LISTS);
for(var i = 0; i < sessions.length; i++) {
currentSession = sessions[i];
// the code snippet above
}
Related
I create an array 'userSelects' with 'select's from an 'option' array, the 'option' array is created with my usernamesunits array.
If I start the function at the first time, it works, but the elements are removed from my array.
running MySQL 5 with php7.3, I use a local server and a webspace.
// Main Tet
let testSelect = document.createElement("select");
let testOption = document.createElement("option");
testSelect.id = "1";
testOption.text = "alle";
testSelect.add(testOption);
let name = document.createElement("select");
let nameOption = document.createElement("option");
let n1ameOption = document.createElement("option");
name.id = "2";
nameOption.text = "--none--";
name.add(nameOption);
nameOption = document.createElement("option");
nameOption.text = userSafe[0].name;
name.add(nameOption);
n1ameOption.text = userSafe[1].name;
name.add(n1ameOption);
document.body.appendChild(name);
document.body.appendChild(testSelect);
// onchange womit die user id übergeben wird
//
name.addEventListener("change",function(){
console.log("tabe :" + name.value);
test(name.selectedIndex - 1 ,testSelect.id);
});
function test(id,oldID){
// r is a new test select
r = document.getElementById(oldID);
r.length = 0;
var sicherheitsCopy = userSelects;
sicherheitsCopy = userSelects;
// wen option select hinzugefügt wird, wird es gelöscht von der userSelect[index]
for(let index = 0; sicherheitsCopy[id].length != 0; index){
r.add(sicherheitsCopy[id][0])
console.log("index nummer " + sicherheitsCopy[id].length);
}
}
// generate userSelects
function initUnitSelect(){
for(let index = 0; index < userSafe.length; ++index){
let testSelect = document.createElement("select");
let userOptionFirstUnit = document.createElement("option");
userOptionFirstUnit.text = "--none--";
testSelect.add(userOptionFirstUnit);
for(let index2 = 0; index2 < userUnitsCase[index][0].length; ++index2){
let userOption = document.createElement("option");
userOption.text = userUnitsCase[index][0][index2];
testSelect.add(userOption);
}
userSelects[index] = testSelect;
console.log("userSelects " + userSelects );
}
}
for an example, my test subdomain
https://twliste.deutschritter.eu/offiziersliste/
the first button show what I mean.
//edit i forget to post a code
// Global Variable
var sfgID = "sfg";
var counter = 0; // count fot hte sfgID
var supCounter = 0; // count for the supID
var supZeilenCounter = 0; // count the row in the table for the user unit
var testCounter = 0;
var sfgSupGroup = 5; //sup Tables
var sfgSupMembergroupe = 5; //Table rows
// Global URL
var getUserInformationURL = "https://twliste.deutschritter.eu/offiziersliste/php_interface/get_user_info.php";
var userSafe = []; // save all user with user informations
var userUnitsCase = []; // save all userUnits,
var userSelects = []; // save userSelects Index == userSafe Array Index
What I am trying to achieve is to set the placeholder of an input field dynamically. I have an input where I say how many inputs I want to render in the form. On that created inputs I set an onchange event:
function inputOnchange (){
setTimeout(function(){
var createdInputs = document.querySelectorAll("*[class^='createInput']");
createdInputs.forEach( function(item){
item.onchange = function() {
changeFormPlaceholder();
}
})
}, 200);
}
As you see it runs an function when the onchange event is triggered below the function:
function changeFormPlaceholder(){
var inputs = document.querySelector('.formFieldInputs');
var num = 0;
var valueArray = {};
inputs.childNodes.forEach( function(input){
var inputValue = input.value;
var name = 'value' + num++;
valueArray[name] = inputValue;
})
for( var newPlaceholder in valueArray ){
if(valueArray.hasOwnProperty(newPlaceholder)){
console.log("newPLH", newPlaceholder, valueArray[newPlaceholder])
var form = document.querySelectorAll("*[class^='exitIntentInput']");
for(var i = 0; i < form.length; ++i){
// console.log("aaraay", form[i].placeholder);
form[i].placeholder = valueArray[newPlaceholder];
}
}
}
}
Now It changes only on the last input field and sets all input field to the second value.
So how can I change them individually?
Here is an FIDDLE
Type in something in the inputs on the sidebar you will see them appear on the right and now change the input value on the left you see my issue
You run a for loop in the other for loop,
for( var newPlaceholder in valueArray ){
if(valueArray.hasOwnProperty(newPlaceholder)){
console.log("newPLH", newPlaceholder, valueArray[newPlaceholder])
var form = document.querySelectorAll("*[class^='exitIntentInput']");
for(var i = 0; i < form.length; ++i){
// console.log("aaraay", form[i].placeholder);
form[i].placeholder = valueArray[newPlaceholder];
}
}
}
and when the second time of the outer for loop, the new Placeholdee="value1",
for(var i = 0; i < form.length; ++i)
// console.log("aaraay", form[i].placeholder);
form[i].placeholder = valueArray[newPlaceholder];
}
then the inner loop will set placeholder of all indexes of form to valueArray["value1"], the last value of inputs.
The simplest way to solve this problem is that declarie var valueArray as an array but object.
Thus no need to run twice for loops.
Code as follows:
function changeFormPlaceholder(){
var inputs = document.querySelector('.formFieldInputs');
var num = 0;
var valueArray = [];
inputs.childNodes.forEach( function(input){
var inputValue = input.value;
var name = 'value' + num++;
valueArray.push(inputValue);
})
var form = document.querySelectorAll("*[class^='exitIntentInput']");
for(var i = 0; i < form.length; ++i){
// console.log("aaraay", form[i].placeholder);
form[i].placeholder = valueArray[i];
}
}
I have to fetch data from the PHP web service in an array and then display it on HTML page using JavaScript. I have used a for loop to do so. But it doesn’t render proper output. Due to innerHTML the output gets replaced. Please help with your suggestions. Here is my code:
function jsondata(data){
alert("JSONdata");
var parsedata = JSON.parse(JSON.stringify(data));
var main_category = parsedata["main Category"];
for (var i = 0; i <= main_category.length; i++) {
menu = JSON.parse(JSON.stringify(main_category[i]));
menu_id[i] = menu['mcatid'];
menu_title[i] = menu['mcattitle'];
menu_img[i] = menu['mcatimage'];
pop_array.push(menu_id[i], menu_title[i], menu_img[i]);
//alert(pop_array);
for (var i = 0; i < main_category.length; i++) {
alert("for start");
var category = document.createElement("li");
document.getElementById("mylist").appendChild(category);
//document.getElementById("mylist").innerHTML='<table><tr><td>'+pop_array[i]+'</td></tr></table>';
document.write(pop_array.join("<br></br>"));
alert("for end");
}
}
}
Although I don't get why pop_array was used here but I assume that you are trying to display the category info as a li tag.
You should set category.innerHTML instead of document.getElementById("mylist").innerHTML.
function jsondata(data){
var parsedata = JSON.parse(JSON.stringify(data));
var main_category = parsedata["main Category"];
for (var i = 0; i < main_category.length; i++) {
var menu = main_category[i];
var category = document.createElement("li");
category.innerHTML = menu['mcattitle']; // construct your own html here
document.getElementById("mylist").appendChild(category);
}
}
I am using CRM Online 2013.
I am trying to remove 3 values from an optionset under a certain condition.
The optionset has six options by default: they are listed at the top of my JS code below.
When I run my code, the correct amount of options appear; but they all say undefined.
Here is what I have at the moment:
var customer = 100000000;
var partner = 100000001;
var partnerCustomer = 100000002;
var customerAndBeta = 100000003;
var partnerAndBeta = 100000004;
var partnerCustomerAndBeta = 100000005;
function populateBetaOptionSet(beta) {
var options = Xrm.Page.getAttribute("intip_websiteaccess").getOptions();
var pickListField = Xrm.Page.getControl("intip_websiteaccess");
for(i = 0; i < options.length; i++)
{
pickListField.removeOption(options[i].value);
}
if (beta == false) {
pickListField.addOption(customer);
pickListField.addOption(partner);
pickListField.addOption(partnerCustomer);
}
pickListField.addOption(customerAndBeta);
pickListField.addOption(partnerAndBeta);
pickListField.addOption(partnerCustomerAndBeta);
}
This is being called from another function which is wired up to a separate field's onchange event. I am sure this is working correctly as I am getting the correct beta value through when it is called.
I am removing all the options before re-adding them to avoid duplicates.
Any idea what I am doing wrong here/or know of a better way of doing this?
Re-wrote your function to match the criterion. The option is an object with both text and value. This is why you see undefined (missing text);
So instead of
var customer = 100000000
it needs to be
var customer = { value : 100000000 , text : "Customer" };
The code below saves each option in global scope and uses it each time you call populateBetaOptionSet
function populateBetaOptionSet(beta) {
var xrmPage = Xrm.Page;
var pickListField = xrmPage.getControl("intip_websiteaccess");
var options = pickListField.getOptions();
//save all options
if (!window.wsOptions)
{
window.wsOptions = {};
wsOptions.customer = pickListField.getOption(100000000);
wsOptions.partner = pickListField.getOption(100000001);
wsOptions.partnerCustomer = pickListField.getOption(100000002);
wsOptions.customerAndBeta = pickListField.getOption(100000003);
wsOptions.partnerAndBeta = pickListField.getOption(100000004);
wsOptions.partnerCustomerAndBeta = pickListField.getOption(100000005);
}
//clear all items
for(var i = 0; i < options.length; i++)
{
pickListField.removeOption(options[i].value);
}
if (beta == false) {
pickListField.addOption(wsOptions.customer);
pickListField.addOption(wsOptions.partner);
pickListField.addOption(wsOptions.partnerCustomer);
}
pickListField.addOption(wsOptions.customerAndBeta);
pickListField.addOption(wsOptions.partnerAndBeta);
pickListField.addOption(wsOptions.partnerCustomerAndBeta);
}
Example use Xrm.Page.getControl(..).addOption :
var low = {value : 100000000, text : "Low"};
var medium = {value : 100000001, text : "Medium"};
var high = {value : 100000002, text : "High"};
var pickList = Xrm.Page.getControl("control_name");
var options = pickList.getOptions();
for (var i = 0; i < options.length; i++)
pickList.removeOption(options[i].value);
pickList.addOption(low);
pickList.addOption(medium);
pickList.addOption(high);
I would like to iterate over a IndexedDB objectStore, get the results and populate this select box.
This is my HTML
<tr>
<td>
<select id="opt" name="opt"></select>
</td>
</tr>
This is my JavaScript
function populateOptions() {
var options = [ "1", "2", "3", "4", "5"];
var opt = document.getElementById("opt");
for (var i = 0; i < options.length; i++) {
var option = document.createElement("option");
option.value = options[i];
var optionText = document.createTextNode(options[i]);
option.appendChild(optionText);
opt.appendChild(option);
}
}
populateOptions();
Try the following:
var dbreq = indexeddb.open("db");
dbreq.onsuccess = function (conn){
var trans = dbreq.result.transaction(["objectstore"]);
var obj = trans.objectStore("objectstore");
var cursor = obj.openCursor();
cursor.onsuccess = function (e) {
if (!cursor.result) {
var opt = document.getElementById("opt");
var option = document.createElement("option");
option.value = cursor.result.value;
var optionText = document.createTextNode(cursor.result.value);
option.appendChild(optionText);
opt.appendChild(option);
cursor["continue"]()
} else {
// cursor ended
}
}
Or use my linq2indexeddb library and do it like this:
var db = linq2indexedDB("db");
db.linq.from("objectstore").select.then(null, null, function(e){
var opt = document.getElementById("opt");
var option = document.createElement("option");
option.value = e.data;
var optionText = document.createTextNode(e.data);
option.appendChild(optionText);
opt.appendChild(option);
});
for more information about indexeddb I can reffer to my blog. Here I frequently post information about the indexedDB API.
In html :
<body onload="load()">
In javascript :
function load(){
populateOptions();
}
or shortly :
<body onload="populateOptions()">