I have this controller function:
public function showclientsinvoice($id)
{
$clients = Clients::find($id);
return response()->json($clients);
}
That makes me autopopulate the input fields with clients data.
My problem is I don't know how to autopopulate a dropdown list
My jquery script is this:
$(document).ready(function () {
$('body').on('click', '#show-client', function () {
var userURL = $(this).data('url');
$.get(userURL, function (data) {
$('#invoicemodal').modal('show');
$('#client-id').val(data.id);
$('#client-name').val(data.nume);
$('#client-ctara').val(data.tara);
$('#cif').val(data.cif);
$('#cif1').val(data.cif1);
$('#rgc').val(data.rgc);
$('#rgc1').val(data.rgc1);
$('#rgc2').val(data.rgc2);
$('#rgc3').val(data.rgc3);
$('#cp').val(data.cp);
$('#judet').val(data.judet);
})
});
});
</script>
How can I integrate in this script an autopopulate for dropdown?
You can use JQuery in this way to add dynamically dropdown options:
let options = {
a : 'one',
b : 'two'
};
var select = $('#idselect');
$.each(options, function(val, text) {
select.append(
$('<option></option>').val(val).html(text)
);
});
Related
Is it possible to trigger a function when the Enter key is pressed in the character field.?
The onchange function is not working as inside the function it returns another form.
From js i want to call function get_details of model customer.status.search on clicking enter button
class CustomerStatusSearch(models.TransientModel):
_name = 'customer.status.search'
def get_details(self):
print("enter")
for li in self:
customer = self.env['res.partner'].search([('id', '=', 23)], limit=1)
return {
'view_type': 'form',
'view_mode': 'form',
'view_id': self.env.ref('operation.view_registration_student_form').id,
'res_model': 'res.partner',
'target': 'current',
'res_id': customer.id,
'type': 'ir.actions.act_window'
}
so is there any Javascript code for that?
You can define a new Char field to handle the Enter key event.
Example:
odoo.define('Module_Name.FieldChar', function (require) {
"use strict";
var FieldChar = require('web.basic_fields').FieldChar;
var registry = require('web.field_registry');
var FieldCharCustom = FieldChar.extend({
_onKeydown: function (ev) {
if (ev.which === $.ui.keyCode.ENTER) {
// this._someFunction();
}
this._super.apply(this, arguments);
},
});
registry.add('char_custom', FieldCharCustom);
});
To load the js file, inherit the web.assets_backed:
<template id="assets_backend" inherit_id="web.assets_backend" name="assets_backend">
<xpath expr="." position="inside">
<script type="text/javascript" src="/Module_Name/static/src/js/field_char.js"></script>
</xpath>
</template>
Then you have just to set the widget attribute of a char field in the view arch:
<field name="name" widget="char_custom"/>
Update
You can use this.rpc to call get_details on customer.status.search model like they did when clicking a button to validate the inventory
Example:
this._rpc({
model: 'customer.status.search',
method: 'get_details',
args: [record_id]
}).then(function (res) {
});
You can find an example in init method on how they get the inventory id from context
Edit:
When you click for the first time in the custom char field the wizard record id will not be available and you can't call the get_details function because it depends on self. The get_details function does only return an action (open the partner form) which is also possible to do using the js code, just call this.do_action to execute the window action.
The fields values will be available in this.recordData variable if you use it to search for a particular partner.
If you try to open the partner form before saving, Odoo will show the following warning:
The record has been modified, your changes will be discarded. Do you want to proceed?
To avoid that you can simulate the click on the save button using:
$(".o_form_button_save").click();
Example:
odoo.define('MODULE_NAME.FieldChar', function (require) {
"use strict";
var core = require('web.core');
var _t = core._t;
var FieldChar = require('web.basic_fields').FieldChar;
var registry = require('web.field_registry');
var FieldCharCustom = FieldChar.extend({
_onKeydown: function (ev) {
this._super.apply(this, arguments);
if (ev.which === $.ui.keyCode.ENTER) {
var self = this;
var customer_id = 14;
$(".o_form_button_save").click();
this._rpc({
model: 'ir.model.data',
method: 'xmlid_to_res_model_res_id',
args: ["base.view_partner_form"],
}).then(function (data) {
self.do_action(
{
name: _t('Customer Status'),
type: 'ir.actions.act_window',
view_mode: 'tree,form',
res_model: 'res.partner',
target: 'current',
res_id: customer_id,
views: [[data[1], 'form'], [false, 'list']],
});
});
}
},
});
registry.add('char_custom', FieldCharCustom);
});
You use addEventListener 'keypress' then check if the keycode is the Enter key
document.getElementById('inputField').addEventListener('keypress', function(event) {
if (event.keyCode == 13) {
//Run a function here
}
});
I apologize I am still fairly new to MVC. I currently have a dropdownlist with some options. What I would like to do is depending on the dropdownlist value that I select then I should be able to render a partial view. I want the partial view to load as soon as the user selects from the dropdownlist.
Also, I am able to render my partial view but it's not returning what I need. When I select from the dropdownlist it does not take the functionID..it just returns all of the items regardless of the functionID.
I want the partial view to render based off the functionID.
Thank you very much. Any help is very much appreciated it.
Main View
#Html.DropDownListFor(m => m.FunctionID, new
SelectList(Model.functionList, "FunctionID", "Name"), "Select
Function", new {#id="id"})
<div id="partialPlaceHolder">
</div>
Partial View
#foreach (var items in Model.itemTypeList)
{
<pre> #items.Definitions</pre>
}
Controller
[HttpGet]
public ActionResult ViewOverview()
{
List<Function> functionList;
List<ItemType> itemTypeList;
using (BusinessLogic BLL = new BusinessLogic())
{
functionList = BLL.GetFunctionList();
itemTypeList = BLL.GetItemTypesList();
}
Words viewModel = new Words();
MetricDefinitions(viewModel);
return View(viewModel);
}
[HttpGet]
public ActionResult GetWords()
{
List<Function> functionList;
List<ItemType> itemTypeList;
using (BusinessLogic BLL = new BusinessLogic())
{
functionList = BLL.GetFunctionList();
itemTypeList = BLL.GetItemTypesList();
}
Words viewModel = new Words()
{
itemTypeList = itemTypeList,
functionList = functionList
};
return PartialView("_ViewWords", viewModel);
}
private void MetricDefinitions(Words model)
{
List<Function> functionList;
List<ItemType> itemTypeList;
using (BusinessLogic BLL = new BusinessLogic())
{
functionList = BLL.GetFunctionList();
itemTypeList = BLL.GetItemTypesList();
}
model.functionList = functionList;
model.itemTypeList = itemTypeList;
}
javascript
$(document).ready(function () {
$('#id').change(function () {
var selectedID = $(this).val();
$.get('/Home/GetWords/' + selectedID, function (data) {
$('#partialPlaceHolder').html(data);
/* little fade in effect */
$('#partialPlaceHolder').fadeIn('fast');
});
});
});
I have added NetFiddle. It works here
Can you try to add selectedItem param into action and use jquery .load() function to get partial result into your target element.
[HttpGet]
public ActionResult GetWords(int selectedItem) // add your selectedVal value in controller
{
.....
}
jquery
// it is going to parse partial view into target div
$("#id").on("change", function(){
var url = '#Url.Action("GetWords", "Home")' + "?selectedItem=" + $(this).val();
$("#partialPlaceHolder").load(url, function(){
console.log("It worked");
$('#partialPlaceHolder').fadeIn('fast');
})
})
I know some php/html/css but javascript is where I need help. I found on web autocomplete script, but this doesn't work on more than two input fields.
There are two problems I need to solve.
When you type in first box, autocomplete shows in second one. How to make script show autocomplete on box where user is typing?
I need to use the same autocomplete on multiple fields on my site.
The javascript syntax I use is:
var MIN_LENGTH = 2;
$( document ).ready(function() {
$("#keyword").keyup(function() {
var keyword = $("#keyword").val();
if (keyword.length >= MIN_LENGTH) {
$.get( "http://example.com/autofill/auto-complete.php", { keyword: keyword } )
.done(function( data ) {
$('#results').html('');
var results = jQuery.parseJSON(data);
$(results).each(function(key, value) {
$('#results').append('<div class="item">' + value + '</div>');
})
$('.item').click(function() {
var text = $(this).html();
$('#keyword').val(text);
})
});
} else {
$('#results').html('');
}
});
$("#keyword").blur(function(){
$("#results").fadeOut(500);
})
.focus(function() {
$("#results").show();
});
});
In order to re-use the same autocomplete code you need to give the scope of the function the context of the correct DOM element.
Here's a a quick jsfiddle with some simple HTML code, but it should give a basic example of how to bind the same events to multiple dom structures.
DEMO: JSfiddle example
JS
var MIN_LENGTH = 2;
$(document).ready(function() {
$(".keyword").keyup(function() {
var $parent = $(this).parent();
var $results = $parent.find('.results');
var keyword = $(this).val();
if (keyword.length >= MIN_LENGTH) {
$.get("/echo/json/", {
keyword: keyword
})
.done(function(data) {
$results.html('');
data = ['test', 'test2'];
//data = jQuery.parseJSON(data);
$(data).each(function(key, value) {
$results.append('<div class="item">' + value + '</div>');
});
});
} else {
$results.html('');
}
});
});
HTML
<div class="autcomplete">
<input class="keyword" />
<ul class="results"></ul>
</div>
<div class="autcomplete">
<input class="keyword" />
<ul class="results"></ul>
</div>
Below is my grid code, how do I get the Primary Key Value when the cell is clicked in jquery?
I have tried searching online and can't find a working example. Is there another way to get the value without using jquery or javascript?
<div id="CampaignGrid">
#(Html.EJ().Grid.Test.Test>("Grid")
...
})
.Columns(col =>
{
col.Field("iCampaign").HeaderText("Campaign").IsPrimaryKey(true).TextAlign(TextAlign.Left).Width(50).AllowEditing(false).Add();
col.Field("vCampaignName").HeaderText("Campaign Name").IsPrimaryKey(false).TextAlign(TextAlign.Left).Width(260).AllowEditing(false).Add();
})
when you are setting fields like col.Field("iCampaign"), you determine a tag with attribute name="iCampaign",which will be used in model binding.
so you can use a jquery selector like this :
$('[name = "iCampaign"]')
you can also solve your problem this way :
#(Html.EJ().Grid<EmployeeView>("MasterGrid")
.Datasource((IEnumerable<object>)ViewBag.datasource1)
.SelectedRowIndex(0)
.Columns(col =>
{
col.Field("EmployeeID").HeaderText("Employee ID").IsPrimaryKey(true).TextAlign(TextAlign.Right).Width(125).Add();
col.Field("FirstName").HeaderText("First Name").Width(100).Add();
col.Field("LastName").HeaderText("Last Name").Width(100).Add();
col.Field("Title").HeaderText("Title").Width(150).Add();
col.Field("BirthDate").HeaderText("Birth Date").TextAlign(TextAlign.Right).Width(100).Format("{0:MM/dd/yyyy}").Add();
col.Field("Country").Width(100).HeaderText("Country").Add();
})
.ClientSideEvents(eve => { eve.RowSelected("rowSelected"); })
)
<script type="text/javascript">
$(function () {
window.rowSelected = function (args) {
var employeeID = args.data.EmployeeID;
var detaildata = ej.DataManager(window.gridData).executeLocal(ej.Query().where("EmployeeID", ej.FilterOperators.equal, employeeID, false).take(10));
var gridObj = $("#DetailGrid").ejGrid("instance");
gridObj.model.dataSource = ej.DataManager(detaildata.slice(0, 5));
$("#DetailGrid").ejGrid("refreshContent");
}
});
</script>
You can try this
#(Html.EJ().Grid<EmployeeView>("MasterGrid")
.Datasource((IEnumerable<object>)ViewBag.datasource1)
.SelectedRowIndex(0)
.Columns(col =>
{
col.Field("EmployeeID").HeaderText("Employee ID").IsPrimaryKey(true).TextAlign(TextAlign.Right).Width(125).Add();
col.Field("FirstName").HeaderText("First Name").Width(100).Add();
col.Field("LastName").HeaderText("Last Name").Width(100).Add();
col.Field("Title").HeaderText("Title").Width(150).Add();
col.Field("BirthDate").HeaderText("Birth Date").TextAlign(TextAlign.Right).Width(100).Format("{0:MM/dd/yyyy}").Add();
col.Field("Country").Width(100).HeaderText("Country").Add();
})
.ClientSideEvents(eve => { eve.CellEdit("cellEdit"); })
)
<script type="text/javascript">
function cellEdit(args)
{
var pkName = args.primaryKey[0];
var pkValue = args.rowData[pkName];
}
</script>
I am using the Chosen plugin in MVC razor and need to get the selected item id in onchange event:
<optgroup label="#col">
foreach (String[] colSub in sList)
{
<option id="#colSub[1]" class="opts">#colSub[0]</option>
}
</optgroup>
JQuery:
$('#chosen').on('change', function (evt, params) {
var selectedOption = params.selected; //gives me the selectedOption = #colSub[0]
var id = //i need the id here
}
In the above i need the ID also?
You can simply use
$('#chosen').on('change', function (evt, params) {
var id = $(this).find('option:selected').prop('id');
});
You can use use .map() to generate array of selected IDs
$("#chosen").on('change', function (evt, params) {
var SelectedIds = $(this).find('option:selected').map(function () {
return $(this).prop('id')
}).get();
console.log(SelectedIds);
})
DEMO