I have a select in Grails as follows
<g:select name="receiptItems" from="${myGrailsProject.ReceiptItem.list()}" multiple="multiple" optionKey="id" optionValue="description" size="5" value="${receiptInstance?.receiptItems*.id}" class="many-to-many"/>
ReceiptItem object has a numeric field (amount). I need to do the sum of amount fields of selected values and put it in another textfield.
In particular, when I select a new value I need to add it to the "totalAmount", and viceversa, when I deselect a value, I need to remove that value from the "totalAmount".
How can I understand if the item is selected or unselected?How can I perform the calculation into the Controller class and then update the textfield with new value in javascript?
Thanks for your help
You can use jquery to do that. For example, your select is
<select id="mySelect" multiple="multiple">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
<option value="4">Fourth</option>
</select>
listen for the change event:
$('#mySelect').change(function() {
var amount = 0;
$('#mySelect option').each(function() {
if($(this).is(':selected'))
amount += $(this).val();
});
$('#amount').val(amount);
});
Hope this helps.
Ok so you have a list of IDs of objects and you need to sum a field of that domain and return the sum to javascript? If so:
JavaScript:
$('#mySelect').change(function() {
var $this = $(this);
$.ajax({
type: 'POST',
url: enterYourPathHere,
data: {values: $this.val()},
dataType: 'json',
success: function(data) {
//Populate your totalAmount field with data.amount
},
error: function(jqXHR, textStatus, errorThrown) {
//Handle any errors
}
});
Controller:
Float totalAmount = Object.findByIdInList(params.list("values"))?.amount?.sum() ?: 0
render [amount: totalAmount] as JSON
Obviously change this for your Domain, fields, etc...
Related
I would like to build a selector that displays a "Check one or more or options" placeholder and, after selecting 1-N options, the placeholder is still displayed instead of the checked results.
In short, the component should always display the placeholder, regardless of having 0, 1 or N options checked.
I have been searching but I can't find any way to do it:
Html:
<select multiple id="e1" style="width:300px">
<option value="AL">Alabama</option>
<option value="Am">Amalapuram</option>
<option value="An">Anakapalli</option>
<option value="Ak">Akkayapalem</option>
<option value="WY">Wyoming</option>
</select>
Js
$('select').select2({
placeholder: "Select a state",
templateSelection: function (data) {
return 'Select a state';
}
});
http://jsfiddle.net/91nqgkuy/2/
Finally, I have chosen to overwrite the results template and insert the desired text.
// Set the default option.
$(select, context).each(function (e) {
setTemplateResults($(this));
});
// Override select2 default work flow.
$(select, context).on('select2:select select2:unselect', function (evt) {
setTemplateResults($(this));
});
// Method.
function setTemplateResults(selector) {
let container = selector.siblings('span.select2').find('ul')
container.html('<li>' + Drupal.t('Select category(ies)') + '</li>');
}
I have a select2 dropdown box using remote datasource.
What I would like to do is if/when there is only one option returned by the search, auto select it. ie, the user doesn;t have to click on the option to make the selection.
$("#searchInfo_Entity_Key").select2({
ajax: {
url: "/Adjustment/GetEntity",
dataType: 'json',
delay: 250,
data: function (params) {
return {
term: params.term, // search term
};
},
processResults: function (data) {
return {
results: data
};
},
results: function (data) {
return { results: data };
},
},
initSelection: function (element, callback) {
var data = [];
callback(data);
},
minimumInputLength: 2,
allowClear: true,
placeholder: "Select an entity"
});
This is a custom matcher, that wraps around the default matcher and counts how many matches there are. If there is only one match, then it will select that match, change it, and close the dropdown box.
(Not tested with remote data.)
$(function() {
var matchCount = 0; // Track how many matches there are
var matched; // Track the ID of the last match
$('select').select2({
placeholder: 'Product Search',
allowClear: true,
matcher: function(params, data) {
// Wrap the default matcher that we have just overridden.
var match = $.fn.select2.defaults.defaults.matcher(params, data);
// If this is the first option that we are testing against,
// reset the matchCount to zero.
var first = $(data.element).closest('select').find('option').first().val();
if (first == data.id) matchCount = 0;
// If there was a match against this option, record it
if (match) {
matchCount = matchCount + 1;
matched = data.id;
}
// If this is the last option that we are testing against,
// now is a good time to check how many matches we had.
var last = $(data.element).closest('select').find('option').last().val();
if (last == data.id && matchCount == 1) {
// There was only one match, change the value to the
// matched option and close the dropdown box.
$(data.element).closest('select')
.val(matched).trigger('change')
.select2('close');
return null;
}
// Return the default match as normal. Null if no match.
return match;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.full.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
<select style="width: 20em">
<option value=""></option>
<option value="100">Product One</option>
<option value="200">Product Two</option>
<option value="300">Product Three</option>
<option value="400">Product Four</option>
<option value="500">Product Five</option>
</select>
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();
});
}
I want to have two different Autocomplete boxes but both using the same AJAX method in the background.
Here is my script
$(document).ready(function () {
$("#SearchProject")
.each(function () {
var urlloc = "/Project/FindProjects";
$(this).autocomplete({
source: function (request, response) {
$.ajax({
url: urlloc, type: "POST", dataType: "json",
data: { searchString: request.term, maxResults: 10 },
success: function (data) {
response($.map(data, function (item) {
return { label: item.name, value: item.name, id: item.id }
}))
}
})
},
select: function (event, ui) {
$("[id$='ProjectID']").val(ui.item.id);
// alert(ui.item ? ("You picked '" + ui.item.label + "' with an ID of " + ui.item.id)
// : "Nothing selected, input was " + this.value);
}
});
});
});
I want my input fields on the form as below.
<input id="SearchProject" name="SearchProject" type="text" value="" /><input type="hidden" name="ProjectID" id="ProjectID" value="" />
<input id="SearchProject2" name="SearchProject" type="text" value="" /><input type="hidden" name="ProjectID" id="ProjectID2" value="" />
When autocomplete select is complete I want the corresponding hidden field to be updated.
How do i achieve this?
Two possibilities:
First (the one I prefer): extract your auto-complete setup into a method:
function configureAutocomplete(autoField, updatedField)
You call this method for as many auto-complete fields as you want, passing it two JQuery selectors: the selector for the auto-complete field, and the hidden update field.
The other way is to base the ID of the hidden field on that of the auto-complete field. This will let you use an each to attach behavior to the fields, but I think it' more trouble than it's worth.
im working on this jquery data entry form in which i need a specific field to be autocompleted with data from mysql
i got everything working, autocomplete retrieves data from the sql through php matching is great in english/latin and utf8 characters
the values get retrieved from the sql as "'number' => 'name'"
right now the autocomplete has 3 values in the output, value, label and id.
as id and value it uses the 'name'
and the label is the 'number' of my sql string (which is posted to the next page when the form is submited)
so everyting works ok, my 'number' is posted correctly, there is a minor annoyance tho
when i select something from the autocomplete list, the field is populated with the 'number'
is there any way to fill it with the 'name'?
ie: search for 'name', get dropdown with 'names', click and get the 'name' in the field, and when i submit i get the 'number' posted?
any help would be greatly appreciated.
if you need to take a look at my code, it's posted on a previous question: Jquery ui - Autocomplete - UTF8 charset
thanx in advance :)
The usual way to do this is:
Use a hidden input to hold the value you'd like to POST, then autocomplete a separate field.
Populate the hidden input on select
Populate the visible, autocompleted input with the label property of the item that was selected.
So, for example:
HTML:
<input type="hidden" name="name" />
<input type="text" id="name_auto" />
JavaScript:
$(function () {
var cache = {},
lastXhr;
$( ".name" ).autocomplete({
minLength: 1,
source: function( request, response ) {
var term = request.term;
if ( term in cache ) {
response( cache[ term ] );
return;
}
lastXhr = $.getJSON( "search.php", request, function( data, status, xhr ) {
cache[ term ] = data;
if ( xhr === lastXhr ) {
response( data );
}
});
},
select: function (event, ui) {
event.preventDefault();
this.value = ui.item.label;
},
change: function (event, ui) {
if (ui.item) {
$("input[name='name']").val(ui.item.value);
} else {
$("input[name='name']").val('');
}
}
});
});
You can use the result (handler) from u'r autocomplete
where the variable data such as arrays and you can return two data at once
Expl:
in javascript
$().ready(function()
{
var url = "<?=base_url()?>index.php/master/agen";
var width_val = 308;
$("#name_auto").autocomplete(url,
{
width: width_val,
selectFirst: false,
});
$("name_auto").result(function(event, data, format)
{
$("#name_auto").val(data[0]);
$("#id").val(data[1]);
});
});
in HTML :
<input type="hidden" name="number" id="id" />
<input type="text" id="name_auto" name="name" />
in PHP :
foreach ($source->result() as $row)
{
echo "$row->nama|$row->id\n";
}
note : here I use PHP CodeIgniter in its