Getting undefined while accessing selected value of drop down - javascript

In lineItemIds, I am getting the id's of all dropdowns. In the first iteration, I am getting the selected value of the first dropdown, but in remaining iterations, I am getting undefined. Here I am validating dynamically generated dropdowns:
var submitForApproval = function(event) {
var lineItemIds = $('input[name="lineItemIds"]').val();
var ok = true;
var i;
var individualId =lineItemIds.split(",");
for(i = 0; i <= individualId.length; i++) {
alert(individualId[i]);
var value = $("select[id='"+individualId[i]+"'] option:selected").val();
if (value == 'Select' ) {
ok = false;
break;
}
}
if (!ok) {
return;
}
});

replace this line it will work.
var value = $("select[id='"+individualId[i]+"'] option:selected").val();
var value = $("#"+individualId[i]).val();
also check what is in your array using.
console.log(individualId[i]);

Related

Replace placeholder of an input in a dynamic form

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];
}
}

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;
};

Filter a child picklist in CRM 2011

I'm trying to convert javascript code from CRM 4.0 to CRM 2011.
I'm having problems with a picklist filter.
My function is on the onchange of the parent picklist. It works the first time but the second it erase everything from my child picklist.
This is the part where I suppose to reset the picklist
if(!oSubPicklist.originalPicklistValues)
{
oSubPicklist.originalPicklistValues = oSubPicklist.getOptions();
}
else
{
oSubPicklist.getOptions = oSubPicklist.originalPicklistValues;
oSubPicklist.setOptions = oSubPicklist.originalPicklistValues;
}
And this is the part where i remove all the option not related:
oTempArray is an array with the options that i want to keep. If a check the "oSubPicklist.getOptions.length" the value is the same that my original picklist.
for (var i=oSubPicklist.getOptions.length; i >= 0;i--)
{
if(oTempArray[i] != true)
{
Xrm.Page.getControl("new_product").removeOption(i);
}
}
Ideas?
Edit: I solved declaring a global var with the originalPickList in the onLoad event and:
oSubPicklist.clearOptions();
for (var i=0; i< oSubPicklist.originalPicklistValues.length; i++)
{
for (var j=0; j< oDesiredOptions.length; j++)
{
if (i == oDesiredOptions[j])
{oSubPicklist.addOption(oSubPicklist.originalPicklistValues[i]);}
}
}
Your code is not very clear to me: May be you could paste all your function code for better understanding but:
This is how you get the options from PickList in CRM 2011
var myOptionSet = Xrm.Page.ui.controls.get("new_product") //get Control
var optionsSet = myOptionSet .getAttribute().getOptions(); //get Options
preferredTimeOptionSet.clearOptions(); //Clear all options
//Create a new Option
var opt1 = new Option();
opt1.text = "one";
opt1.value = 1;
//Add Option
myOptionSet.addOption(opt1);
//Remove Option
myOptionSet.removeOption(1);
Good Example here
Here is another way to do Parent/Child picklists:
function dynamicDropdown(parent, child) {
filterPicklist(parent, child);
}
function parentListFilter(parent, id) {
var filter = "";
if (getParentCode(parent) != "") {
filter = getParentCode(parent);
} else {
// No [ ] match
}
return filter;
}
function filterPicklist(parent, child) {
var parentList = Xrm.Page.getAttribute(parent).getValue();
var childListControlAttrib = Xrm.Page.getAttribute(child);
var childListOptions = childListControlAttrib.getOptions();
var childListControl = Xrm.Page.getControl(child);
var codeToFilterListOn = parentListFilter(parent, parentList);
if (codeToFilterListOn != "") {
childListControl.clearOptions();
for (var optionIndex in childListOptions) {
var option = childListOptions[optionIndex];
// Ignore xx and check for Match
if (option.text.substring(0, 2) != "xx" && option.text.indexOf(codeToFilterListOn) > -1) {
childListControl.addOption(option);
}
}
} else {
// Didn't match, show all?
}
}
function getParentCode(parent) {
//Get Parent Code Dynamically from inside [ ]
var filter = "";
var parentValue = Xrm.Page.getAttribute(parent).getText();
if (parentValue && parentValue.indexOf("]") > -1) {
var parentCode = parentValue.substring(parentValue.indexOf("[") + 1, parentValue.indexOf("]"));
if (parentCode) {
filter = parentCode + " | ";
} else {}
}
return filter;
}
See more here: Parent/Child

Dynamically Change Option Set Values in CRM

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);

fail to create\edit select element with JS

i am trying to create a select element with JS or even edit an existing one yet i seem to be missing something.
this is done in Joomla if this matters.
this is my code:
var option = document.createElement("option");
var select = document.createElement("select");
select.setAttribute("id", "chooseCat");
for(int i=0;i<LevelNames.Length;i++)
{
option.innerHTML = LevelNames[i];
option.setAttribute("value",LevelIds[i]);
document.getElementById("cat_chooser").appendChild(option);
document.getElementById("cat_chooser").options.add(option);
}
select.onchange=function()
{
CreateDDL(this.options[this.selectedIndex].value);
}
var test = document.getElementById("cat_chooser");
test.appendChild(select);
document.add(select);
document.appendChild(select);
this is all the ways i tried doing that.
cat_chooser is a SELECT added manualy to the page.
any help?
EDIT:
this is the whole code :
<script language=\"javascript\" type=\"text/javascript\">
//definitions
var LevelNames = new Array();
var LevelIds = new Array();
boolean isFirstRun = true;
//this functions create a Drop Down List
function CreateDDL(pid=null){
//pass arrays for client side, henceforth : var id,var parent_it, var title
<?php echo "\n".$id."\n".$parent_id."\n".$title."\n\n";?>
if(pid){
}
if(isFirstRun)
{
for(int i=0; i < id.length;i++)
{
//if category has no parent
if(parent_id[i] == "1")
{
LevelIds.push(id[i]);
LevelNames.push(title[i]);
}
}
}
else{
for(int i=0; i < id.length;i++)
{
//if is a son of our target?
if(parent_id[i] == pid)
{
LevelIds.push(id[i]);
LevelNames.push(title[i]);
}
}
}
//finished first run
isFirstRun=false;
//create the actuall drop down
//var option = document.createElement("option");
var select = document.createElement("select");
select.setAttribute("id", "chooseCat");
for(var i=0;i<LevelNames.length;i++)
{
var option = new Option(/* Label */ LevelNames[i],
/* Value */ LevelIds[i] );
select.options.add(option);
}
select.onchange=function()
{
CreateDDL(this.options[this.selectedIndex].value);
}
var test = document.getElementById("cat_chooser");
test.appendChild(select);
//document.add(select);
//document.appendChild(select);
document.body.appendChild(select);
}
CreateDDL();
</script>
JavaScript is not Java. You cannot use int or boolean to declare variables. Instead, use var.
JavaScript is not PHP. You cannot define a default value using function createDDL(pid=null)
The .add method is only defined at the HTMLSelectElement.options object.
.appendChild should be used on document.body, not document, because you want to add elemetns to the body, rather than the document.
Working code, provided that <?php .. ?> returns valid JavaScript objects.
<script language="javascript" type="text/javascript"> //No backslashes..
//definitions
var LevelNames = new Array();
var LevelIds = new Array();
var isFirstRun = true;
//this functions create a Drop Down List
function CreateDDL(pid) {
if(typeof pid == "undefined") pid = null; //Default value
//pass arrays for client side, henceforth : var id,var parent_it, var title
<?php echo "\n".$id."\n".$parent_id."\n".$title."\n\n"; ?>
if (pid) {
}
if (isFirstRun) {
for (var i = 0; i < id.length; i++) {
//if category has no parent
if (parent_id[i] == "1")
{
LevelIds.push(id[i]);
LevelNames.push(title[i]);
}
}
} else {
for (var i = 0; i < id.length; i++) {
//if is a son of our target?
if (parent_id[i] == pid) {
LevelIds.push(id[i]);
LevelNames.push(title[i]);
}
}
}
//finished first run
isFirstRun = false;
//create the actuall drop down
//var option = document.createElement("option");
var select = document.createElement("select");
select.setAttribute("id", "chooseCat");
for (var i = 0; i < LevelNames.length; i++) {
var option = new Option(/* Label */ LevelNames[i],
/* Value */ LevelIds[i]);
select.options.add(option);
}
select.onchange = function () {
CreateDDL(this.options[this.selectedIndex].value);
}
var test = document.getElementById("cat_chooser");
test.appendChild(select);
//document.add(select);
//document.appendChild(select);
document.body.appendChild(select);
}
CreateDDL();
</script>
You need to create a new element and append it in each iteration. Currently, the entire for loop append data to the same option.
Also, in the for loop statement, you typecast the i variable, which you can't do in JavaScript.

Categories