Retrieve value from HTML Object - javascript

I have the following div (this was already given to me, I did not create it):
<div data-sudo-slider='{"slideCount":1, "moveCount":1, "customLink":"#slider-nav a", "continuous":true, "updateBefore":false, "effect":"sliceRevealDown", "auto":true, "speed":1500, "pause": 5000}'>
as far as my understanding goes (please correct me if I am wrong), we are saying here, that I want to assing the following values (such as slideCount, moveCount, customLink, etc...) to the object named data-sudo-slider.
What I am trying to do in my underlying JavaScript, is to retrieve the value of pause from this object. Here is what I am doing:
var sudoEl = jQuery('[data-sudo-slider]');
var pause = sudoEl.pause;
Even though it recognized the slider object, it did not retrieve the value for pause I have passed in (returned value is undefined.
How can I retrieve this value?

You can use data() like this:
The .data() method allows us to attach data of any type to DOM
elements in a way that is safe from circular references and therefore
from memory leaks. We can retrieve several distinct values for a
single element one at a time, or as a set:
$('[data-sudo-slider]').data('sudoSlider').pause;
why did you have to specify 'sudoSlider'?
You can also use sudo-slider.
It worked as the property name is derived as following:
The attribute name is converted to all lowercase letters.
The data- prefix is stripped from the attribute name.
Any hyphen characters are also removed from the attribute name.
The remaining characters are converted to CamelCase. The characters immediately following the hyphens removed in Step 3 become uppercase.

You can get this property by:
$(function () {
var pause = $('[data-sudo-slider]').data('sudoSlider').pause;
});
$('[data-sudo-slider]') is the div element, where data-sudo-slider is defined. .data('sudoSlider') is the data property value. data is working with - signs a littlebit different, you can read about it in jQuery data documentation.
.pause is the property of JSON object.

You should use .data() to fetch data-sudo-slider value.
Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute.
var sudoEl = jQuery('[data-sudo-slider]').data('sudo-slider');
alert(sudoEl.pause);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-sudo-slider='{"slideCount":1, "moveCount":1, "customLink":"#slider-nav a", "continuous":true, "updateBefore":false, "effect":"sliceRevealDown", "auto":true, "speed":1500, "pause": 5000}'>

To retrieve the correct element use
var element = $("div[data-sudo-slider]");
You can either get the data-sudo-slider attribute via
var sudoSlider = element.attr("data-sudo-slider");
In which case you will have to convert the string to JSON to access the pause property:
var pause = JSON.parse(sudoSlider).pause;
or better yet, use the .data() method
var sudoSlider = element.data("sudoSlider");
var pause = sudoSlider.pause;

Related

Traverse XML with jQuery to get element value

I have some XML that looks like so:
<closure1>
<topClosure>
<ellipsoidalHead>
<standardComponentData>
<variousElements>
<idNumber>234567</idNumber>
<nominalThickness units="in">0.3750</nominalThickness>
</standardComponentData>
</ellipsoidalHead>
</topClosure>
</closure1>
<shell>
<standardComponentData>
<various_elements>
<nominalThickness units="in">0.6250</nominalThickness>
<idNumber>123456</idNumber>
</standardComponentData>
</shell>
<nozzle>
<standardComponentData>
<various_elements>
<attachedToidNumber>123456</attachedToidNumber>
</standardComponentData>
<nozzle>
In my JS code, I already have the <nozzle> element bomNode as a jQuery set, i.e.
var bomNode = $("nozzle");
So, for each nozzle element, I need to
Get the value of <attachedToidNumber> in the <nozzle> element.
Find the element that contains the <idNumber> that matches
<attachedToidNumber> (<shell> in this case).
Get the value in the <nominalThickess>
element.
As you can see, the depth of the desired <idNumber> element can vary. This is also a very small subset of the whole XML structure, so it can be very large.
I've tried something like this:
var attachedToElement = bomNode.parents().find('idNumber').text() === attachedToId;
but I get false returned. What's the easiest way to get the desired idNumber value? I'm sure it's something simple, but I'm just missing it.
Thanks.
UPDATE: I realized that bomNode is at the top level, I don't need to go up. a level. Doing something like this
var attachedToElement = bomNode.parents().siblings().find('idNumber')
gives me a list of children elements that have an <idNumber> element. So, I need to find the one that has the desired value. My thought is to use .each(). However, that value is defined outside of the .each() function, so I don't have anything to match against. Once I have the list of matches, what's the easiest way to get the set that has the <idNumber> value I want?
You were right - you missed a simple thing:
shell is not a parent of nozzle. They are siblings. Try this:
var attachedToElement = bomNode.siblings().find('idNumber').text() === attachedToId;
But this would return true (if true) - not the actual value.

How to get element id in client-side javascript in Orbeon Forms?

I'm new to XHTML, XForm, and Orbeon, and I've got a question in regards to retrieving HTML element ID using client-side javascript in Orbeon Forms. In normal HTML I'd just used the getElementById function, and Orbeon's documentation suggest a function for retrieving the value of an element (controller in their terminology).
ORBEON.xforms.Document.getValue(controlIdOrElement)
However, with an Orbeon From (snippet) such as
<xf:bind id="fr-form-binds" ref="instance('fr-form-instance')">
<xf:bind id="section-1-bind" name="section-1" ref="section-1">
<xf:bind id="cvr-input-bind" name="cvr-input" ref="cvr-input"/>
(...)
<fr:section id="section-1-control" bind="section-1-bind">
<xf:label ref="$form-resources/section-1/label"/>
<fr:grid>
<xh:tr>
<xh:td>
<xf:input id="cvr-input-control" bind="cvr-input-bind">
<xf:label ref="$form-resources/cvr-input/label"/>
<xf:hint ref="$form-resources/cvr-input/hint"/>
<xf:alert ref="$fr-resources/detail/labels/alert"/>
</xf:input>
</xh:td>
(...)
the getValue function doesn't find a value on any of the parameter variants
cvr-input
cvr-input-control
cvr-input-bind
given as a string.
When I inspect the generated form I see that the input element has gotten the id section-1-control≡xf-383≡cvr-input-control, to which it makes sense that getValue cannot find it on the three variants above.
I've made a trigger button--shown below--that produces the intended result (map the input value to another controller/element), but I can't imagine the solution would have to involve hard-coding the section-parts of the element ID.
Thus my question is: how do I retrieve an element/controller (or its value) when the coded ID is modified in the final view?
<xf:trigger id="get-pnumbers-btn-control" bind="get-pnumbers-btn-bind">
<xf:label ref="$form-resources/get-pnumbers-btn/label"/>
<xf:hint ref="$form-resources/get-pnumbers-btn/hint"/>
<xf:alert ref="$fr-resources/detail/labels/alert"/>
<xxf:script ev:event="DOMActivate" type="javascript">
var cvrInputElementId = "section-1-control≡xf-383≡cvr-input-control";
var cvrOutputElementId = "section-1-control≡xf-383≡cvr-output-control";
var cvrInput = ORBEON.xforms.Document.getValue(cvrInputElementId);
ORBEON.xforms.Document.setValue(cvrOutputElementId, cvrInput);
</xxf:script>
</xf:trigger>
The xxf:client-id() function resolves an id and returns the client id. That could be helpful. Then you need somehow to pass that id to the script (which is easy with the upcoming 4.11 but a bit harder previously).
You can also use jQuery, finding an element with id ending with a certain string:
var clientId = ORBEON.jQuery('[id $= "cvr-input-control"]').attr('id')
There is an RFE to improve the id scheme.

save data for an HTML element such that it can be accessed later

Everything I've read says do not save custom properties or attributes to HTML DOM Elements. So I'm trying to figure out how else I should save properties/attributes for an element such that I can access them later.
Originally I was thinking of using the element as the key in a hash but JS converts hash keys to string so that won't work.
Use case:
function do1(element)
{
var w = element.style.width;
element.style.width = "200px";
// i want to save the w variable for this element somewhere/somehow
}
function do2(element)
{
// i want to be able to get the w variable i saved earlier for the element
}
I thought of using the element's ID but the element won't always have an ID that I can use and I can't set one because there might be other JS that dynamically sets IDs for elements.
Why not use data attributes? They're specifically intended for storing extra data on 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.

How do I access the original element from the jQuery wrapper

Assuming I have this:
var wrap = $("#someId");
I need to access the original object that I would get by
var orig = document.getElementById("someId");
But I don't want to do a document.getElementById.
Is there something I can use on wrap to get it? something like:
var orig = wrap.original();
I searched high and low but I didn't find anything; or maybe I'm not looking for the right thing.
The function for this is get. You can pass an index to get to access the element at that index, so wrap.get(0) gets the first element (note that the index is 0-based, like an array). You can also use a negative index, so wrap.get(-2) gets the last-but-one element in the selection.
wrap.get(0); // get the first element
wrap.get(1); // get the second element
wrap.get(6); // get the seventh element
wrap.get(-1); // get the last element
wrap.get(-4); // get the element four from the end
You can also use array-like syntax to access elements, e.g. wrap[0]. However, you can only use positive indexes for this.
wrap[0]; // get the first element
wrap[1]; // get the second element
wrap[6]; // get the seventh element
$("#someId") will return a jQuery object, so to get at the actual HTML element you can do:
wrap[0] or wrap.get(0).
You can use get() to retrieve the HTML element.
var orig = wrap.get(0);
However, if wrap consists of multiple elements, you will need to know the correct index which to use when you use the get() function.
You can just use var orig = wrap[0]; as far as I know, if there's more than one element. If there's just the one, you can just use wrap without $() around it.
You can use wrap still.. Wrap is the same as 'orig' would be in the above! :)
If you really want:
var orig = wrap;

Categories

Resources