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.
Related
I am new to scripting on photoshop and it seems not all javascript is the same. What I'm trying to do is I have a list of layers that are as follows:
Cat pic 1.jpg
Cat pic 1.jpg copy
Dog pic 1.jpg
Dog pic 1.jpg copy
....
I want to merge the ones that are copies of each other so "Cat pic 1.jpg" and "Cat pic 1.jpg copy" and create one layer from the two which is just "Cat pic 1.jpg".
They are all active and there is no shapes or anything so its just layers. I have about 300 layers and each one is exactly like that. There is a duplicate of each layer and the name has copy at the end. I wrote a script but I don't know how to merge two layers together. My code doesn't work. It is pieced together from someone trying to sort the layers alphabetically.
Basically I had a layer list and I flipped it horizontally and now I need to merge the left half with the right half. The left is without the word 'copy'.
Any help is greatly appreciated guys! Please feel free to ignore all my code I have zero confidence in it.
Thanks in advance!
#target photoshop
var layers = activeDocument.layers;
var layersArray = [];
var len = layers.length;
// store all layers in an array
for (var i = 0; i < len; i++) {
layersArray.push(layers[i]);
}
var layersOrig= [];
for (var i = 0; i < len; i++) {
var cond = myIndexOf(layersArray[i], "copy");
if (cond === -1) {
layersOrig.push(layersArray[i]);
delete layersArray[i];
}
}
layersOrig.sort();
// sort layer top to bottom
layersArray.sort();
for (var i = 0; i < len; i++) {
layersArray[i] = merge(layersOrig[i], layersArray[i];
}
for (i = 0; i < len; i++) {
layersArray[i].move(layers[i], ElementPlacement.PLACEBEFORE);
}
function myIndexOf(array, x){
var n=-1, N=array.length;
while (++n<N && array[n]!==x);
return n<N ? n : -1;
};
Maybe like this?
function main()
{
var layersInfo = getAllLayersNames(); //getting myself an object of layer names and IDs
for (layerName in layersInfo)
{
deselectLayers(); //deselecting all layers first
if (layersInfo[layerName].length == 1) continue; //if there's only one layer in the object: ignore it
for (var i = 0; i < layersInfo[layerName].length; i++)
{
selectById(layersInfo[layerName][i], true); //selecting layers-clones by IDs
}
mergeDown(); //merge down selected layers
activeDocument.activeLayer.name = layerName; //renaming the resulting layer to original layer name
}
/////////////////////////////////////////////////////////////////////////////////////
// functions
function getAllLayersNames()
{
var lyrs = {};
try
{
activeDocument.backgroundLayer;
var layers = 0
}
catch (e)
{
var layers = 1;
};
while (true)
{
ref = new ActionReference();
ref.putIndex(charIDToTypeID('Lyr '), layers);
try
{
var desc = executeActionGet(ref);
}
catch (err)
{
break;
}
var lyr = {};
lyr.name = desc.getString(charIDToTypeID("Nm "));
var nameWithoutCopy = lyr.name.replace(/\scopy.*/, '');
lyr.id = desc.getInteger(stringIDToTypeID("layerID"));
if (lyrs[nameWithoutCopy] == undefined) lyrs[nameWithoutCopy] = [lyr.id]
else lyrs[nameWithoutCopy].push(lyr.id);
layers++;
}
return lyrs
};
function selectById(id, add)
{
var desc1 = new ActionDescriptor();
var ref1 = new ActionReference();
ref1.putIdentifier(charIDToTypeID('Lyr '), id);
desc1.putReference(charIDToTypeID('null'), ref1);
if (add) desc1.putEnumerated(stringIDToTypeID("selectionModifier"), stringIDToTypeID("selectionModifierType"), stringIDToTypeID("addToSelection"));
executeAction(charIDToTypeID('slct'), desc1, DialogModes.NO);
};
function deselectLayers()
{
var desc60 = new ActionDescriptor();
var ref30 = new ActionReference();
ref30.putEnumerated(charIDToTypeID('Lyr '), charIDToTypeID('Ordn'), charIDToTypeID('Trgt'));
desc60.putReference(charIDToTypeID('null'), ref30);
executeAction(stringIDToTypeID('selectNoLayers'), desc60, DialogModes.NO);
};
function mergeDown()
{
var desc11 = new ActionDescriptor();
executeAction(charIDToTypeID('Mrg2'), desc11, DialogModes.NO);
};
}
app.activeDocument.suspendHistory("rename all copies", "main()");
Input > Result:
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>
Following the documentation sample, I'm trying to create a function that searchs for a numerated list in a google document and, if finds it, adds a new item to that list. But I get this error: Cannot find method setListId(string). (line 21, file "test") or, if I change line 21 content (replacing elementContentfor newElement), I get the message: Preparing for execution... and nothing happens. How to fix it?
This is my code:
function test() {
var elementContent = "New item testing"; // a paragraph with its formating
var targetDocId = "1R2c3vo9oOOjjlDR_n5L6Tf9yb-luzt4IxpHwwZoTeLE";
var targetDoc = DocumentApp.openById(targetDocId);
var body = targetDoc.getBody();
for (var i = 0; i < targetDoc.getNumChildren(); i++) {
var child = targetDoc.getChild(i);
if (child.getType() == DocumentApp.ElementType.LIST_ITEM){
var listId = child.getListId();
var newElement = body.appendListItem(elementContent);
newElement.setListId(newElement);
Logger.log("child = " + child);
}
}
}
Following my comment, I tried to play with your script to see what happened and I came up with that code below...
I'm not saying it solves your issue and/or is the best way to achieve what you want but at least it gives a result that works as expected.
Please consider it as a "new playground" and keep experimenting on it to make it better ;-)
function test() {
var elementContent = "New item testing"; // a paragraph with its formating
var targetDocId = DocumentApp.getActiveDocument().getId();
var targetDoc = DocumentApp.openById(targetDocId);
var body = targetDoc.getBody();
var childIndex = 0;
for (var i = 0; i < targetDoc.getNumChildren(); i++) {
var child = targetDoc.getChild(i);
if (child.getType() == DocumentApp.ElementType.LIST_ITEM){
while(child.getType() == DocumentApp.ElementType.LIST_ITEM){
child = targetDoc.getChild(i)
childIndex = body.getChildIndex(child);
Logger.log(childIndex)
i++
}
child = targetDoc.getChild(i-2)
var listId = child.getListId();
Logger.log(childIndex)
var newElement = child.getParent().insertListItem(childIndex, elementContent);
newElement.setListId(child);
break;
}
}
}
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.
We have a dropdown list that is dynamically populated using javascript (below). But it doesn't show in IE7.
This is the code that populates the options:
<script language="javascript" type="text/javascript">
window.onload = function() {
var today= new Date();
var year= today.getFullYear();
var val =0;
t2= 51;
grad_yr = document.getElementById("grad_yr");
grad_yr.options[0] = new Option("Year",val,false,false);
var y=year;
var yy=y;
for (var i=1; i <t2 ; i++) {
grad_yr.options[i] = new Option(y,y);
y=yy-1;
yy--;
}
}
</script>
This is the HTML:
<select name="grad_yr" id="grad_yr"></select>
What could be wrong?
EDIT: Ok, nevermind. Apparently, the list is actually being populated. It's just that we have another javascript that sort of moves the position of the options that's why it looks hidden. Thanks anyway!
You've created a name collision by using the same global variable name for your grad_yr variable and the select element. Comment out the line where you are pulling your grad_yr from the document by ID, as it is unneccessary:
//grad_yr = document.getElementById("grad_yr");
grad_yr.options[0] = new Option("Year", val, false, false);
Or, if you really do need to have a variable reference, just give your variable a different name, like this (or some such):
grad_yrVar = document.getElementById("grad_yr");
grad_yrVar.options[0] = new Option("Year", val, false, false);
...
for (var i = 1; i < t2; i++) {
grad_yrVar.options[i] = new Option(y, y);
y = yy - 1;
yy--;
}
...and it should work.
Try this
var grad_yr = document.getElementById("grad_yr");