I facing a problem here when using select.Items.Count.
situation 1:
<select id="PrimaryArea" style="width: 100px" required tabindex="6" runat="server">
<option value="A">Item1</option>
<option value="B">Item2</option>
<option value="C">Item3</option>
<option value="D">Item4</option>
</select>
In c#
int PrimaryAreaCount=PrimaryArea.Items.Count // return 4
situation 2: option add programmatically
<select id="SecondaryArea" style="width: 100px" required tabindex="7" runat="server">
</select>
in Javascript: return correctly when check using javascript
var select = document.getElementById("<%= SecondaryArea.ClientID %>");
var js = JSON.stringify(<%= SecondaryTable %>);
var js2 = JSON.parse(js);
var len = js2.length;
var i = 0;
while (i < len) {
var new_option = new Option(js2[i].ref_desc, js2[i].cd);
select.options[select.options.length] = new_option;
i += 1;
}
In C#
int SecondaryAreaCount=SecondaryArea.Items.Count // always return 0
What should I do to get the right answer for SecondaryAreaCount in C#?
If I understand your second scenario correctly, you start with an empty list of items and then add options in JavaScript.
In this case, you can not calculate the correct count in serverside C# code, because the JavaScript will only be executed after the page has been served to the client.
One solution would be to use an additional hidden input to post back the count result.
<input id="SecondaryAreaCount" type="hidden" value="0" />
<script>
// your existing JS loop here ...
var countResult = document.getElementById("SecondaryAreaCount");
countResult.value = i; // var i is select.options.length after the while loop
</script>
Related
I've been banging my head against this for the past several days and have finally broken down and admitted defeat. This is my first project utilizing Google HTML Service, and what I'm trying to do seems simple, but I can't get it to work. Here is what I want to happen...
User interacts with spreadsheet and needs to add additional rows with data
User selects an option from a custom menu item (got this working)
This selection launches an HTML service form (got this working)
User selects the values from two drop down lists and clicks submit
The selected options read read (working kind of...) and passed to the .js (this is where I'm stuck), which will create the rows and place the data.
Below is my code:
Function that launches the HTML Service
function AddAdditionalApplicant() {
var ss = SpreadsheetApp.getActiveSpreadsheet(),
html = HtmlService.createHtmlOutputFromFile('index');
ss.show(html);
}
index.html
<form name="AddApplicant" onsubmit="formSubmit()">
<p><b>What Type?</b></p>
<select name="NumOfApp" id="NumOfApp">
<option value="1">1</option>
<option value="2">2</option>
<option value="Cosigner">Cosigner</option>
</select>
<p><b>How Many?</b></p>
<select name="TypeOfApp" id="TypeOfApp">
<option value="Roommate">Roommate</option>
<option value="Cosigner">Cosigner</option>
</select>
<p></p>
<div>
<!--<input type="submit" class="button redButton" value="Submit" onclick="formSubmit()">-->
<input type="submit" class="button redButton" value="Submit">
</div>
</form>
<script type="text/javascript">
function formSubmit() {
//var a=document.getElementById('NumOfApp').selectedIndex;
//var b=document.getElementById('NumOfApp').options;
//alert("Index: " + b[a].index + " is " + b[a].text);
//var x=document.getElementById('TypeOfApp').selectedIndex;
//var y=document.getElementById('TypeOfApp').options;
//alert("Index: " + y[x].index + " is " + y[x].text);
google.script.run.getValuesFromForm(document.forms[0]);
}
</script>
If you uncomment the lines that are commented out you will see that the values are read correctly. Now, here is where it fails... I attempt to pass the form as an object to the function "getValuesFromFrom" using
google.script.run.getValuesFromForm(document.forms[0]);
Function getValuesFromFrom
function getValuesFromForm(AppForm){
Browser.msgbox("success") /attempt to test and see if the execution gets this far...no go
//var a=AppForm['NumOfApp'].selectedIndex;
//var b=AppForm['NumOfApp'].options;
//Logger.log(b[a])
//
//var x=AppForm.TypeOfApp.selectedIndex;
var type = AppForm.TypeOfApp.options[AppForm.TypeOfApp.selectedIndex].value;
Logger.log(type)
}
Nothing happens... the browser msgBox does not pop up. What am I missing? Also, how can I get the form to close automatically when the "Submit" button is pressed. Any help is greatly appreciated.
EDIT:
After going back and forth with #Sandy Good I realized the "AppForm" variable in the getValuesFromForm function was undefined, which means that the form object was not being passed to the function from the html. I tried another approach, and just attempted to pass a string variable to the function by altering the script portion of the html code like this
var x=document.getElementById('TypeOfApp').selectedIndex;
var y=document.getElementById('TypeOfApp').options;
//alert("Index: " + y[x].index + " is " + y[x].text);
var type=y[x].value
// google.script.run.getValuesFromForm(y[x], b[a]);
google.script.run.withFailureHandler(google.script.host.close)
.getValuesFromForm(type);
This was successful, while this...
var x=document.getElementById('TypeOfApp').selectedIndex;
var y=document.getElementById('TypeOfApp').options;
//alert("Index: " + y[x].index + " is " + y[x].text);
var type=y[x]
// google.script.run.getValuesFromForm(y[x], b[a]);
google.script.run.withFailureHandler(google.script.host.close)
.getValuesFromForm(type);
was not!
So the question remains, what was I doing wrong previously?
EDIT: July 10th...Working code
Function that launches the HTML Service
function AddAdditionalApplicant() {
var ss = SpreadsheetApp.getActiveSpreadsheet(),
html = HtmlService.createHtmlOutputFromFile('index');
ss.show(html);
}
index.html
<form name="AddApplicant" onsubmit="formSubmit(this)">
<p><b>How Many?</b></p>
<select name="NumOfApp" id="NumOfApp">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<p><b>What Type?</b></p>
<select name="TypeOfApp" id="TypeOfApp">
<option value="Roommate">Roommate</option>
<option value="Cosigner">Cosigner</option>
</select>
<p></p>
<div>
<!--<input type="submit" class="button redButton" value="Submit" onclick="formSubmit()">-->
<input type="submit" class="button redButton" value="Submit">
</div>
</form>
<script type="text/javascript">
function formSubmit(argTheFormElement) {
google.script.run
.withFailureHandler(myFailureFunction)
.withSuccessHandler(google.script.host.close)
.getValuesFromForm(argTheFormElement);
}
function myFailureFunction(argError) {
alert("There was an error: " + argError.message);
google.script.host.close();
}
</script>
Function that receives the Form element
function getValuesFromForm(AppFormElement){
var ss = SpreadsheetApp.getActive();
var s = ss.getActiveSheet();
var sname = s.getName();
var num = AppFormElement.NumOfApp
var type = AppFormElement.TypeOfApp
var activeRow = s.getActiveCell().getRow();
var addCell = s.getRange(activeRow,2);
if (type == "Roommate") {
for(var i = 0; i < num; ++i){
AddRoommate(activeRow,addCell,sname,s);
}
}else if (type == "Cosigner"){
for(var i = 0; i < num; ++i){
AddCosigner(activeRow,addCell,sname,s);
}
}
s.setActiveRange(addCell.offset(1,1));
}
Hope this helps someone out!!!
Change your form tag, and add this to the function:
onsubmit="formSubmit(this)"
Then modify your function:
function formSubmit(argTheFormElement) {
Then put the variable argTheFormElement into the google.script.run.function(parameter);
google.script.run.getValuesFromForm(argTheFormElement);
That will pass all input values to the server. The get the values out, you must use the name of the name tag.
var type = AppForm.NumOfApp; //Get NumOfApp value
To make the dialog close, use:
google.script.host.close;
google.script.host.close
On a JSP page I have a following declaration:
<html:select property="filterBookingTargetId" styleClass="input_middle" >
<html:option value="0">-all-</html:option>
<html:options collection="bookTargetTypes" property="key" labelProperty="value"/>
</html:select>
where collection bookTargetTypes is a set of key-value (int, String) pairs implemented in Java as a HashMap and read by a server.
If I could use jQuery, I would implement it similarly to answers present on the Stack discussion here. Unfortunately, I can't; nor can I sort those values before they are uploaded to the server i. e. in Java, on the code level.
The underlying question is, how in pure JavaScript can I refer to bookTargetTypes collection to sort them alphabetically before they are shown on the page?
Example values of "bookTargetTypes" collection, after they are rendered on the page, are shown below:
<html:option value="5">bbb</html:option>
<html:option value="13">ccC</html:option>
<html:option value="1">Aaa</html:option>
[UPDATE]
<script language="javascript">
function sortOptions() {
var options = document.getElementById('myselect').options;
var optionsArray = [];
for (var i = 0; i < options.length; i++) {
optionsArray.push(options[i]);
}
optionsArray = optionsArray.sort(function (a, b) {
return a.innerHTML.toLowerCase().charCodeAt(0) - b.innerHTML.toLowerCase().charCodeAt(0);
});
for (var i = 0; i <= options.length; i++) {
options[i] = optionsArray[i];
}
options[0].selected = true;
}
sortOptions();
</script>
<input type="hidden" name="method" value="listSettlementFiles">
<input type="hidden" name="pageNo" value="">
<input type="hidden" name="countPerPage" value="">
<input type="hidden" name="sc" value="">
<div class="search_bar" id="search" name="search_div">
<table align="center" width="100%">
<tr>
<td align="center">
<LABEL>Name of channels</LABEL>
<select name="filterBookingTargetId" id="myselect" class="input_middle">
<option value="17">Baa</option>
<option value="15">Paa</option>
<option value="2">Saaa</option>
<option value="9">Daaa</option>
<option value="6">Naaa</option>
<option value="1">Eaaa</option>
<option value="14">Sdda</option>
<option value="7">Raaa</option>
<option value="22">Pdddaa</option>
</select>
Well, since you said you can't use jquery or can't modify java code. Here is a pure javascript solution. It would be better if you give an id for your select. You can save the options in an array and then use sort function by comparing first letter charcode of innerHTML inside each option.
in your HTML give an id
<html:select id="myselect" property="filterBookingTargetId" styleClass="input_middle" >
<html:option value="0">-all-</html:option>
<html:options collection="bookTargetTypes" property="key" labelProperty="value"/>
</html:select>
javascript
function sortOptions() {
var options = document.getElementById('myselect').options;
var optionsArray = [];
for (var i = 0; i < options.length; i++) {
optionsArray.push(options[i]);
}
optionsArray = optionsArray.sort(function (a, b) {
return a.innerHTML.toLowerCase().charCodeAt(0) - b.innerHTML.toLowerCase().charCodeAt(0);
});
for (var i = 0; i <= options.length; i++) {
options[i] = optionsArray[i];
}
options[0].selected = true;
}
sortOptions();
click here for Fiddle Demo
You can not refer to bookTargetTypes after the page is rendered.
And if you can not use jQuery, you can only replicate the jQuery behavior using pure javascript.
You can write a onload script which will get triggerred after the page is loaded. In that script you can reorder the options of the particular select element.
In an HTML page i have severals list.
<select name="salut-1358937506000-OK">
<option selected="" value="OK">OK</option>
<option value="OK">NOK</option>
</select>
<select name="salut-1358937582000-OK">
<option selected="" value="OK">OK</option>
<option value="OK">NOK</option>
</select>
...
In javascript, I want to get all select/option list which started by "salut-".
For theses list, i want to compare his name and his selected value.
I know it is possible in jQuery but can't use jquery, only javascript (JSNI with GWT exactly).
Have you an idea?
Thanks!
var selects = document.getElementsByTagName('select');
var sel;
var relevantSelects = [];
for(var z=0; z<selects.length; z++){
sel = selects[z];
if(sel.name.indexOf('salut-') === 0){
relevantSelects.push(sel);
}
}
console.log(relevantSelects);
You can use the getElementsByTagName function to get each SELECT name, for example:
var e = document.getElementsByTagName("select");
for (var i = 0; i < e.length; i++){
var name = e[i].getAttribute("name");
}
Then you can use the following code to get each OPTION for the SELECT, to do any necessary comparisons:
var options = e[i].getElementsByTagName("option")
I'm integrating Postcode anywhere with my web project. I'm using a drop drop for the county/state field. Postcode anywhere returns the name of the County. Can I change the Selected Index when I only have the name? (I'm using a number for the value field which relates to a database field).
I tried the following:
var f = document.getElementById("state_dropdown");
f.options.[f.selectedIndex].text = response[0].County;
I've tried to include the drop down code html here but I can't get it to work properly for some reason.
But of course this just changes the text field for the item in the drop down that is already selected.
I can query the database and find out what ID I have assigned the county but I'd rather not if there is another way.
Loop over the options until you have a match:
for (var i = 0; i < f.options.length; i++) {
if (f.options[i].text == response[0].Country) {
f.options.selectedIndex = i;
break;
}
}
Demo.
I would make a function and loop over the labels:
See: http://jsfiddle.net/Y3kYH/
<select id="country" name="countryselect" size="1">
<option value="1230">A</option>
<option value="1010">B</option>
<option value="1213">C</option>
<option value="1013">D</option>
</select>
JavaScript
function selectElementByName(id, name) {
f = document.getElementById(id);
for(i=0;i<f.options.length;i++){
if(f.options[i].label == name){
f.options.selectedIndex = i;
break;
}
}
}
selectElementByName("country","B");
Just a variation on other answers:
<script type="text/javascript">
function setValue(el, value) {
var sel = el.form.sel0;
var i = sel.options.length;
while (i--) {
sel.options[i].selected = sel.options[i].text == value;
}
}
</script>
<form>
<select name="sel0">
<option value="0" selected>China
<option value="1">Russia
</select>
<button type="button" onclick="setValue(this, 'Russia');">Set to Russia</button>
<input type="reset">
</form>
I have 2 listboxes and when a button is pressed I need to move an option from one to another.
I did this:
HTML
<table border="1" cellpadding="5">
<tr>
<td> Un-Selected <br />
<select multiple="multiple" id="selectBoxOne" size="5" class="selectListBox">
<option value="0" id="multiple0">Option 0</option>
<option value="1" id="multiple1">Option 1</option>
<option value="2" id="multiple2">Option 2</option>
<option value="3" id="multiple3">Option 3</option>
<option value="4" id="multiple4">Option 4</option>
<option value="5" id="multiple5">Option 5</option>
</select>
<br />
<input type="checkbox" id="selectAllFirst" />Select All or Ctrl+Click
</td>
<td>
<div onclick="move('left');">
<< </div>
<div onclick="move('right');"> >></div>
</td>
<td> Selected <br />
<select name="policyCode" multiple="multiple" id="selectBoxSecond" size="5" class="selectListBox"></select>
<br />
<input type="checkbox" id="selectAllSecond" />Select All or Ctrl+Click
</td>
</tr>
</table>
javascript:
// Declare elements
var selectOptions = Array();
selectOptions[0] = "Option 0";
selectOptions[1] = "Option 1";
selectOptions[2] = "Option 2";
selectOptions[3] = "Option 3";
selectOptions[4] = "Option 4";
selectOptions[5] = "Option 5";
// function to move an element from a box to the other
function move(sens)
{
if (sens == "right")
{
var selObj = document.getElementById('selectBoxOne');
var chkAll = document.getElementById("selectAllFirst")
var destination = document.getElementById("selectBoxSecond");
}
else
{
var selObj = document.getElementById('selectBoxSecond');
var chkAll = document.getElementById("selectAllSecond")
var destination = document.getElementById("selectBoxOne");
}
var selectedArray = new Array();
var i;
var count = 0;
if (chkAll.checked == 1)
{
for (i = 0; i<selectOptions.length; i++)
{
selectedArray[i] = i;
}
}
else
{
for (i=0; i<selObj.options.length; i++) {
if (selObj.options[i].selected) {
selectedArray[count] = selObj.options[i].value;
count++;
}
}
}
for (i = 0; i < selectedArray.length; i++)
{
var optionTag = document.createElement("option");
id = selectedArray[i];
optionTag.innerHTML = selectOptions[id];
optionTag.value = id;
optionTag.id = "multiple"+id;
destination.appendChild(optionTag);
var rmv = document.getElementById("multiple"+id);
rmv.parentNode.removeChild(rmv);
}
}
Now: The script works great from moving from left box to the right box. But when I try the other way around it kind of crashes. No error returned but I know for sure is the removal part (if I comment it it works fine... except that it generates duplicates since there is no removal of the moved option).
To be more specific, this 2 lines:
var rmv = document.getElementById("multiple"+id);
rmv.parentNode.removeChild(rmv);
Since there is no error returned, I don't know how to fix this.
That's a very long winded way of doing things! :-)
You can move an option from one select to another simply by assigning it as a child of the other select, e.g.
function move(sens) {
var i, sourceSel, targetSel;
if (sens == 'right') {
sourceSel = document.getElementById('selectBoxOne');
targetSel = document.getElementById('selectBoxSecond');
} else {
sourceSel = document.getElementById('selectBoxSecond');
targetSel = document.getElementById('selectBoxOne');
}
i = sourceSel.options.length;
while (i--) {
if (sourceSel.options[i].selected) {
targetSel.appendChild(sourceSel.options[i]);
}
}
}
will move all the selected options from one to the other. Note that the while loop goes backwards because the options collection is a live NodeList, so as you remove options is shortens the collection. If you go forwards through it you need to update the index and length as you go (so going backward is simpler).
You may want to include some kind of ordering or sorting (e.g. by value or text).
I guess if the selectAll checkbox is checked you'll just move them all, or (preferably) you could use a click listener to select/deselect all the appropriate optoins when it's clicked independent of the move function.
An id has to be unique, or it won't work properly. As you add the new option before removing the original, you get two options with the same id, and you won't find the original option when you want to remove it.
Just swap these three lines around, so that you remove the option before adding the new one. From this:
destination.appendChild(optionTag);
var rmv = document.getElementById("multiple"+id);
rmv.parentNode.removeChild(rmv);
to this:
var rmv = document.getElementById("multiple"+id);
rmv.parentNode.removeChild(rmv);
destination.appendChild(optionTag);