fail to create\edit select element with JS - javascript

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.

Related

Add a paragraph or table etc. at Cursor

I have a function for adding the contents of a separate google document at the cursor point within the active document, but I haven't been able to get it to work. I keep getting the "Element does not contain the specified child element" exception, and then the contents gets pasted to the bottom of the document rather than at the cursor point!
function AddTable() {
//here you need to get document id from url (Example, 1oWyVMa-8fzQ4leCrn2kIk70GT5O9pqsXsT88ZjYE_z8)
var FileTemplateFileId = "1MFG06knf__tcwHWdybaBk124Ia_Mb0gBE0Gk8e0URAM"; //Browser.inputBox("ID der Serienbriefvorlage (aus Dokumentenlink kopieren):");
var doc = DocumentApp.openById(FileTemplateFileId);
var DocName = doc.getName();
//Create copy of the template document and open it
var docCopy = DocumentApp.getActiveDocument();
var totalParagraphs = doc.getBody().getParagraphs(); // get the total number of paragraphs elements
Logger.log(totalParagraphs);
var cursor = docCopy.getCursor();
var totalElements = doc.getNumChildren();
var elements = [];
for (var j = 0; j < totalElements; ++j) {
var body = docCopy.getBody();
var element = doc.getChild(j).copy();
var type = element.getType();
if (type == DocumentApp.ElementType.PARAGRAPH) {
body.appendParagraph(element);
} else if (type == DocumentApp.ElementType.TABLE) {
body.appendTable(element);
} else if (type == DocumentApp.ElementType.LIST_ITEM) {
body.appendListItem(element);
}
// ...add other conditions (headers, footers...
}
Logger.log(element.editAsText().getText());
elements.push(element); // store paragraphs in an array
Logger.log(element.editAsText().getText());
for (var el = 0; el < elements.length; el++) {
var paragraph = elements[el].copy();
var doc = DocumentApp.getActiveDocument();
var bodys = doc.getBody();
var cursor = doc.getCursor();
var element = cursor.getElement();
var container = element.getParent();
try {
var childIndex = body.getChildIndex(container);
bodys.insertParagraph(childIndex, paragraph);
} catch (e) {
DocumentApp.getUi().alert("There was a problem: " + e.message);
}
}
}
You want to copy the objects (paragraphs, tables and lists) from the document of 1MFG06knf__tcwHWdybaBk124Ia_Mb0gBE0Gk8e0URAM to the active Document.
You want to copy the objects to the cursor position on the active Document.
You want to achieve this using Google Apps Script.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Modification points:
In your script, appendParagraph, appendTable and appendListItem are used at the 1st for loop. I think that the reason that the copied objects are put to the last of the document is due to this.
var body = docCopy.getBody(); can be put to the out of the for loop.
In your case, I think that when the 1st for loop is modified, 2nd for loop is not required.
When above points are reflected to your script, it becomes as follows.
Modified script:
function AddTable() {
var FileTemplateFileId = "1MFG06knf__tcwHWdybaBk124Ia_Mb0gBE0Gk8e0URAM";
var doc = DocumentApp.openById(FileTemplateFileId);
var docCopy = DocumentApp.getActiveDocument();
var body = docCopy.getBody();
var cursor = docCopy.getCursor();
var cursorPos = docCopy.getBody().getChildIndex(cursor.getElement());
var totalElements = doc.getNumChildren();
for (var j = 0; j < totalElements; ++j) {
var element = doc.getChild(j).copy();
var type = element.getType();
if (type == DocumentApp.ElementType.PARAGRAPH) {
body.insertParagraph(cursorPos + j, element);
} else if (type == DocumentApp.ElementType.TABLE) {
body.insertTable(cursorPos + j, element);
} else if (type == DocumentApp.ElementType.LIST_ITEM) {
body.insertListItem(cursorPos + j, element);
}
}
}
It seems that DocName is not used in your script.
References:
insertParagraph()
insertTable()
insertListItem()
If I misunderstood your question and this was not the result you want, I apologize. At that time, can you provide the sample source Document? By this, I would like to confirm it.

Getting undefined while accessing selected value of drop down

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

Split values by comma separated string in javascript

Here is my issue:
I have RadListBox and I'm trying to get the values and append them so the result would be displayed like that: '1,2,3,4' but I'm getting back : 1,2,3,4,
Does anyone know how can I achieve that?
Problem starts here:
var sbLocationsIDS = new StringBuilder();
for (i = 0; i < LocationIDS.get_items().get_count(); i++) {
sbLocationsIDS.append(LocationIDS.getItem(i).get_value()+ ",");
}
The result: sbLocationsIDS =1,2,3,4, instead of '1,2,3,4'
The Rest of the Code:
function openNewTab(url) {
var captureURL = url;
var win = window.open(captureURL, '_blank');
win.focus();
}
function GetComparisonsReport(sender, args) {
var isValid = Page_ClientValidate('validateComparisons');
if (isValid) { // If its true is going to fire the rest of the code
var SessionID = getUrlVars()["SessionID"];
var companyCodeVal = document.getElementById("<%=hfC.ClientID%>").value;
var LocationIDS = $find("<%=rlbSelectedLocation.ClientID %>");
var CategoriesIDS = $find("<%=rlbSelectedCategory.ClientID %>");
var fileType = $find("<%=rcbFileType.ClientID %>");
var fromFirstPeriod = $find("<%=rdpFromFirstPeriod.ClientID %>");
var toFirstPeriod = $find("<%=rdpToFirstPeriod.ClientID %>");
var fromSecondPeriod = $find("<%=rdpFromSecondPeriod.ClientID %>");
var toSecondPeriod = $find("<%=rdpToSecondPeriod.ClientID %>");;
if (LocationIDS.get_items().get_count() < 0) {
radalert("Please choose locations and select the Add button.<h3 style='color: #ff0000;'></h3>", 420, 170, "Case Global Alert");
return;
}
if (CategoriesIDS.get_items().get_count() < 0) {
radalert("Please choose categories and select the Add button.<h3 style='color: #ff0000;'></h3>", 420, 170, "Case Global Alert");
return;
}
var fromFirstPeriodDateValSelected = fromFirstPeriod.get_dateInput().get_selectedDate().format("yyyy/MM/dd");
var toFirstPeriodDateValSelected = toFirstPeriod.get_dateInput().get_selectedDate().format("yyyy/MM/dd");
var fromSecondPeriodDateValSelected = fromSecondPeriod.get_dateInput().get_selectedDate().format("yyyy/MM/dd");
var toSecondPeriodDateValSelected = toSecondPeriod.get_dateInput().get_selectedDate().format("yyyy/MM/dd");
var fileTypeValSelected = fileType.get_selectedItem().get_value();
var sbLocationsIDS = new StringBuilder();
for (i = 0; i < LocationIDS.get_items().get_count(); i++) {
sbLocationsIDS.append(LocationIDS.getItem(i).get_value()+ ","); // The problem is here!!!
}
var sbCategoriesIDS = new StringBuilder();
for (i = 0; i < CategoriesIDS.get_items().get_count(); i++) {
sbCategoriesIDS.append(CategoriesIDS.getItem(i).get_value() + ",");
}
var ComparisonsURL = (String.format("https://www.test.com/cgis/{0}/reports/ConnectTorptIncidentsCountByLocationInterval.asp?SessionID={1}&locString={2}&catString={3}&FromDate1={4}&&ToDate1={5}&FromDate2={6}&ToDate2={7}&ExportType={8}", companyCodeVal, SessionID, sbLocationsIDS, sbCategoriesIDS, fromFirstPeriodDateValSelected, toFirstPeriodDateValSelected, fromSecondPeriodDateValSelected, toSecondPeriodDateValSelected, fileTypeValSelected));
openNewTab(ComparisonsURL);
}
}
String.format = function () {
// The string containing the format items (e.g. "{0}")
// will and always has to be the first argument.
var theString = arguments[0];
// start with the second argument (i = 1)
for (var i = 1; i < arguments.length; i++) {
// "gm" = RegEx options for Global search (more than one instance)
// and for Multiline search
var regEx = new RegExp("\\{" + (i - 1) + "\\}", "gm");
theString = theString.replace(regEx, arguments[i]);
}
return theString;
}
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
vars[key] = value;
});
return vars;
}
// Initializes a new instance of the StringBuilder class
// and appends the given value if supplied
function StringBuilder(value) {
this.strings = new Array("");
this.append(value);
}
// Appends the given value to the end of this instance.
StringBuilder.prototype.append = function (value) {
if (value) {
this.strings.push(value);
}
}
// Clears the string buffer
StringBuilder.prototype.clear = function () {
this.strings.length = 1;
}
// Converts this instance to a String.
StringBuilder.prototype.toString = function () {
return this.strings.join("");
}
The problem is your loop is appending , always even for the last item in the loop.
You want to append only for all items other than the last. There are multiple ways to do that, simplest being: check if the current element is the last and if so, do not append ,
var sbLocationsIDS = new StringBuilder();
for (i = 0; i < LocationIDS.get_items().get_count(); i++) {
sbLocationsIDS.append(LocationIDS.getItem(i).get_value()); //append only value
if(i != (LocationIDS.get_items().get_count() -1)) { //if not last item in list
sbLocationsIDS.append(","); //append ,
}
}
There are other ways to do it, and depending on what you want to do with the values in the future, these may be pretty useful. (I see that the append in your code is actually a call to join, so this is actually a simpler version)
Add the values of the list to a array and use Array.join:
var select = document.getElementById("locationId");
var options = select.options;
var optionsArray = [];
if(options) {
for (var i=0; i<=options.length; i++) {
//text is the text displayed in the dropdown.
//You can also use value which is from the value attribute of >option>
optionsArray.push(options[i].text);
}
}
var sbLocationsIDS = optionsArray.join(",");
With JQuery, the above code becomes a bit more simple:
var optionsArray = [];
$("#locationId option").each(function(){
optionsArray.push(options[i].text);
});
var sbLocationsIDS = optionsArray.join(",");
Actually, if you decide yo use JQuery, you can use jquery.map:
(idea from Assigning select list values to array)
$(document).ready(function() {
$("#b").click(function() {
var sbLocationsIDS = jQuery.map($("#locationId option"), function(n, i) {
return (n.value);
}).join(",");
alert(sbLocationsIDS);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="locationId">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button id="b">Click</button>

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

Comparing a Variable to an Array Element Not Working [Javascript]

Being new to javascript I have come across an odd issue. I have an array of elements and a variable, I want to compare that variable to all array elements and do something if they match .
Here is the snippet of code:
for (var i=0; i<country_arr.length; i++) {
option_str.options[option_str.length] = new Option(country_arr[i],country_arr[i]);
if(selected_country == country_arr[i]){
option_str.options[i].selected = true;
}
}
The array itself is an array of strings:
var country_arr = new Array("Republic of Ireland", "Northern Ireland");
For whatever reason this does not enter the if statement but oddly enough when i replace:
if(selected_country == country_arr[i])
with:
if(selected_country == "Republic of Ireland")
...it does and works perfectly.
Am I comparing the two elements incorrectly? Any help would be greatly appreciated.
UPDATE - FULL .js FILE:
Full External .js File:
//Create a new array, to contain the list of countries available.
var country_arr = new Array("Republic of Ireland", "Northern Ireland");
//Create a new array to hold a list of counties depending on country selection.
var s_a = new Array();
s_a[0]="";
s_a[1]="Carlow|Cavan|Clare|Cork|Donegal|Dublin|Galway|Kerry|Kildare|Kilkenny|Laois|Leitrim|Limerick|Longford|Louth|Mayo|Meath|Monaghan|Offaly|Roscommon|Sligo|Tipperary|Waterford|Westmeath|Wexford|Wicklow";
s_a[2]="Antrim|Armagh|Down|Dungannon|Derry|Tyrone";
function print_country(country_id, selected_country){
//Given the id of the <select> tag as function argument, it inserts <option> tags
var option_str = document.getElementById(country_id);
option_str.length=0;
option_str.options[0] = new Option('Select Country','');
option_str.selectedIndex = 0;
for (var i=0; i<country_arr.length; i++) {
option_str.options[option_str.length] = new Option(country_arr[i],country_arr[i]);
if(selected_country == country_arr[i]){
option_str.options[i].selected = true;
print_county('county',i);
}
}
}
function print_county(state_id, state_index){
var option_str = document.getElementById(state_id);
option_str.length=0; // Fixed by Julian Woods
option_str.options[0] = new Option('Select County','');
option_str.selectedIndex = 0;
var state_arr = s_a[state_index].split("|");
for (var i=0; i<state_arr.length; i++) {
option_str.options[option_str.length] = new Option(state_arr[i],state_arr[i]);
}
}
The function is called and the variable selected_country is set via a php file using:
<script language="javascript">
var selected = <?php echo json_encode($g_country); ?>;
print_country("country", selected);
</script>
The issue isn't the if statement, but that you have an error elsewhere. This is what's wrong:
option_str.options[option_str.length] = ...
option_str.length is probably not what you meant. Try:
option_str.options[option_str.options.length] = ...
...or better yet:
option_str.options.push(new Option(...));
Here's a working example.

Categories