Getting value of field with Javascript/jQuery - javascript

This is my page:
http://bryntum.com/examples/gantt-latest/examples/basic/basic.html
I want to get current value of Start and Finish date.
( I will later implement a button, that user can press and then it will get all dates and post them somewhere). At the moment I just need somehow to get the date values.
At first the values are loaded from XML, but you can change the values manually.
I tried looking into source code, but was not able to get the field IDs etc.
So how I can access those fields with JS?

In case you're still looking for JS solution:
I couln't use Jquery, does the server support it?
By using JS, since the cells do not have an ID, you can access your fields by class name:
document.getElementsByClassName("x-grid-cell-inner ");
And than iterating trough the returned array.
Complete code:
var data = document.getElementsByClassName("x-grid-cell-inner ");
var mark = 0;
var out = "";
var patt=/\d\/\d/;
for (i in data) {
var txt = new String(data[i].innerHTML);
if (patt.test(txt)) {
if (mark == 0) {
out += "start: "+txt+" ";
mark = 1;
} else {
mark = 0;
out += "end: "+txt+" ";
}
}
}

It would be totally wrong to do this with jquery - It's an Extjs component with really good documentation.
Gnt.panel.Gantt has a getStart method:
Method to get a the current start date of the scheduler view
and a getEnd method:
Method to get a the current end date of the scheduler view
http://bryntum.com/docs/#!/api/Gnt.panel.Gantt
Edit:
Try getTaskStore, then getById on the store witch will return a Task that has a StartDate and EndDate fields.

unfortunately, there's no unique id on the divs so you can't access them. but they seem to have unique class="" values:
class="x-grid-cell x-grid-cell-startdatecolumn-1011"
class="x-grid-cell x-grid-cell-enddatecolumn-1014"
create a javascript like this
document.getElementsByClassName("x-grid-cell x-grid-cell-enddatecolumn-1014")
to access them and then you can get their start and end dates

Related

Save and load full html select in cookie/localStorage

There have been previous questions surrounding this, however I want to know if its possible to save the whole configuration of the html select in a cookie/localStorage. By the whole configuration I mean all of the options that are currently in the select, and which option is selected.
And then load this configuration back from the cookie.
From previous questions, I currently save the select element using an onChange listener, which saves the element like:
$('#chosen-url').on("change", function () {
saveToBrowserCookies("settings_select", this);
});
function saveToBrowserCookies(key, value) {
document.cookie = key + "=" + value + "; path=/";
}
And then load the select like so (on initialization):
var savedSelect = getFromBrowserCookies("settings_select");
if (savedSelect) {
var select = document.getElementById("chosen-url");
select.value = savedSelect;
}
function getFromBrowserCookies(key) {
var cookies = {}
var all = document.cookie;
var value = null;
if (all === "") { return cookies }
else {
var list = all.split("; ");
for (var i = 0; i < list.length; i++) {
var cookie = list[i];
var p = cookie.indexOf("=");
var name = cookie.substring(0, p);
if (name == key) {
value = cookie.substring(p + 1);
break;
}
}
}
return value;
}
However this doesn't work.
You can save anything in storage or in cookie, as long as it is a string. So in your case I'd recommend:
Get all your select options and currently selected value and create
an object with structure that would be easy to understand.
Stringify this object to JSON form with JSON.stringify.
Save json string in cookie or in LS.
After reload, get saved json, read it with JSON.parse and take all needed information from the object.
Recreate select element and set its chosen value.
I think that controlling select input per se is outside of the scope of this question, especially because we don't know if you are programming in pure js or in some kind of framework. But there are many informations on how to control select inputs on the web, e.g. here you can find decent answers on "how to set select value programatically".
Edit: you edited your question, so I will also add something to my response. You are trying to save whole "this" as cookie. I am not a big fan of jquery, but I guess that "this" is not necessarily the selected value. It may be a whole DOM object or change event maybe. Try logging out "this" and see what it is. You need to save string in a cookie.
Also, check in developer tools if the cookie was saved.
Last but not least, using break in a for loop is questionable. You can try using list.find instead.

Java Script + JSON Parsing and converting into Array

I'm looking for help in converting a particular elements in JSON message to an array using java script at run time. We wanted the script to be more generic. Actually we were trying the following which worked for single element and while changing it to handle for multiple elements at run time its not working.
//Working for Single element - Static
var bodyContext = JSON.parse(response.content)
if(bodyContext.companylist.company.constructor !== Array){
bodyContext.companylist.company = [bodyContext.companylist.company]
}
The above code works and converts Company in JSON message as a Array, Where as the below we tried for multiple elements is not working
//Not Working for multiple elements - dynamic
var bodyContext = JSON.parse(response.content)
var elementName = "";
//Loop runs every time and changes the value of elementName at every iteration
if(bodyContext.elementName .constructor !== Array){ //not working
bodyContext.elementName = [bodyContext.elementName] //Not working
}
instead of looking for "bodyContext.companylist.company" and converting into Array, "bodyContext.elementName" is checked and added to the bodycontext object.
how to handle this. ElementName variable along with JavaScript object is not recognized.
Please help.
you can JSON.parse(data) then you can fetch data from Javascript object like
$.each(Obj,function(key,value){
});
You'll want to use
bodyContext[elementName]
since
bodyContext.elementName
looks for a field in bodyContext named elementName, not the a field named after the value in elementName.
Also, you initialize elementName with "", and this won't match anything on the first iteration.

Get and pass array values from Javascript

Bit of background info - the developer of the system we use has left the company and I've been asked to add a few new features. Needless to say, there's no documentation and to make matters worse I'm an absolute novice so am having to learn as I go along. I'm kind of managing to do most things but have come totally stuck on this problem. For anyone kind enough to help me out, if you could really dumb any answers down that would be great. So, the problem........
HTML page that is dynamically populated with a list of items. For each item in the list there's a checkbox, and for each checkbox that's ticked I need to update a MySQL database. The code that adds the checkboxes to the page is
echo("<td class=\"tableRight\" style=\"width: 5%\"><input type=\"checkbox\" name=\"costume[]\" value=\"".$costume['id']."\" id=\"costume_".$costume['id']."\" onclick=\"tickrow(".$costume['id'].");\" /></td>");
The JavaScript file is loaded in the page head with
<script src=\"costume-list.js\" type=\"text/javascript\"></script>
The button's code that should kick off the database update is
echo("<div class=\"navContainer\" onClick=\"batch_move() \" class=\"navItem\">");
echo("<img src=\"/resource/img/icon/move.png\" border=\"0\" /><br />Batch Move Costumes");
echo("</a></div>");
And finally the JavaScript I've managed to put together is
function batch_move() {
var combo = document.getElementById("cbo_title");
var move_to = combo.options[combo.selectedIndex].text;
var move_to_id = combo.options[combo.selectedIndex].value;
if (move_to.length==0) {
alert("Please select the location you want to move the costumes to.");
return;
}
var resp_move = confirm("Are you sure you want to MOVE the selected costumes to "+move_to+" ?");
if (resp_move==true) {
alert("Lets move em");
window.open ("http://path-to-server/costume/batch-move-costume.php? loc="+move_to_id+"&items="+INeedTheArrayHere,"mywindow","menubar=1,resizable=1,width=350,height=250");
}
}
So what I want to do is first make sure that at least one checkbox is ticked and if it is then get the values of the ticked boxes into an array to pass to the called PHP form. I can manage the update code in the opened form, it's just getting the array to it.
Sorry for long post, but hope that's enough info. If there's anything else you need to know please ask and I'll supply more details. Many thanks
First off, you have my deepest sympathy. It totally sucks to get something like this mess dumped on you. This should help:
var valString = "";
var list = document.querySelectorAll('input[type ="checkbox"]');
for(var node in list) {
if(list[node].checked) {
valString += list[node].name + ',';
//you will need to add a name property when you create the html
//<input type='checkbox' name='dress'>Dress
}
}
This will create a comma-delimited string of all the checked checkbox values that you can send to the server. You can split it into an array on the server side. You will not be able to just drop an array into the GET part of the url like you have 'IneedArrayHere' above, hence the string. Also, if there are too many selections (URLS have a length limit) you will need to switch from GET to POST, which is a whole other issue.
P.S. I highly recommend that you take all those escaped double quotes and make them unescaped single quotes. That sort of thing is done by people who are used to things like SQL varieties where the difference between single and double quotes is significant, but in javascript and most (all?) sever-side languages (like php) the difference is irrelevant.
<script>
function myFunction()
{
var collection =document.getElementById("boxes").getElementsByTagName('INPUT');
var res =[];
for (var x=0; x < collection.length; x++) {
if (collection[x].type.toUpperCase()=='CHECKBOX')
var b = [collection[x].name ,collection[x].checked ] ;
res[res.length] = b;
}
alert(JSON.stringify(res));
}
</script>
<html>
<div id="boxes">
<input type="checkbox" name="1" value="1">eded</input>
<input type="checkbox" name="2" value="2">eded</input>
</div>
<input type="button" onclick="myFunction()" value="ok">
<html>
Now you can simply send the JSON to the server.
many thanks for your answer. I've plugged in your code into the JavaScript and ticked a few of the checkboxes on the form. When the code runs I get the first prompt message, but not the message box with a the value of valString ?.
It's obviously something I'm doing wrong - as I said I'm a complete novice and struggling to get to grips with this system I seem to have inherited (not through choice!)
Current code looks like this, and any pointers to my latest mistake would be much appreciated
function batch_move() {
var combo = document.getElementById("cbo_title");
var move_to = combo.options[combo.selectedIndex].text;
var move_to_id = combo.options[combo.selectedIndex].value;
if (move_to.length==0) {
alert("Please select the location you want to move the costumes to.");
return;
}
var resp_move = confirm("Are you sure you want to MOVE the selected costumes to "+move_to+" ?");
var valString = "";
var list = document.querySelectorAll('input[type ="checkbox"]');
for(var node in list) {
if(list[node].checked) {
valString += list[node].name + ',';
}
}
alert(valString);
if (resp_move==true) {
alert("Lets move em");
window.open ("http://path-to-server/costume/batch-move-costume.php?loc="+move_to_id+"&items=2,3,4,5","mywindow","menubar=1,resizable=1,width=350,height=250");
}
}

Need to get an array of the names of all applicationScope variables

In an application I am working on I need to get a list of the names of all applicationScope variable then I need to cycle through them and filter out the ones starting with a know string say $xyx. I thought that the applicationScope.keySet().
I'm using this code for starter:
var col = applicationScope.keySet();
var itr:java.util.Iterator = col.iterator();
if (itr.hasNext()){
var str:String = itr.next();
dBar.info(str,"Value = ");
}
if I put the variable col in a viewScope it shows a list of all the keys. but when I run the script the values displayed in the dBar info are not the keys but some other information that I'm not sure where it comes from.
I should just be able to iterat through the list of keys, am I missing something?
This code is in the before page loads event
After some poking around and experimenting I got this to work:
var col = applicationScope.keySet();
var itr:java.util.Iterator = col.iterator();
while (itr.hasNext()){
var str:Map.Entry = itr.next();
if (str.substring(0,9) == "$wfsLock_"){
//do stuff
}
}
so I'm now a happy camper.
Although your code works in SSJS, it is not correct (and that's why I don't like SSJS...).
The applicationScope is an implementation of the java.util.Map interface and the keySet() method returns a Set containing the keys in that Map. Every entry is (probably) a String (other data types like integers are actually also valid). The line
var str:Map.Entry = itr.next();
doesn't cast it to a Map.Entry: it doesn't really do anything: str remains a string.
The Map interface also has an entrySet() method that returns the entries (Map.Entry). You can use that to retrieve the key as well as the value:
var it = applicationScope.entrySet().iterator();
while (it.hasNext()) {
var entry = it.next();
print( entry.getKey() + " = " + entry.getValue() );
}
(in this code the print() line will use the toString() method of the key as well as the value to send information to the console)
I see from your code that you've installed my XPages Debug Toolbar. You can also use that to quickly check what's in the scopes and what the actual datatype is.

Type Casting in Apps Script

First time on StackOverFlow!
I am working on building an app that takes in a value through a UI Form TextBox. Once that form is submitted it calls a method that then appends a "/" to the value. The problem is that .append() is not available, because getElementById() returns a GenericWidget object and thus cannot be operated on as if it were a string. I have tried type casting it use .toString() in the var userinput = app.getElementById('input').toString; call and afterward using userinput = userinput.toString.
I have been working with Apps Script for about a month and a few days now and I think that casting to a different type other than GenericWidget would be helpful for anyone who wants to modify a value in a type specific way after passing the value to another method.
I have also done a good bit of research trying to find a solutiong for my problem but like a couple times in the past working with Apps Script I find that since it is a younger language there isn't as much helpful information as there is with languages like Javascript, HTML, and XML. Any help is appreciated.
You have to get the textBox value using e.parameter.textBoxName an then re-assign a value to the textBox. A short example will be more explicit
function doGet(){
var app = UiApp.createApplication();
var textbox = app.createTextBox().setName('txt').setId('txt')
// add other elements, handlers, callBackElements, etc...
}
function changetext(e){
var app = UiApp.getActiveApplication();
var textBoxValue = e.parameter.txt ; // get the value in the text box
var txtBoxWidget = app.getElementById('txt') ; get the widget by its ID
txtBoxWidget.setText(textBoxValue+'/'):// assign the modified value
return app ;// update the UI with new value
}

Categories

Resources