Knockout Example - Form Show hide panels
Show Hide controlled by dropdown, with custom binding to use jquery slide to open/close panel.
HTML
<script src="https://flowcms.infxsolutions.com/script/jQuery/jquery-2.1.1.min.js"></script>
<form id='Form1'>Forename:
<input name="forename" value="Ben" />
<br/>Surname:
<input name="surname" value="Clayton" />
<br/>House No.:
<input name="housenum" value="123333" />
<br/>Pay by:
<select id='payby' data-bind="value:payby, valueAllowUnset:true">
<option value=-1>[Select]</option>
<option value=0>Cash</option>
<option value=1>On Account</option>
<option value=2>Credit Card</option>
</select>
<br/>
<div data-bind="slideVisible: payby()==0">Cash Amount:
<input name="amount" />
<br/>
</div>
<div data-bind="slideVisible: payby()==1">Account Name:
<input name="accname" value="Fred Smith" />
<br/>Account No.:
<input name="accno" value="987654321" />
<br/>
</div>
<div data-bind="slideVisible: payby()==2">Card Number:
<input name="ccnum" value="1111 2222 3333 4444" />
<br/>Card Expire:
<input name="ccexpire" value="11/2014" />
<br/>
</div>
<button class="submit" data-bind="click: submit">Submit</button>
</form>
CSS
div {
padding:20px;
border:1px solid red;
}
#payby {
margin-top:30px;
margin-bottom:30px;
}
.submit {margin-top:20px;}
JavaScript
ko.bindingHandlers.slideVisible = {
update: function (element, valueAccessor, allBindings) {
// First get the latest data that we're bound to
var value = valueAccessor();
// Next, whether or not the supplied model property is observable, get its current value
var valueUnwrapped = ko.unwrap(value);
// Grab some more data from another binding property
var duration = allBindings.get('slideDuration') || 400; // 400ms is default duration unless otherwise specified
// Now manipulate the DOM element
if (valueUnwrapped == true) $(element).slideDown(duration); // Make the element visible
else $(element).slideUp(duration); // Make the element invisible
}
};
function viewModel() {
this.payby = ko.observable(-1);
this.submit = function () {
var fdata = $("#Form1").serialize();
alert("\n" + fdata);
}
};
var vm = new viewModel();
ko.applyBindings(vm, document.getElementById("Form1"));