I’m building a Windows 8 Metro app in HTML5/Javascript, and I have several screens where users need to fill-in forms.
According to the documentation (http://msdn.microsoft.com/en-us/library/windows/apps/hh700358.aspx) and a few tests, data binding in WinJS seems to be only from the Javascript to the UI.
How can I get what the user typed-in in a Javascript object I could post to the server?
Here’s what I tried so far:
My HTML form:
<div id="createFormDiv" class="hide">
<form id="createForm" onsubmit="return false;">
<fieldset class="formSection entityForm">
<legend>Create New Address</legend>
<table class="fields">
<tr><td>Line 1</td><td><input id="i2" type="text" data-win-bind="value: Line1" /></td></tr>
<tr><td>Line 2</td><td><input id="i3" type="text" data-win-bind="value: Line2" /></td></tr>
<tr><td>City</td><td><input id="i4" type="text" data-win-bind="value: City" /></td></tr>
<tr><td>Zip</td><td><input id="i5" type="text" data-win-bind="value: Zip" /></td></tr>
<tr><td>Country</td><td><input id="i6" type="text" data-win-bind="value: Country" /></td></tr>
<tr><td>Contact</td><td><input id="i7" type="text" data-win-bind="value: Contact" /></td></tr>
</table>
<button id="cancelCreateButton" class="button">Cancel</button>
<button id="createButton" type="submit" class="button">Create</button>
</fieldset>
</form>
In my JS, I created an empty object which I bound to my form, subscribed to the click event on createButton, and expected to retrieve an object filled-in with the changes.
Here’s the code:
var element = document.getElementById("createFormDiv");
var data = {
Line1: "",
Line2: "",
City: "",
Zip: "",
Country: ""
};
WinJS.Binding.processAll(element, data);
_bindingSource = WinJS.Binding.as(data);
And then:
function onCreateCommandClick(args) {
var Line2 = _bindingSource.getProperty("Line2");
}
Problem is, Line2 property always has its initial value.
Is there a way to retrieve a JavaScript object from an HTML form in WinJS or am I bound to parse each input value individually? If so, what would be the best way?
Thanks,
Carl
Meanwhile here’s what I’m doing:
This works great as long as you have inputs using the value property.
For others such as checkboxes or textareas use the appropriate property instead of value (checked for checkbox for instance).
If anyone has a better solution, I’d love to hear it 🙂
Hope this helps,
Carl