How to determiine which dropdown was used - html-select

I have a form with more than one dropdown list, like this below. I can see how to get the ID's of each dropdown but I can't figure out how to get the one that was actually used. Would someone explain how to do that, please.
<div>
<select name="id[11]" class="pullDown" id="attrdrop0">
<option class="pink" value="31`">No</option>
<option class="pink" value="32">Yes (+$40.00)</option>
</select>
</div>
<div>
<select name="id[10]" class="pullDown" id="attrdrop1">
<option class="pink" value="31">No</option>
<option class="pink" value="32">Yes (+$150.00)</option>
</select>
</div>
<script>
$(function () {
$("#prices").change(function () {
console.log('A change was made');
CalculatePrice();
});
});
function CalculatePrice() {
var ttl_price = 0;
var id = '';
$(":input.select, :input").each(function() {
var cur_price = $('option:selected', $(this)).text();
ttl_price += cur_price;
id = $(this).attr('id');
/*** What now ***/
});
SetPrice(id, ttl_price);
}
</script>

You can pass the control as a parameter to CalculatePrice.
$(function () {
$("#prices").change(function () {
console.log('A change was made');
CalculatePrice(this);
});
});
function CalculatePrice(triggerObject) {
var ttl_price = 0;
var id = '';
$(":input.select, :input").each(function() {
var cur_price = $('option:selected', $(this)).text();
ttl_price += cur_price;
id = $(this).attr('id');
/*** What now ***/
if (triggerObject.id) {...}
});
SetPrice(id, ttl_price);
}
</script>

Related

bootstrap Dual Listbox knockout binding

I am using bootstrap dual listbox pluging in my ASP.NET MVC project.
I am also using Knockout in the project. I am trying to create bindingHandler for the this plugin to make it working smoothly with knockout.
here is what I tried
Binding Handler
ko.bindingHandlers.dualList = {
init: function (element, valueAccessor) {
$(element).bootstrapDualListbox({
selectorMinimalHeight: 160
});
$(element).on('change', function () {
$(element).bootstrapDualListbox('refresh', true);
});
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).bootstrapDualListbox('destroy');
});
},
update: function (element, valueAccessor) {
$(element).bootstrapDualListbox('refresh', true);
}
}
HTML
<select class="form-control" data-bind="foreach:{data: EditedElement().Operations, as : 'op'} , dualList: EditedElement().Operations" multiple>
<option data-bind="value: op.OperationID(), text: op.Name(), selected: op.IsSelected()"></option>
</select>
View Model
function SelectOperationVM(operationId, isSelected, name) {
var self = this;
self.OperationID = ko.observable(operationId);
self.IsSelected = ko.observable(isSelected);
self.Name = ko.observable(name);
self.copy = function () {
return new SelectOperationVM(self.OperationID(), self.IsSelected(), self.Name());
}
}
My problem is that I can not make sync between the viewModel observableArray, and the plugin.
In other words, I want the changes in the plugin (the user removed some options or added some options) to be reflected on the view model property, and vice verse
to sync, you need to pass multiple observables to custom binding
so your html should be like
<select class="form-control" data-bind="foreach: { data: Operations, as: 'op'}, dualList: { options: Operations, selected: Selected }" multiple>
<option data-bind="value: op.OperationID(), text: op.Name(), selected: op.IsSelected()"></option>
</select>
and custom binding be like
ko.bindingHandlers.dualList = {
init: function(element, valueAccessor) {
var data = ko.utils.unwrapObservable(valueAccessor());
$(element).bootstrapDualListbox({
selectorMinimalHeight: 160
});
$(element).on('change', function() {
// save selected to an observable
data.selected($(element).val());;
});
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
$(element).bootstrapDualListbox('destroy');
});
},
update: function(element, valueAccessor) {
// to view if there is an update (without this "update" will not fire)
var options = ko.utils.unwrapObservable(valueAccessor()).options();
$(element).bootstrapDualListbox('refresh', true);
}
}
also i have created a dirty working jsfiddle

Autocomplete combobox widget force change

I'm getting absolutely no where in getting the underlying select to fire a changed event after a autocomplete value is selected.
How can I force a change within the widget. From what I can find I need to
trigger a select event and trigger a change with something like this, but I can't get it to work
select: function(event,ui) {
this.value=ui.item.value;
$(this).trigger('change');
return false; }
(function( $ ) {
$.widget("st.comboboxAutocomplete", {
options: {
minLength: 0,
showDropdown: false,
width: '',
Id: '',
},
_create: function () {
this.wrapper = $("<span>")
.addClass("st-comboboxAutocomplete")
.css({ 'padding': '0px 0px', 'width': this.options.width})
.insertAfter(this.element);
this.element.hide();
this._createAutocomplete();
if (this.options.showDropdown)
{
this._createShowAllButton();
}
},
_createAutocomplete: function () {
var selected = this.element.children(":selected"),
value = selected.val() ? selected.text() : "";
this.input = $("<input>")
.appendTo(this.wrapper)
.val(value)
.attr("title", "")
.attr("id", this.options.Id)
.addClass("st-comboboxAutocomplete-input")
.css('margin-right', '5px')
.autocomplete({
delay: 0,
minLength: this.options.minLength,
source: $.proxy(this, "_source"),
});
this._on(this.input, {
autocompleteselect: function (event, ui) {
ui.item.option.selected = true;
this._trigger("select", event, {
item: ui.item.option
});
},
autocompletechange: "_removeIfInvalid"
});
},
_createShowAllButton: function () {
var input = this.input,
wasOpen = false;
$("<a>")
.attr("tabIndex", -1)
.attr("title", "Show All Items")
.tooltip()
.css('background-color', '#fff')
.appendTo(this.wrapper)
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass("ui-corner-all")
.addClass("st-comboboxAutocomplete-toggle ui-corner-right")
.on("mousedown", function () {
wasOpen = input.autocomplete("widget").is(":visible");
})
.on("click", function () {
input.trigger("focus");
// Close if already visible
if (wasOpen) {
return;
}
// Pass empty string as value to search for, displaying all results
input.autocomplete("search", "");
});
},
_source: function (request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response(this.element.children("option").map(function () {
var text = $(this).text();
if (this.value && (!request.term || matcher.test(text)))
return {
label: text,
value: text,
option: this
};
}));
},
_removeIfInvalid: function (event, ui) {
// Selected an item, nothing to do
if (ui.item) {
return;
}
// Search for a match (case-insensitive)
var value = this.input.val(),
valueLowerCase = value.toLowerCase(),
valid = false;
this.element.children("option").each(function () {
if ($(this).text().toLowerCase() === valueLowerCase) {
this.selected = valid = true;
return false;
}
});
// Found a match, nothing to do
if (valid) {
return;
}
// Remove invalid value
this.input
.val("")
.attr("title", value + " didn't match any item")
.tooltip("open");
this.element.val("");
this._delay(function () {
this.input.tooltip("close").attr("title", "");
}, 2500);
this.input.autocomplete("instance").term = "";
},
_destroy: function () {
this.wrapper.remove();
this.element.show();
}
});
})( jQuery );
$(function() {
$( "#combobox" ).comboboxAutocomplete();
$("#combobox").change(function() {
alert(this.value);
});
});
.ui-button { margin-left: -1px; }
.ui-button-icon-only .ui-button-text { padding: 0.35em; }
.ui-autocomplete-input { margin: 0; padding: 0.48em 0 0.47em 0.45em; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<meta charset="utf-8">
<div class="demo">
<div class="ui-widget">
<label>Your preferred programming language: </label>
<select id="combobox">
<option value="">Select one...</option>
<option value="ActionScript">ActionScript</option>
<option value="AppleScript">AppleScript</option>
<option value="Asp">Asp</option>
<option value="BASIC">BASIC</option>
<option value="C">C</option>
<option value="C++">C++</option>
<option value="Clojure">Clojure</option>
<option value="COBOL">COBOL</option>
<option value="ColdFusion">ColdFusion</option>
<option value="Erlang">Erlang</option>
<option value="Fortran">Fortran</option>
<option value="Groovy">Groovy</option>
<option value="Haskell">Haskell</option>
<option value="Java">Java</option>
<option value="JavaScript">JavaScript</option>
<option value="Lisp">Lisp</option>
<option value="Perl">Perl</option>
<option value="PHP">PHP</option>
<option value="Python">Python</option>
<option value="Ruby">Ruby</option>
<option value="Scala">Scala</option>
<option value="Scheme">Scheme</option>
</select>
</div>
<button id="toggle">Show underlying select</button>
</div><!-- End demo -->
<div class="demo-description">
<p>A custom widget built by composition of Autocomplete and Button. You can either type something into the field to get filtered suggestions based on your input, or use the button to get the full list of selections.</p>
<p>The input is read from an existing select-element for progressive enhancement, passed to Autocomplete with a customized source-option.</p>
</div><!-- End demo-description -->
In case inquiring minds want to know, I solved this with the following
_createAutocomplete: function () {
var selected = this.element.children(":selected"),
value = selected.val() ? selected.text() : "";
this.input = $("<input>")
.appendTo(this.wrapper)
.val(value)
.attr("title", "")
.attr("id", this.options.Id)
.addClass("st-comboboxAutocomplete-input")
.css('margin-right', '5px')
.autocomplete({
delay: 0,
minLength: this.options.minLength,
source: $.proxy(this, "_source"),
change: $.proxy(this, "_change")
});
this._on(this.input, {
autocompleteselect: function (event, ui) {
ui.item.option.selected = true;
this._trigger("select", event, {
item: ui.item.option
});
},
autocompletechange: "_removeIfInvalid"
});
}
_change: function (event, ui) {
this.value = ui.item.value;
this.element.trigger('change');
return false;
}
This will fire a change when you tab or exit the autocomplete. If you want it to fire the change on select then use
select: $.proxy(this, "_select")
_select: function (event, ui) {
this.element.trigger('change');
},

knockoutjs select option not bind

I am very new to knockoutjs. I try to modified a little from [knockoutjs sample] (http://knockoutjs.com/documentation/options-binding.html) but it didn't work.
<select data-bind="option: availCustomers, optionsText: 'CustomerName',
value: selectedCustomer, optionsCaption: '--- Choose ---'">
</select>
and the viewmodel :
<script>
function customerViewModel() {
var self = this;
self.availCustomers = ko.observableArray();
self.selectedCustomer = ko.observable();
};
var Customer = function (id, name) {
this.CustomerId = id;
this.CustomerName = name;
};
$(document).ready( function() {
var cvm = new customerViewModel();
cvm.availCustomers = new ko.observableArray([
new Customer("12345", "ABC"),
new Customer("54321", "XYZ")
]);
ko.applyBindings(cvm);
});
</script>
so please guide me
I think this is just a mispeling error, the parameter to bind is called "options".
<select data-bind="options: availCustomers, optionsText: 'CustomerName',
value: selectedCustomer, optionsCaption: '--- Choose ---'">
</select>

kendo checkbox checked binding. Not able to bind to an array of checkboxes

I have an array of checkboxes and I would like to use it as an array, for example set single iitems in a group of options and retrieve the values of the group.
For a single checkbox I'm able to set it and get the click event, as an array I don't get anything.
HTML code :
<div class="k-group" id="chkbox-options">
<label>
Red
<input type="checkbox" id="chk1" value="Red" data-bind="checked: colors" />
Green
<input type="checkbox" id="chk2" value="Green" data-bind="checked: colors" />
Blue
<input type="checkbox" id="chk3" value="Blue" data-bind="checked: colors" />
</label>
</div>
Javascript code :
<script type="text/javascript">
var colordata = null;
$(document).ready(function () {
colordata = kendo.observable({
colors: ["Blue"]
});
kendo.bind($("chkbox-options"), colordata);
$("#dump-values").click(function () {
kendoConsole.log(colordata.colors.toString());
});
$("#chk1").click(function () {
kendoConsole.log("click chk1");
if (this.checked) {
kendoConsole.log("click chk1 true");
}
});
});
</script>
I can get the click event on a single checkbox, while I cannot set the values of the checkboxes in kendo.observable in the field var colordata.
I saw a similar example in the kendo documentation but I'm not able to make it work.
Thanks for your help
Marco
couple of points:
1. in kendo.bind # is missing for the div id chkbox-options
2. you need to read the changed colors inside the change event of the the observable object. The change happens after the click event so inside click event you always see the old data.
I have corrected your jsFiddle: http://jsfiddle.net/whizkid747/rPjjJ/4/
var colordata = null;
$(document).ready(function () {
colordata = kendo.observable({
colors: ["Blue"]
});
kendo.bind($("#chkbox-options"), colordata);
colordata.bind("change", function(e) {
var selectedColors = '';
$.each(colordata.colors, function(key, value){
selectedColors = selectedColors + " " + value;
});
if(colordata.colors.length == 0){
console.log('no colors selected');
}else{
console.log('selected colors:' + selectedColors);
}
});
});

copy data from one Html.listboxfor to other listbox in asp.net mvc

I have two Html.ListBoxFor called A & B.
1) A has data populated from DB & B is empty.
2) I want a functionality like this where items from list A are placed into list B.
$('.add').on('click', function() {
var options = $('select.multiselect1 option:selected').sort().clone();
$('select.multiselect2').append(options);
});
$('.addAll').on('click', function() {
var options = $('select.multiselect1 option').sort().clone();
$('select.multiselect2').append(options);
});
$('.remove').on('click', function() {
$('select.multiselect2 option:selected').remove();
});
$('.removeAll').on('click', function() {
$('select.multiselect2').empty();
});
3) I tried this with asp.net mvc, but I was unable to fetch the selected items in model & controller.
4) I want a way by which we can perform this in asp.net mvc. If there can be some way in mvc then I would be able to store that data in SQL DB
5) Its jquery sibling is here
Any help would be appreciated
I think this will help you.
Blockquote
Html file
Fruits:
<select multiple="multiple" id="a">
<option value="1">Apple</option>
<option value="2">Orange</option>
<option value="3">Banana</option>
</select>
<input type="button" id="add" value="Add"/>
<input type="button" id="addall" value="Add all"/>
<select multiple="multiple" id="b">
</select>
Javascript File
$("#add").bind("click", function () {
addOption(false);
});
$("#addall").bind("click", function () {
addOption(true);
});
function addOption(isAll){
var option = $("#a option");
if (!isAll) {
option = $("#a option:selected");
} else {
$("#b").html("");
}
$(option).each(function () {
var val = $(this).val();
var text = $(this).text();
$("#b").append($(this)[0].outerHTML);
$(this).remove();
});
}

Resources