How to select from the database within a option that is filled with JavaScript - asp.net-core

I'm new to razor page
I have an edit page - that it has 2 selection tags
1 - "MissionTime" and the other - "MissionDay".
The choices in MissionDay vary according to the choice of MissionTime.
In terms of JavaScript it works great! On the Create page it works really well.
Also on the edit page it works well on the part of the JavaScript.
The problem is when the database has information () but it does not select according to the value in the database.
<div class = "col-sm-4">
<label asp-for = "Mission.MissionTime" class = "control-label"> </label>
<select id = "MissionTime" asp-for = "Mission.MissionTime">
<option value = "0">
with no
</option>
<option value = "1">
Every day
</option>
<option value = "7">
once a week
</option>
<option value = "30">
once a month
</option>
<option value = "365">
Once a year
</option>
</select>
</div> <div class = "col-sm-4">
<label asp-for = "Mission.MissionDay" class = "control-label"> </label>
<select id = "MissionDay" asp-for = "Mission.MissionDay">
<option value = "0">
with no
</option>
</select>
</div>
Code JavaScript -
<script>
$ (document) .ready (function () {
missionTime ();
$ ("#MissionTime"). Change (function () {
missionTime ();
});
$ ("#MissionDay"). Change (function () {
var d = new Date ();
var val = $ (this) .val ();
if (val == "Sunday") {
d.setDate (d.getDate () + ((7 - d.getDay ())% 7 + 0)% 7);
} else if (val == "Monday") {
d.setDate (d.getDate () + ((7 - d.getDay ())% 7 + 1)% 7);
} else if (val == "Tuesday") {
d.setDate (d.getDate () + ((7 - d.getDay ())% 7 + 2)% 7);
} else if (val == "Wednesday") {
d.setDate (d.getDate () + ((7 - d.getDay ())% 7 + 3)% 7);
} else if (val == "Thursday") {
d.setDate (d.getDate () + ((7 - d.getDay ())% 7 + 4)% 7);
}
else if (val == "startMonth") {
d.setMonth (d.getMonth () + 1, 1);
}
else if (val == "middleMonth") {
// if 15th of current month is over move to next month
// need to check whether to use> = or just> ie on 15th Jun
// if you want 15 Jun then use> else if you want 15 Jul use> =
var dt = d.getDate ();
d.setDate (15);
if (dt> = 15) {
d.setMonth (date.getMonth () + 1);
}
d.setHours (23, 59, 59, 0);
}
else if (val == "endMonth") {
d.setMonth (d.getMonth () + 1);
d.setDate (0);
}
else if (val == "firstYear") {
d = new Date (new Date (). getFullYear () +1, 0, 1);
}
else if (val == "lastYear") {
d = new Date (new Date (). getFullYear (), 11, 31);
}
var dd = String (d.getDate ()). padStart (2, '0');
var mm = String (d.getMonth () + 1) .padStart (2, '0'); // January is 0!
var yyyy = d.getFullYear ();
d = yyyy + '-' + mm + '-' + dd;
document.getElementById ("firstDate"). value = d;
}
);
function missionTime () {
var val = $ ("# MissionTime"). val ();
if (val == "1") {
$ ("#MissionDay"). Html ("<option value = '0'> without </option>");
today ();
} else if (val == "7") {
$ ("#MissionDay"). Html ("<option value = 'Sunday'> Sunday </option> <option value = 'Monday'> Monday </option> <option value = 'Tuesday'> Tuesday < / option> <option value = 'Wednesday'> Wednesday </option> <option value = 'Thursday'> Thursday </option> ");
var d = new Date ();
d.setDate (d.getDate () + ((7 - d.getDay ())% 7 + 0)% 7);
var dd = String (d.getDate ()). padStart (2, '0');
var mm = String (d.getMonth () + 1) .padStart (2, '0'); // January is 0!
var yyyy = d.getFullYear ();
d = yyyy + '-' + mm + '-' + dd;
document.getElementById ("firstDate"). value = d;
} else if (val == "30") {
. / option> ");
var d = new Date ();
d.setMonth (d.getMonth () + 1, 1);
var dd = String (d.getDate ()). padStart (2, '0');
var mm = String (d.getMonth () + 1) .padStart (2, '0'); // January is 0!
var yyyy = d.getFullYear ();
d = yyyy + '-' + mm + '-' + dd;
document.getElementById ("firstDate"). value = d;
} else if (val == "365") {
$ ("#MissionDay"). Html ("<option value = 'firstYear'> beginning of year </option> <option value = 'lastYear'> end of year </option>");
} else if (val == "0") {
$ ("#MissionDay"). Html ("<option value = '0'> without </option>");
today ();
}
}
function today () {
var today = new Date ();
var dd = String (today.getDate ()). padStart (2, '0');
var mm = String (today.getMonth () + 1) .padStart (2, '0'); // January is 0!
var yyyy = today.getFullYear ();
today = yyyy + '-' + mm + '-' + dd;
document.getElementById ("firstDate"). value = today;
}
});
</script>
The code works great!
The problem is that I can not get the data in the "MissionDay"
I guess this is because first the page takes data from the database and only then does it run the script. Anyone have any tips on how to solve this problem?
Best regards

The problem is when the database has information () but it does not select according to the value in the database.
Please note that the option(s) that you generate on JavaScript client could not be available when the Select Tag Helper is rendered. Therefore it does not set default selected option based on the data passed through Mission.MissionDay.
To achieve your requirement of setting the default selected option based on the stored MissionDay, you can try to store the data in a hidden field, then set the selected option in JavaScript code, like below.
Add a hidden field with id="hf_missionDay"
<label asp-for="Mission.MissionDay" class="control-label"> </label>
<input type="hidden" id="hf_missionDay" value="Mission.MissionDay" />
<select id="MissionDay" asp-for="Mission.MissionDay">
<option value="0">
with no
</option>
</select>
Set selected option based on the data store in hidden field
$(document).ready(function() {
missionTime();
SetSelectionOfMissionDay();
//...
//your code logic here
//...
SetSelectionOfMissionDay function
function SetSelectionOfMissionDay() {
var mday = $("#hf_missionDay").val();
$("select#MissionDay option[value='" + mday + "']").attr("selected", true);
//or
//$("select#MissionDay").val(mday);
}

Related

How Can I Add Website Decimal Quantity in Odoo

I Have a custom module website_decimal_quantity. after installing this module, In the website shop cart, when the user clicks on the + or - button to adjust quantity, It should add or deduct .1 value from it. i find out that a function onclickaddcartjson in the sale.variantmixin is responsible for the button click.i tried to extend the onclickaddcartjson function that present in the website_sale.website_sale. but it does not work.
Thanks For the Attention
My code is like :
publicWidget.registry.WebsiteSale.include({
onClickAddCartJSON: function (ev) {
ev.preventDefault();
var $link = $(ev.currentTarget);
var $input = $link.closest('.input-group').find("input");
var min = parseFloat($input.data("min") || 0);
var max = parseFloat($input.data("max") || Infinity);
var previousQty = parseFloat($input.val() || 0, 10);
var quantity = ($link.has(".fa-minus").length ? -0.1 : 0.1) + previousQty;
var newQty = quantity > min ? (quantity < max ? quantity : max) : min;
if (newQty !== previousQty) {
$input.val(newQty).trigger('change');
}
return false;
},
_changeCartQuantity: function ($input, value, $dom_optional, line_id, productIDs) {
_.each($dom_optional, function (elem) {
$(elem).find('.js_quantity').text(value);
productIDs.push($(elem).find('span[data-product-id]').data('product-id'));
});
$input.data('update_change', true);
this._rpc({
route: "/shop/cart/update_json",
params: {
line_id: line_id,
product_id: parseInt($input.data('product-id'), 10),
set_qty: value
},
}).then(function (data) {
$input.data('update_change', false);
var check_value = parseFloat($input.val());
if (isNaN(check_value)) {
check_value = 1;
}
if (value !== check_value) {
$input.trigger('change');
return;
}
if (!data.cart_quantity) {
return window.location = '/shop/cart';
}
wSaleUtils.updateCartNavBar(data);
$input.val(data.quantity);
$('.js_quantity[data-line-id='+line_id+']').val(data.quantity).text(data.quantity);
if (data.warning) {
var cart_alert = $('.oe_cart').parent().find('#data_warning');
if (cart_alert.length === 0) {
$('.oe_cart').prepend('<div class="alert alert-danger alert-dismissable" role="alert" id="data_warning">'+
'<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> ' + data.warning + '</div>');
}
else {
cart_alert.html('<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> ' + data.warning);
}
$input.val(data.quantity);
}
});
},
_onChangeCartQuantity: function (ev) {
var $input = $(ev.currentTarget);
if ($input.data('update_change')) {
return;
}
var value = parseFloat($input.val());
if (isNaN(value)) {
value = 1;
}
var $dom = $input.closest('tr');
// var default_price = parseFloat($dom.find('.text-danger > span.oe_currency_value').text());
var $dom_optional = $dom.nextUntil(':not(.optional_product.info)');
var line_id = parseInt($input.data('line-id'), 10);
var productIDs = [parseInt($input.data('product-id'), 10)];
this._changeCartQuantity($input, value, $dom_optional, line_id, productIDs);
},
})
The change that I made is in _onclickaddcartjson; change the line
var quantity = ($link.has(".fa-minus").length ? -0.1 : 0.1) + previousQty;
and in _changeCartQuantity, change the check_value into:
var check_value = parseFloat($input.val())
And in _onChangeCartQuantity, change the value into:
var value = parseFloat($input.val()).
Even if I made these changes in source file without my custom module, the quantity increase or decrease by .1. But it automatically turns into an integer value. That means when I click on the + button, the value changes to 1.1, but it immediately changes to 1. Also, if I click on the - button, it will changes to 2.9 from 3, then it changes to 2 as its value. If anybody has an idea about this please share. Thanks for the attention.
Yes, it 's possible as the type of the underlying field in model SaleOrderLine is Float. And in website_sale/models/sale_order.py : int(sum(order.mapped('website_order_line.product_uom_qty'))) needs to be reülaced by: sum(order.mapped('website_order_line.product_uom_qty')):
class SaleOrderLine(models.Model):
_name = 'sale.order.line'
product_uom_qty = fields.Float(string='Quantity', digits='Product Unit of Measure', required=True, default=1.0)
#api.depends('order_line.product_uom_qty', 'order_line.product_id')
def _compute_cart_info(self):
for order in self:
order.cart_quantity = sum(order.mapped('website_order_line.product_uom_qty'))
order.only_services = all(l.product_id.type in ('service', 'digital') for l in order.website_order_line)
The underlying python method to add quantity is located in addons module website_sale/models/sale_oder.py :
def _cart_update(self, product_id=None, line_id=None, add_qty=0, set_qty=0, **kwargs):
""" Add or set product quantity, add_qty can be negative """
self.ensure_one()
product_context = dict(self.env.context)
product_context.setdefault('lang', self.sudo().partner_id.lang)
SaleOrderLineSudo = self.env['sale.order.line'].sudo().with_context(product_context)
...
...which is called by 2 methods in website_sale/controllers/main.py :
#http.route(['/shop/cart/update'], type='http', auth="public", methods=['GET', 'POST'], website=True, csrf=False)
def cart_update(self, product_id, add_qty=1, set_qty=0, **kw):
AND
#http.route(['/shop/cart/update_json'], type='json', auth="public", methods=['POST'], website=True, csrf=False)
def cart_update_json(self, product_id, line_id=None, add_qty=None, set_qty=None, display=True):
"""This route is called when changing quantity from the cart or adding
a product from the wishlist."""
"""This route is called when adding a product to cart (no options)."""
This controller method cart_update_json is called in sale/.../js/variant_mixin.js by:
onClickAddCartJSON: function (ev) {
ev.preventDefault();
var $link = $(ev.currentTarget);
var $input = $link.closest('.input-group').find("input");
var min = parseFloat($input.data("min") || 0);
var max = parseFloat($input.data("max") || Infinity);
var previousQty = parseFloat($input.val() || 0, 10);
var quantity = ($link.has(".fa-minus").length ? -1 : 1) + previousQty;
var newQty = quantity > min ? (quantity < max ? quantity : max) : min;
if (newQty !== previousQty) {
$input.val(newQty).trigger('change');
}
return false;
},
...where: var quantity = ($link.has(".fa-minus").length ? -1 : 1) + previousQty; shows us that is incremented +1 oder -1
That s why you need to override this function in website_sale/.../website_sale.js to integrate:
var $parent = $(ev.target).closest('.js_product');
var product_id = this._getProductId($parent);
if product_id == yourspecificproductid
var quantity = ($link.has(".fa-minus").length ? -0.1 : 0.1) +
previousQty;
else
var quantity = ($link.has(".fa-minus").length ? -1 : 1) +
previousQty;
When quantity input value is changed automatically, it might be caused by parseInt($input.val()) in _onChangeCartQuantity in the file: website_sale.js:
_onChangeCartQuantity: function (ev) {
var $input = $(ev.currentTarget);
if ($input.data('update_change')) {
return;
}
var value = parseFloat($input.val() || 0, 10);
if (isNaN(value)) {
value = 1;
}
var $dom = $input.closest('tr');
// var default_price = parseFloat($dom.find('.text-danger > span.oe_currency_value').text());
var $dom_optional = $dom.nextUntil(':not(.optional_product.info)');
var line_id = parseInt($input.data('line-id'), 10);
var productIDs = [parseInt($input.data('product-id'), 10)];
this._changeCartQuantity($input, value, $dom_optional, line_id, productIDs);
},

Use filter in Vue3 but can't read globalProperties

Just a quick question,
I know that Vue3 doesn't use filters anymore and notes says use computed or methd instead. but also there is a globalProperties we can use,
I used this globalProperties but keep getting this error
Uncaught TypeError: Cannot read property 'globalProperties' of undefined
Does anyone know where is the bug in my code?
const app = {
data() {
return {
message: ""
}
}
}
app.config.globalProperties.$filters = {
formatDate(value) {
if (value == "0001-01-01T00:00:00")
return "";
var today = new Date(value);
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();
today = dd + '/' + mm + '/' + yyyy;
return today;
}
}
Vue.createApp(app).mount('#app');
And I am using the filter in my table like this
<td>
{{ $filters.formatDate(incident.incidentData) }}
</td>
The config field belongs to the root instance not to the root component so you should do:
const app = {
data() {
return {
message: ""
}
}
}
const myApp=Vue.createApp(app)
myApp.config.globalProperties.$filters = {
formatDate(value) {
if (value == "0001-01-01T00:00:00")
return "";
var today = new Date(value);
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();
today = dd + '/' + mm + '/' + yyyy;
return today;
}
}
myApp.mount('#app');
Vue.createApp(app) return the root instance
myApp.mount('#app'); after mounting root app to an element it returns the root component

Can't perform credit card formatting in angular reactive form

I am trying to perform credit card validator i.e adding space after every fourth digit like 1111 1111 1111 1111. But somehow I can't get work done.
Here is what I have tried.
Thank you in advance
html
<ion-item>
<ion-label position="floating">Card number</ion-label>
<ion-input type ="tel" formControlName = "cardnumber" keypress ="cc_format($evet)" ></ion-input>
</ion-item>
ts
cc_format(value) {
var v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '')
var matches = v.match(/\d{4,16}/g);
var match = matches && matches[0] || ''
var parts = []
for (let i=0, len=match.length; i<len; i+=4) {
parts.push(match.substring(i, i+4))
}
if (parts.length > 0) {
return parts.join(' ')
} else {
return value
}
}
First let's use ionChange to get the changed value from your input. Connect your input with the creditCardNumber defined in the ts file. Now convert the credit card number and add it to the dynamic variable.
<ion-item>
<ion-label position="floating">Card number</ion-label>
<ion-input type ="tel" formControlName="cardnumber" (ionChange)="cc_format($event.target.value)" [(ngModel)]="creditCardNumber"></ion-input>
</ion-item>
creditCardNumber: string;
cc_format(value: string) {
const v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '');
const matches = v.match(/\d{4,16}/g);
const match = (matches && matches[0]) || '';
const parts = [];
for (let i = 0, len = match.length; i < len; i += 4) {
parts.push(match.substring(i, i + 4));
}
if (parts.length > 0) {
this.creditCardNumber = parts.join(' ');
} else {
this.creditCardNumber = value;
}
}

Dojo dgrid: Filter data from store with diffrent fields when I click on filter button

I am using 'dgrid/Grid' and dstore/RequestMemory for creating grid and storing data. Now I want to filter data according to values in the fields(see img). I am not sure how to filter data when using simple Dgrid and dstore.
var structure = [{
label : "Value Date",
field : "valueDate"
}, {
id: "currencyCol",
label : "Currency",
field : "currency"
}, {
label : "Nostro",
field : "nostroAgent"
}];
var store= new RequestMemory({
target: 'getReportData',
idProperty: "cashflowId",
headers: structure
});
// Create an instance of OnDemandGrid referencing the store
var grid = new(declare([Grid, Pagination, Selection]))({
collection: store,
columns: structure,
loadingMessage: 'Loading data...',
noDataMessage: 'No results found.',
minRowsPerPage: 50,
}, 'grid');
grid.startup();
on(document.getElementById("filter"), "click", function(event) {
event.preventDefault();
grid.set('collection', store.filter({
**currencyCol: "AED"**
.
.
.
}));
Any help would be appreciated or suggest if I use some diffrent store or grid.
I got the solution for my question. On filter button click I have written all my filtering logic and the final store will set to dgrid:
on(document.getElementById("filter"), "click", function(event) {
var store= new RequestMemory({
target: 'getReportData',
idProperty: "cashflowId",
headers: structure
});
var from=dijit.byId('from').value;
var to=dijit.byId('to').value;
var curr=dijit.byId('currency').value;
var nos=dijit.byId('nostro').value;
var authStatus=dijit.byId('authStatus').value;
var filterStore;
var finalStore=store;
var filter= new store.Filter();
var dateToFindFrom;
var dateToFindTo;
if (from != "" && from !== null) {
var yyyy = from.getFullYear().toString();
var mm = ((from.getMonth()) + 1).toString(); // getMonth() is zero-based
var dd = from.getDate().toString();
if(mm <= 9){
mm= "0" + mm;
}
if(dd <= 9){
dd= "0" + dd;
}
dateToFindFrom =yyyy + mm + dd;
filterStore= filter.gte('valueDate', dateToFindFrom);
finalStore=finalStore.filter(filterStore);
}
if (to != "" && to !== null) {
var yyyy = to.getFullYear().toString();
var mm = ((to.getMonth()) + 1).toString(); // getMonth() is zero-based
var dd = to.getDate().toString();
if(mm <= 9){
mm= "0" + mm;
}
if(dd <= 9){
dd= "0" + dd;
}
dateToFindTo =yyyy + mm + dd;
filterStore= filter.lte('valueDate', dateToFindTo); //.lte('valueDate', dateToFindTo);
finalStore=finalStore.filter(filterStore);
}
if(curr != "" && curr !== null) {
filterStore= filter.eq('currency', curr);
finalStore=finalStore.filter(filterStore);
}
if(nos != "" && nos !== null) {
filterStore= filter.eq('nostroAgent',nos);
finalStore=finalStore.filter(filterStore);
}
if(authStatus != "" && authStatus !== null) {
if (authStatus=='ALL') {
var both= [true, false];
filterStore= filter.in('approved', both);
finalStore=finalStore.filter(filterStore);
} else if (authStatus=='Authorised Only') {
filterStore= filter.eq('approved', true);
finalStore=finalStore.filter(filterStore);
} else if (authStatus=='Unauthorised Only') {
filterStore= filter.eq('approved', false);
finalStore=finalStore.filter(filterStore);
};
};
grid.set('collection', finalStore);
});

Format Textbox input for phone number MVC

I am simply using a #Html.TextBoxFor(m => m.PhoneNumber, new { id = "phoneNo")
I am using a regex to limit it to 10 numbers only.
Is there a way I can format the textbox to appear like (555) 444-3333 while they type, but in the model it will simply be passing the 10 numbers, like 5554443333? I meant to automatically create those brackets and - while also checking using regex if they entered 10 numbers?
You can do it with jquery as Matt said at his comment, stated at this question of the site:
Phone mask with jQuery and Masked Input Plugin
Or with plain javascript, as explained by xxx here with alternatives too:
Mask US phone number string with JavaScript
List of alternatives coded for a example input called "phone":
Example code with plain javaScript:
document.getElementById('phone').addEventListener('input', function (e) {
var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
});
Example code with jQuery but without adding any new dependence():
$('#phone', '#example-form')
.keydown(function (e) {
var key = e.which || e.charCode || e.keyCode || 0;
$phone = $(this);
// Don't let them remove the starting '('
if ($phone.val().length === 1 && (key === 8 || key === 46)) {
$phone.val('(');
return false;
}
// Reset if they highlight and type over first char.
else if ($phone.val().charAt(0) !== '(') {
$phone.val('('+$phone.val());
}
// Auto-format- do not expose the mask as the user begins to type
if (key !== 8 && key !== 9) {
if ($phone.val().length === 4) {
$phone.val($phone.val() + ')');
}
if ($phone.val().length === 5) {
$phone.val($phone.val() + ' ');
}
if ($phone.val().length === 9) {
$phone.val($phone.val() + '-');
}
}
// Allow numeric (and tab, backspace, delete) keys only
return (key == 8 ||
key == 9 ||
key == 46 ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
})
.bind('focus click', function () {
$phone = $(this);
if ($phone.val().length === 0) {
$phone.val('(');
}
else {
var val = $phone.val();
$phone.val('').val(val); // Ensure cursor remains at the end
}
})
.blur(function () {
$phone = $(this);
if ($phone.val() === '(') {
$phone.val('');
}
});
Example code with jQuery using Masked Input Plugin:
$("#phone").mask("(99) 9999?9-9999");
$("#phone").on("blur", function() {
var last = $(this).val().substr( $(this).val().indexOf("-") + 1 );
if( last.length == 3 ) {
var move = $(this).val().substr( $(this).val().indexOf("-") - 1, 1 );
var lastfour = move + last;
var first = $(this).val().substr( 0, 9 );
$(this).val( first + '-' + lastfour );
}
});