Javascript not working in Livecycle - javascript

I have JavaScript that works in JSFiddle but not in LiveCycle Designer ES3. What I'm trying to do is have the field of a drop down list change background color when an option other than the default option is selected (on change).
function BackgroundChange(ddl) {
var value = ddl.srcElement.options[ddl.srcElement.selectedIndex].value;
var positionddlist = document.getElementById('positionddlist');
// 99 is the value assigned to the default option
if (value !== "99") {
alert('Changes from default values require comment.');
document.getElementById('positionddlist').style.backgroundColor = "orange";
} else {
document.getElementById('positionddlist').style.backgroundColor = "";
}
}
Suggestions?

I'm afraid I have some bad news for you. The DOM code available to you in LiveCycle Designer is not an HTML DOM, so it doesn't support the same methods and properties. In this case, there is no srcElement property, nor is there a getElementById method.
The list of properties and methods that are available are outlined in the [LiveCycle Designer Scripting Reference][1].
The easiest way to to set the border color is to pass in the object and then set the value using fillColor, as in:
DropDownList1.fillColor = "255,102,0";
Personally, I rely a lot on LiveCycle Designer's object assist to guide me through an object's properties.

You can write this script directly "on" the Drop Down object under the "Change" event. When writing script "on" an object, the keyword this becomes bound to the object. You could use the following:
if(this.rawValue!="99"){
//this.fillColor should also work
this.border.fill.color.value = "255,255,0";
}
else{
this.border.fill.color.value = "0,0,0";
}
If you are writing a script object function, simply pass in the XFA object as an input parameter:
function changeDropDownFill(dropDown){
if(this.rawValue!="99"){
//this.fillColor should also work
dropDown.border.fill.color.value = "255,255,0";
}
else{
dropDown.border.fill.color.value = "0,0,0";
}
}
And call it from the Change event like so: nameOfYourScriptObject.changeDropDownFill(this);

Related

How to disable a button click in JavaScript? [duplicate]

I’ve read that you can disable (make physically unclickable) an HTML button simply by appending disable to its tag, but not as an attribute, as follows:
<input type="button" name=myButton value="disable" disabled>
Since this setting is not an attribute, how can I add this in dynamically via JavaScript to disable a button that was previously enabled?
Since this setting is not an attribute
It is an attribute.
Some attributes are defined as boolean, which means you can specify their value and leave everything else out. i.e. Instead of disabled="disabled", you include only the bold part. In HTML 4, you should include only the bold part as the full version is marked as a feature with limited support (although that is less true now then when the spec was written).
As of HTML 5, the rules have changed and now you include only the name and not the value. This makes no practical difference because the name and the value are the same.
The DOM property is also called disabled and is a boolean that takes true or false.
foo.disabled = true;
In theory you can also foo.setAttribute('disabled', 'disabled'); and foo.removeAttribute("disabled"), but I wouldn't trust this with older versions of Internet Explorer (which are notoriously buggy when it comes to setAttribute).
to disable
document.getElementById("btnPlaceOrder").disabled = true;
to enable
document.getElementById("btnPlaceOrder").disabled = false;
It is an attribute, but a boolean one (so it doesn't need a name, just a value -- I know, it's weird). You can set the property equivalent in Javascript:
document.getElementsByName("myButton")[0].disabled = true;
Try the following:
document.getElementById("id").setAttribute("disabled", "disabled");
The official way to set the disabled attribute on an HTMLInputElement is this:
var input = document.querySelector('[name="myButton"]');
// Without querySelector API
// var input = document.getElementsByName('myButton').item(0);
// disable
input.setAttribute('disabled', true);
// enable
input.removeAttribute('disabled');
While #kaushar's answer is sufficient for enabling and disabling an HTMLInputElement, and is probably preferable for cross-browser compatibility due to IE's historically buggy setAttribute, it only works because Element properties shadow Element attributes. If a property is set, then the DOM uses the value of the property by default rather than the value of the equivalent attribute.
There is a very important difference between properties and attributes. An example of a true HTMLInputElement property is input.value, and below demonstrates how shadowing works:
var input = document.querySelector('#test');
// the attribute works as expected
console.log('old attribute:', input.getAttribute('value'));
// the property is equal to the attribute when the property is not explicitly set
console.log('old property:', input.value);
// change the input's value property
input.value = "My New Value";
// the attribute remains there because it still exists in the DOM markup
console.log('new attribute:', input.getAttribute('value'));
// but the property is equal to the set value due to the shadowing effect
console.log('new property:', input.value);
<input id="test" type="text" value="Hello World" />
That is what it means to say that properties shadow attributes. This concept also applies to inherited properties on the prototype chain:
function Parent() {
this.property = 'ParentInstance';
}
Parent.prototype.property = 'ParentPrototype';
// ES5 inheritance
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
function Child() {
// ES5 super()
Parent.call(this);
this.property = 'ChildInstance';
}
Child.prototype.property = 'ChildPrototype';
logChain('new Parent()');
log('-------------------------------');
logChain('Object.create(Parent.prototype)');
log('-----------');
logChain('new Child()');
log('------------------------------');
logChain('Object.create(Child.prototype)');
// below is for demonstration purposes
// don't ever actually use document.write(), eval(), or access __proto__
function log(value) {
document.write(`<pre>${value}</pre>`);
}
function logChain(code) {
log(code);
var object = eval(code);
do {
log(`${object.constructor.name} ${object instanceof object.constructor ? 'instance' : 'prototype'} property: ${JSON.stringify(object.property)}`);
object = object.__proto__;
} while (object !== null);
}
I hope this clarifies any confusion about the difference between properties and attributes.
It's still an attribute. Setting it to:
<input type="button" name=myButton value="disable" disabled="disabled">
... is valid.
If you have the button object, called b: b.disabled=false;
I think the best way could be:
$("#ctl00_ContentPlaceHolder1_btnPlaceOrder").attr('disabled', true);
It works fine cross-browser.
<button disabled=true>text here</button>
You can still use an attribute. Just use the 'disabled' attribute instead of 'value'.

creating Vanilla JS equivalent css method of jQuery

I am trying to create a function like the function of jQuery which changes the style of an HTMLElement, probably you have seen it somewhere:
$("button").css("color", "red");
which is pretty handy, so here is what I've tried:
function $(selector, parent=document){
return parent.querySelector(selector);
}
so the above code is the code of the function $ which grabs an HTMLElement from the DOM,this seems to work perfectly.
Now, the next step for me is to define the $ function methods and properties, so the method I want to create is the css method as seen in the previous example:
$.css = function(style, value){
this[style] = value;
}
now after testing the css method it's not working (and of course it will never work, but I'm just trying to deliver my question idea for you).
I know a lot about object-oriented programming in JavaScript, I am comfortable with it, so I have no problem if you posted any answer, I will try my best to understand it.
I've tried a lot to understand what's the magic that the jQuery developers made to create this method.
What do you think the best approach to make it? what about mixins, what if I wanted other functions and not just "$" to inherit this "css" method?
To modify styles, you need to set a CSS property of the style declaration object of an element. For example:
elm.style.color = 'red';
You need to modify your $.css to access the current element(s) in the collection, and access their .style[propertyName] property.
You can put the collection onto a property of the instance, and make sure to put the css method as a prototype of the class:
function collection (selector, parent = document) {
this.elms = parent.querySelectorAll(selector);
}
collection.prototype.css = function(prop, value) {
for (const elm of this.elms) {
elm.style[prop] = value;
}
}
const $ = (...args) => new collection(...args);
$("button").css("color", "red");
<button>a button</button>
<button>a button</button>
Because your $ doesn't use new, you'll either need it to return an instance of a different class (as in the code above), or always use new when calling it, or have $ return its instance created via Object.create, or something like that. There are various methods.
Not sure if this is what you're after, but you could just apply the style inline?
var elem = document.querySelector('#some-element');
//set color to red
elem.style.color = 'red';
//set the background color to a light gray
elem.style.backgroundColor = '#e5e5e5';
//set the height to 225px
elem.style.height = '225px';

Value is undefined when element is obtained with jQuery

Below is the code where I obtain my input element with jQuery:
var txt = $(tableRow).find('input:text');
if (txt.value == null) {
//TO DO code
}
and here's how I do it with pure JavaScript
var txt = document.getElementById('txtAge');
if (txt.value == null) {
//TO DO code
}
With the first way the value of the txt is undefined. But with the second way the value is what's inside the input element. Now more interesting is, on the bottom-right pane of the Mozilla Firebug if I scroll down to the "value" of the txt I can see it there, both ways.
I know I can simply say $(txt).val(), but I also want to understand why I can't access the value of an element if it's been selected by jQuery. Isn't jQuery just a library of JavaScript functions?
.value is not part of the jquery api. You should use .val() instead:
var txt = $(tableRow).find('input:text');
if (txt.val() == "") {
//TO DO code
}
A dom object and a jquery dom object are not exactly the same. In fact, you can open the Developer tools (in webkit) or Firebug (Firefox) to check what are they in the inside. Jquery holds more information (actually, it contains an instance of the dom that it's representing). So, if you wanted to use .value, you need to call the "generic" dom object from the jquery object, and then use .value.
jQuery selects DOM elements using various native and non-native techniques and places them all in it’s own array-like instance that also wraps them in their own API. jQuery doesn’t "extend" native DOM properties or methods, so you will need to target the DOM node to do that.
Think of it like this:
var node = document.getElementById('txtAge'); // the DOM node
var txt = $('#txtAge'); // the same node wrapped in a jQuery object/API
Since jQuery object holds an array-like collection of DOM nodes, so you can access the first element by doing:
txt[0] // same as node
But it’s generally recommended that you use the .get() method:
txt.get(0)
Another more jQuery-way to do what you want is to iterate through a jQuery collection using .each():
$(tableRow).find('input:text').each(function() {
// "this" in the each callback is the DOM node
if ( this.value == null ) {
// Do something
}
});
.find() will return an arry-like object. If you're sure that there's one, and one only, element matching your query, you could do
var txt = $(tableRow).find('input:text')[0].value;
That's not very jQuery-like, so to speak, more like a mismatch of both jQuery and DOM methods, but it'll get what you want. Also, since you show, as a DOM example, var txt = document.getElementById('txtAge');, this could be rewritten in jQuery as
var txt = $('#txtAge')[0];
var x = $(tableRow).find('input:text');
It's an jquery object .
`x.value`
There is no property value in jquery object . So it returns undefined.
x.val() is a method you can use for get the value of an element.

Moving inline code into function, with object name generation

I am customizing Denis Gritcyuk's Popup date picker.
This pop-up script uses inline Javascript in a href link, to set the selected date into the input field, in the parent window, that is was called for. An example URL looks like:
<a href="javascript:window.opener.document.formname.field.value='03-10-2011';
window.close();">3</a>
The input field name, (e.g. document.formname.field), is passed to the script as a string parameter.
I would like to add things done when that link is clicked (e.g. change background color of field, set flag, etc.). So while this DOES work, it's getting ugly fast.
<a href="javascript:window.opener.document.formname.field.value='03-10-2011';
window.opener.document.formname.field.style.backgroundColor='#FFB6C1';
window.close();">3</a>
How would I move these inline commands into a JS function? This would give me much cleaner URLs and code. The URL would now look something like
3
with a function like (this example obviously does NOT work):
function updateField (str_target, str_datetime) {
var fieldName = "window.opener" + str_target;
[fieldName].value = str_datetime;
[fieldName].style.backgroundColor = '#FFB6C1';
// Set flag, etc.
window.close();
}
So any suggestions on how this can be done, please?
I'd prefer to hide the dom path tracing back from the current window back to the opener. It's appropriate to bake that into the function since the function will always be used in the context of that child popup. Then your function call is cleaner and more readable. Obviously, replace "myField" with the ID of the field you're intending to update.
3
function updateField ( str_date, str_fieldname ) {
var fieldToUpdate = document.getElementById( str_fieldname );
fieldToUpdate.value = str_date;
fieldToUpdate.style.backgroundColor = '#FFB6C1';
// Set flag, etc.
window.close();
}
You're acessing the property incorrectly. Try:
function updateField (str_target, str_datetime) {
var fieldName = window.opener;
str_target = str_target.split('.');
for (var i = 0; i < str_target.length; i++)
fieldName = fieldName[str_target[i]];
fieldName.value = str_datetime;
fieldName.style.backgroundColor = '#FFB6C1';
// Set flag, etc.
window.close();
}
The bracket notation ([]) is only used for properties of objects, not objects themselves. If you found my post helpful, please vote for it.
You can build a string and evaluate it as code using the eval function, but I would recommend against it.
There are a couple of things wrong with your code:
You cannot use the [] operator in a global context, you have to suffix it on an object, so you can say window["opener"] and this will be equivalent to window.opener, but there is no such thing as simply ["window"]
When navigating nested properties, as in window.opener.document you cannot navigate multiple levels using the [] operator. I.e. window["opener.document"] is not allowed. You must use window["opener"]["document"] instead.

Setting properties on anonymous DOM elements through JavaScript?

Let's say I'm generating markup through server-side code. I'm generating a bunch of HTML tags but I want to add custom client-side behavior.
With JavaScript (if I had a reference to the DOM node) I could have written:
var myDOMNode = ...
myDOMNode.myCustomAttribute = "Hi!";
Now the issue here is that I don't want to qualify every element with an unique id just to initialize data. And it's really strange to me, that there's not an easier and unobtrusive way to attach client-side behavior.
If I'm remembing this correctly, this is valid IE stuff.
<div onload="this.myCustomAttribute='Hi!'"></div>
If I was able to do this, I should be able to access it's "data context" though the identifier 'myCustomAttribute', which is really what I want.
The following will work but not validate:
<div myattribute="myvalue"></div>
But if you are injecting it into the HTML with Javascript, then perhaps that's not concern for you. Otherwise, you can use something like jQuery to process the elements before adding them to the DOM:
$(elements).each(function(){
$(this).attr('myattribute','myvalue');
});
First off you should access custom attributes using the getAttribute and setAttribute methods if you want your code to work on other browsers than IE.
As to your event handler question that really depends on how you add the event handler.
Assigning a function directly to the elements onXXXX property would allow you access the the element via this.
If you use IE's attachEvent you can't use this, you can access the element that generated the event using event.srcElementbut that may be child element of the div. Hence you will need to test for the existance of myCustomAttribute and search up the ancestors until you find it.
I do appricate the input but I've finally figured this out and it's the way I go about initialization that has been the thorn in my side.
What you never wan't do is to pollute your global namespace with a bunch of short lived identifiers. Any time you put id="" on an element you're doing exactly that (same thing for any top level function). By relying on jQuery, HTML5 data and CSS there's a solution to my problem which I think is quite elegant.
What I do is that I reserve a CSS class for a specific behavior and then use HTML5 data to parameterize the behavior. When the document is ready, I query the document (using Query) for the CSS class that represents the behavior and initialize the client-side behavior.
I've been doing a lot of ASP.NET and within this context both the id="" and name="" belongs to ASP.NET and is pretty useless for anything else than internal ASP.NET stuff. What you typically find yourself doing is to get at a server-side property called ClientID you can refer to this from client-side JavaScript, it's a lot of hassle. They made it easier in 4.0 but fundamentally I think it's pretty much broken.
Using this hybrid of CSS, HTML5 data and jQuery solves this problem altogether. Here's an example of an attached behavior that uses regular expressions to validate the input of a textbox.
<input type="text" class="-input-regex" data-regex="^[a-z]+$" />
And here's the script:
$(function () {
function checkRegex(inp) {
if (inp.data("regex").test(inp.val()))
inp.data("good-value", inp.val());
else
inp.val(inp.data("good-value"));
}
$(".-input-regex")
.each(function () {
// starting with jQuery 1.5
// you can get at HTML5 data like this
var inp = $(this);
var pattern = inp.data("regex");
inp.data("regex", new RegExp(pattern));
checkRegex(inp);
})
.keyup(function (e) {
checkRegex($(this));
})
.change(function (e) {
checkRegex($(this));
})
.bind("paste", undefined, function (e) {
checkRegex($(this));
})
;
});
Totally clean, no funky id="" or obtrusive dependency.
In HTML5 there are HTML5 data attributes introduced exactly for the case.
<!DOCTYPE html>
<div data-my-custom-attribute='Hi!'></div>
is now corect, validating html. You can use any name starting with data- in any quantity.
There is jQuery .data method for interaction with them. Use .data( key ) to get, .data(key, value) to set data-key attribute. For example,
$('div').each(function () {
$(this).html($(this).data('myCustomAttribute')).data('processed', 'OK');
});
How about this?
<script>
function LoadElement(myDiv)
{
alert(this.myCustomAttribute);
}
</script>
<div onload="LoadElement(this)"></div>
not tested btw
Since you're trying to do this for multiple elements, you may try name attributes and getElementsByName.
<div name="handleonload">...</div>
window.onload = function () {
var divs = document.getElementsByName('handleonload');
for (var i = 0; i < divs.length; i += 1) {
divs[i].foo = 'bar';
}
};
Alternatively, you can use selectors, using libraries (such as jQuery and Prototype) and their respective iterators. This will also allow for you to search by other attributes (such as class).
Though, be cautious with your terminology:
obj.property = value;
<tag attribute="value">
<div style="width:100px;height:100px;border:solid black 1px" myCustomAttribute='Hi!' onclick="alert(myCustomAttribute);"></div>
The onload event is used for server side events. Its not part of the standard html element events.
Take a look at the following functions (especially the walk_the_dom one):
// walk_the_DOM visits every node of the tree in HTML source order, starting
// from some given node. It invokes a function,
// passing it each node in turn. walk_the_DOM calls
// itself to process each of the child nodes.
var walk_the_DOM = function walk(node, func) {
func(node);
node = node.firstChild;
while (node) {
walk(node, func);
node = node.nextSibling;
}
};
// getElementsByAttribute takes an attribute name string and an optional
// matching value. It calls walk_the_DOM, passing it a
// function that looks for an attribute name in the
// node. The matching nodes are accumulated in a
// results array.
var getElementsByAttribute = function (att, value) {
var results = [];
walk_the_DOM(document.body, function (node) {
var actual = node.nodeType === 1 && node.getAttribute(att);
if (typeof actual === 'string' &&
(actual === value || typeof value !== 'string')) {
results.push(node);
}
});
return results;
};
With the above two functions at hand, now we can do something like this:
some link
<script>
var els = getElementsByAttribute('dreas');
if (els.length > 0) {
els[0].innerHTML = 'changed text';
}
</script>
Notice how now I am making finding that particular element (which has an attribute called dreas) without using an id or a class name...or even a tag name
Looks like jQuery is the best bet for this one based on my searching. You can bind an object to a DOM node by:
var domNode = ...
var myObject = { ... }
$(domNode).data('mydata', mymyObj);
then you can call the data back up the same way, using your key.
var myObect = $(domNode).data('mydata');
I assume you could also store a reference to this within this object, but that may be more info then you really want. Hope I could help.

Categories

Resources