How to set date mask in fields - javascript

How can I set mask on date fields, date from and date to.
Here is my code below
<div class="col-md-6">
Year_from
#Html.TextBoxFor(model => model.yfrom, new { #class = "form-control", maxlength = "10", minlength="4" })
</div>
<div class="col-md-6">
Year_to
#Html.TextBoxFor(model => model.yto, new { #class = "form-control", maxlength = "10", minlength = "4" })
</div>
<script>
jQuery(function ($) {
$("#yfrom").mask("99.99.9999");
$("#yto").mask("99.99.9999");
});
var v = this.value;
if (v.match(/^\d{2}$.) !== null) {
this.value = v + '.';
} else if (v.match(/^\d{2}\/\d{2}$.) !== null) {
this.value = v + '.';
}
</script>
</div>
I tried to include jQuery function to this, but still not working, I need something that would show error on date field when someone input wrong values in first field and switch to another one.

Related

enable/disable radio buttons from drop down menu selection in razor

I have a view like below
#Html.DropDownListFor(m => m.Student, (List<SelectListItem>)ViewBag.Students, new { #id = "inputtext", #class = "form-control"})
<div class="form-group">
#Html.LabelFor(m => m.Teacher, new { #class = "control-label col-sm-2" })
<div class="col-sm-10">
#Html.RadioButtonFor(m => m.Teacher, "1")<span>A Transfer</span>
#Html.RadioButtonFor(m => m.Teacher, "2")<span>B</span>
#Html.RadioButtonFor(m => m.Teacher, "3")<span>C</span>
</div>
</div>
I need a script that will enable/disable radio buttons based on specific drop down menu selections. if the dropdown has a value of 1, then all the radiobutton will be disabled. and if the dropdown does not have a value of 1, the radiobutton will be enabled.
I'm confused doing it in the razor View. Please Help :)
I have used this code to enable/disable the textbox depending upon dropdown selection . Replace ("NO") with your's radio button name and also (opts.value == 'Y') Y with 1
function updateTextBox(opts) {
var chks = document.getElementsByName("NO");
if (opts.value == 'Y') {
for (var i = 0; i <= chks.length - 1; i++) {
chks[i].disabled = false;
}
}
else {
for (var i = 0; i <= chks.length - 1; i++) {
chks[i].disabled = true;
chks[i].checked = false;
}
}
}

Sum of Rows in Jquery

What I'm doing right now is to fetch values by their id in J Query and it is working fine.
But to do this I have to assign every control different id's (Duplicate Id does not give result on second row) .
JS
$('#Qty,#Price,#Disc').on('input', function () {
var val1 = Number($('#Qty').val());
var val2 = Number($('#Price').val());
var val3 = isNaN(Number($('#Disc').val())) ? 0 : Number($('#Disc').val());
var total = isNaN(val1 * val2) ? 0 : (val1 * val2);
$('#TotalAmount').val(total - (total * (val3 / 100)));
$('#NetAmt').val($('#TotalAmount').val());
});
$('#Qty1,#Price1,#Disc1').on('input', function () {
var val1 = Number($('#Qty1').val());
var val2 = Number($('#Price1').val());
var val3 = isNaN(Number($('#Disc1').val())) ? 0 : Number($('#Disc1').val());
var total = isNaN(val1 * val2) ? 0 : (val1 * val2);
$('#TotalAmount1').val(total - (total * (val3 / 100)));
$('#NetAmt').val(Number($('#TotalAmount').val()) + Number($('#TotalAmount1').val()));
});
RAZOR
<div style="padding:10px" class="row">
<div class="left">
#Html.EditorFor(model => model.a, new { htmlAttributes = new { Type = "Text", placeholder = "ProductName" } })
</div>
<div class="left">
#Html.EditorFor(model => model.b, new { htmlAttributes = new { id = "Qty", Type = "Text", placeholder = "Qty" } })
</div>
<div class="left">
#Html.EditorFor(model => model.c, new { htmlAttributes = new { id = "Price", Type = "Text", placeholder = "Price" } })
</div>
<div class="left">
#Html.EditorFor(model => model.d, new { htmlAttributes = new { id = "Disc", Type = "Text", placeholder = "Discount" } })
</div>
<div class="left">
#Html.EditorFor(model => model.e, new { htmlAttributes = new { id = "TotalAmount", Type = "Text", placeholder = "Total Amount" } })
</div>
<div class="left">
#Html.EditorFor(model => model.f, new { htmlAttributes = new { Type = "Text", placeholder = "Remarks" } })
</div>
</div>
<div style="padding:10px" class="row">
<div class="left">
#Html.EditorFor(model => model.a, new { htmlAttributes = new { Type = "Text", placeholder = "ProductName" } })
</div>
<div class="left">
#Html.EditorFor(model => model.b, new { htmlAttributes = new { id = "Qty1", Type = "Text", placeholder = "Qty" } })
</div>
<div class="left">
#Html.EditorFor(model => model.c, new { htmlAttributes = new { id = "Price1", Type = "Text", placeholder = "Price" } })
</div>
<div class="left">
#Html.EditorFor(model => model.d, new { htmlAttributes = new { id = "Disc1", Type = "Text", placeholder = "Discount" } })
</div>
<div class="left">
#Html.EditorFor(model => model.e, new { htmlAttributes = new { id = "TotalAmount1", Type = "Text", placeholder = "Total Amount" } })
</div>
<div class="left">
#Html.EditorFor(model => model.f, new { htmlAttributes = new { Type = "Text", placeholder = "Remarks" } })
</div>
</div>
What I've tried before is to change id to #class on my RAZOR Page 'ClassName' without numeric identifier (Example id = Qty and id = qty1 changed to #class=Qty).
JS
$('.row').each(function(){
$('.Qty,.Price,.Disc').on('input', function () {
var val1 = Number($('.Qty').val());
var val2 = Number($('.Price').val());
var val3 = isNaN(Number($('.Disc').val())) ? 0 : Number($('.Disc').val());
var total = isNaN(val1 * val2) ? 0 : (val1 * val2);
});
$('.TotalAmount1').val(total - (total * (val3 / 100)));
$('.NetAmt').val(Number($('.TotalAmount').val()));
});
Kindly guide me.
Basic Concept of Sum of row is like this , use your logic and implement
sum =0;
$('.row').each(function(e){
sum +=parseInt($($('.row')[e]).html());
})
console.log(sum);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="order_table">
<tr>
<th>NAME</th>
<th>value</th>
<tr>
<tr>
<td>John</td>
<td class='row'>123</td>
<tr>
<tr>
<td>Harry</td>
<td class='row'>23</td>
<tr>
</table>
Update :
$('tr').each(function () {
var sum = 0
$(this).find('.row').each(function () {
var row = $(this).text();
sum += parseFloat(row);
console.log(sum);
});
$('.result', this).val(sum);
})
https://jsfiddle.net/bo4g76ra/4/
I've Done this way.
$("#ProData").on("keyup", ".Qty,.Disc,.Price,.Cell", function (e) {
e.preventDefault();
var Qty = Number($(this).parent().find('.Qty').val());
var Price = Number($(this).parent().find('.Price').val());
var Disc = Number($(this).parent().find('.Disc').val());
var TWDisc = isNaN(Qty * Price) ? 0 : (Qty * Price);
var Total = (TWDisc - (TWDisc * (Disc / 100)))
$(this).parent().find('.TotalAmount').val(Total);
var sum = 0;
$(".TotalAmount").each(function () {
sum += +$(this).val();
});
$("#NetAmt").val(sum);
});

Update Birthday using Year and Month values

I'm trying to display and update a child's age through a MM/dd/YYYY textbox, and simple int values in year(s) and month(s) textboxes.
So if a child had a birthday of: 02/03/2015, and I'm comparing against today's date of 03/07/2018, the Year textbox should say 3 and the month textbox should say 1
If you were to change the year value to 5, the DoB value should change to 02/03/2013.
If you were to then change the month value to 9, the DoB value should change to 05/03/2012.
If I were to change the DoB value, the Year and Month textbox should also change to the appropriate values.
The day value should be persisted, and changed to 01 when it can't.
I would like to of course account for odd date arithmetic.
What I have so far in my C# MVC app is that I have a ChildViewModel object with these properties:
DateTime? DateOfBirth
public int AgeMonths
public int AgeYears
On my view, I have a textbox for each of these values.
<div class="row">
<div class="form-group">
#Html.LabelFor(m => m.DateOfBirth, new { #class = "control-label" })
#Html.TextBoxFor(m => m.DateOfBirth, "{0:MM/dd/yyyy}", new { #class = "form-control", placeholder = "Child's Date of Birth", onchange = "determineAge(this.id, null, null)" })
</div>
<div class="form-group">
#Html.LabelFor(m => m.AgeYears, new { #class = "control-label" })
#Html.TextBoxFor(m => m.AgeYears, new { #class = "form-control", placeholder = "x years and...", onchange = "determineAge(null, this.id, null)" })
</div>
<div class="form-group">
#Html.LabelFor(m => m.AgeMonths, new { #class = "control-label" })
#Html.TextBoxFor(m => m.AgeMonths, new { #class = "form-control", placeholder = "...y months old", onchange = "determineAge(null, null, this.id)" })
</div>
</div>
Here is my JavaScript so far, slightly altered to work in the snippet, using a little bit of moment.js v2.21.0
https://jsfiddle.net/RyanTaite/fak22xrf
The snippet below is effectively the same code:
function determineAge(dobId, ageYearsId, ageMonthsId) {
///<summary>Updates the Date of Birth, Years, and/or Months text box(es) based on what's passed in. It's likely terribly written and I'd welcome a rewrite by someone better at date math. Dependant on moment.js</summary>
var dobValue = null;
var yearValue = null;
var monthValue = null;
var today = new Date();
// Update DOB, AgeYears, and AgeMonths based on who was changed
if (dobId !== null) {
dobValue = new Date(document.getElementById(DateOfBirth.value));
var ageInMonths = today.getMonth() - dobValue.getMonth() + (12 * (today.getFullYear() - dobValue.getFullYear()));
yearValue = Math.floor(ageInMonths / 12);
monthValue = ageInMonths % 12;
document.getElementById('AgeYears').value = yearValue;
document.getElementById('AgeMonths').value = monthValue;
} else if (ageYearsId !== null) {
yearValue = document.getElementById('AgeYears').value;
monthValue = document.getElementById('AgeMonths').value;
dobValue = new Date(document.getElementById('DateOfBirth').value);
dobValue.setFullYear(today.getFullYear() - yearValue);
document.getElementById('DateOfBirth').value = dobValue.toLocaleDateString();
} else if (ageMonthsId !== null) {
dobValue = new moment(new Date());
monthValue = parseInt(document.getElementById('AgeMonths').value);
yearValue = parseInt(document.getElementById('AgeYears').value);
var dayValue = new moment(document.getElementById('DateOfBirth').value, "MMDDYYYY").get('date');
var totalMonths = monthValue + (yearValue * 12);
dobValue.subtract(totalMonths, "months");
// This is the proper way to set the day value of a moment object, you have to chain your way there
dobValue.year(dobValue.get('year')).month(dobValue.get('month')).date(dayValue);
document.getElementById('DateOfBirth').value = moment(dobValue._d).format("MM/DD/YYYY");
}
}
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="form-group">
<div class="control-label">Date of Birth</div>
<input class="form-control" id="DateOfBirth" placeholder="Child's Date of Birth" onchange="determineAge(this.id, null, null)"></input>
</div>
<div class="form-group">
<div class="control-label">Years</div>
<input class="form-control" id="AgeYears" placeholder="x years and..." onchange="determineAge(null, this.id, null)"></input>
</div>
<div class="form-group">
<div class="control-label">Months</div>
<input class="form-control" id="AgeMonths" placeholder="...y months old" onchange="determineAge(null, null, this.id)"></input>
</div>
</div>
It's buggy and likely terribly written, so I'd love some help with this.
I believe I fixed it using diff and general moment properties more, as Matt's comment suggested.
If nothing else, it's cleaner and closer to what I wanted.
I welcome anyone's suggestions or edits to improve this.
function determineAge(dobId, ageYearsId, ageMonthsId) {
///<summary>Updates the Date of Birth, Years, and/or Months text box(es) based on what's passed in. Dependant on moment.js</summary>
var dobValue = null;
var yearValue = null;
var monthValue = null;
var today = new moment();
// Update DOB, AgeYears, and AgeMonths based on who was changed
if (dobId !== null) {
dobValue = new moment(document.getElementById('DateOfBirth').value, "MMDDYYYY");
yearValue = new moment().diff(dobValue, 'years');
monthValue = new moment().diff(dobValue, 'month') % 12;
document.getElementById('AgeYears').value = yearValue;
document.getElementById('AgeMonths').value = monthValue;
} else if (ageYearsId !== null || ageMonthsId !== null) {
yearValue = parseInt(document.getElementById('AgeYears').value);
monthValue = parseInt(document.getElementById('AgeMonths').value);
dobValue = new moment(document.getElementById('DateOfBirth').value, "MMDDYYYY");
const ageInMonths = (yearValue * 12) + (monthValue);
const todayMinusMonths = today.subtract(ageInMonths, 'months');
const dayValue = dobValue.date();
dobValue = todayMinusMonths;
dobValue.date(dayValue);
document.getElementById('DateOfBirth').value = dobValue.format("MM/DD/YYYY");
}
}
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="form-group">
<div class="control-label">Date of Birth</div>
<input class="form-control" id="DateOfBirth" placeholder="MM/dd/YYYY" onchange="determineAge(this.id, null, null)">
</div>
<div class="form-group">
<div class="control-label">Years</div>
<input class="form-control" id="AgeYears" placeholder="x years and..." onchange="determineAge(null, this.id, null)">
</div>
<div class="form-group">
<div class="control-label">Months</div>
<input class="form-control" id="AgeMonths" placeholder="...y months old" onchange="determineAge(null, null, this.id)">
</div>
</div>

Jquery document on change: can I use variable as selector?

I am very new to javascript and jQuery. In my view, I have a List of QuoteDetails, as follows:
<div class="col-md-10" id="QuoteDetails">
#for (int i = 0; i < Model.QuoteDetail.Count; i++)
{
<div id="row">
#Html.HiddenFor(model => model.QuoteDetail[i].QuoteId, new { htmlAttributes = new { #class = "form-control" } })
#Html.HiddenFor(model => model.QuoteDetail[i].QuoteDetailId, new { htmlAttributes = new { #class = "form-control" } })
#Html.EditorFor(model => model.QuoteDetail[i].ProductId, new { htmlAttributes = new { #id = "PId", #class = "form-control", style = "width: 75px" } })
#Html.EditorFor(model => model.QuoteDetail[i].ProductName, new { htmlAttributes = new { #id = "Product", #class = "form-control", style = "width: 300px" } })
#Html.EditorFor(model => model.QuoteDetail[i].Amount, new { htmlAttributes = new { #class = "form-control", style = "width: 95px" } })
#Html.EditorFor(model => model.QuoteDetail[i].ListPrice, new { htmlAttributes = new { #id = "Lprice", #class = "form-control", style = "width: 95px" } })
#Html.EditorFor(model => model.QuoteDetail[i].Discount, new { htmlAttributes = new { #class = "form-control", style = "width: 100px" } })
#Html.EditorFor(model => model.QuoteDetail[i].Price, new { htmlAttributes = new { #id = "Pr", #class = "form-control", style = "width: 100px" } })
#Html.ValidationMessageFor(model => model.QuoteDetail, "", new { #class = "text-danger" })
}
When either the Amount or Discount is changed by the user, I want to recalculate the Price. I am trying to solve it with the following javascript/jQuery:
<script type="text/javascript">
$(document).ready(function () {
var quoteDetails = $('[name*="QuoteDetailId"]');
var amounts = $('[id*="Amount"]')
var discounts = $('[id*="Discount"]')
var prices = $('[id*="Price"]')
var listPrices = $('[id*="LPrice"]')
for (var i = 0; i < quoteDetails.length; i++) {
$(document).on("change", discounts[i], amounts[i], function calculate() {
var finalPrice = $(amounts[i]).val() * ($(listPrices[i]).val() * ((100 - $(discount[i]).val()) / 100))
$(prices[i]).val(finalPrice);
});
};
});
</script>
Is there a way to use variables with indices as jQuery selectors in the document.on change? Any help will be much appreciated.
Give your elements class names, e.g
#Html.EditorFor(m=> m.QuoteDetail[i].Amount, new { htmlAttributes = new { #class = "form-control amount"} })
and change the container to <div class="row">
(ditto for discount, listprice and price)
Then your script becomes
$('.amount, .discount').change(function() {
// Get container
var row = $(this).closest('.row');
// Get values
var amount = Number(row.find('.amount').val());
var listprice = Number(row.find('.listprice').val());
var discount = Number(row.find('.discount').val());
// Validate
if (isNaN(amount) || isNaN(listprice) || isNaN(discount))
{
return; // may want to display an error message?
}
// Calculate
var finalPrice = amount * listprice * ((100 - discount) / 100)
// Update
row.find('.price').val(finalPrice);
})
A few things to note:
Duplicate id attributes are invalid html - remove all your new {
#id = ".." code.
Because of your class names, you can now style the widths - e.g.
.price { width: 95px; }
Convert the values to a Number and check
that the value is valid using isNaN before doing the calculation
Since Price is a calculated field, it should not be editable in the
view (or have a setter in the model. Use a <div> or similar
element to display it (and then use
row.find('.price').text(finalPrice); to set it
Note also that .on() is not necessary unless your dynamically adding those elements after the view has been first generated.

Select option from DropDown and automaticly set value in another TextField ASP .NET MVC

I would like to choose an option from the dropdown menu and based on the selected option automaticly set the value in the second input field.
Like this:
I created javascript code but its not working properly.
$(function () {
$("#artikel").keyup(function (e) {
var val1 = $("#artikel").val(),
result = "";
if (val1.match = "Spletna aplikacija")
result = 5;
if (val1.match = "Namizna aplikacija")
result = 10;
if (val1.match = "Mobilna aplikacija")
result = 13;
if (val1.match = "Spletna stran")
result = 20;
$("#cena").val(result);
});
});
Here is my .cshtml file (partial):
<div class="form-group">
#Html.LabelFor(model => model.artikel, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.artikel, new SelectList(new[] { String.Empty, "Spletna aplikacija - 5€", "Namizna aplikacija - 10€", "Mobilna aplikacija - 13€", "Spletna stran - 20€" } ))
#Html.ValidationMessageFor(model => model.artikel, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.cena, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.cena, new { htmlAttributes = new { #class = "#artikel" } })
#Html.ValidationMessageFor(model => model.cena, "", new { #class = "text-danger" })
</div>
</div>
And my controler POST Code:
public ActionResult Create()
{
ViewBag.zapStDoumenta_tk = new SelectList(db.dokumentGlava, "zapStDokumenta", "kodaRacuna");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "zapStPostavke,artikel,kolicina,zapStDoumenta_tk,cena,popust,davek,znesek")] postavkaDokumenta postavkaDokumenta)
{
if (ModelState.IsValid)
{
db.postavkaDokumenta.Add(postavkaDokumenta);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.zapStDoumenta_tk = new SelectList(db.dokumentGlava, "zapStDokumenta", "kodaRacuna", postavkaDokumenta.zapStDoumenta_tk);
return View(postavkaDokumenta);
}
Can you guys plase help me, what im doing wrong?
Much thanks!
Your function should be like below
$(function () {
$("#artikel").change(function (e) {
var val1 = $("#artikel").val(),
result = "";
if (val1 == "Spletna aplikacija - 5€")
result = 5;
if (val1 == "Namizna aplikacija - 10€")
result = 10;
if (val1 == "Mobilna aplikacija - 13€")
result = 13;
if (val1 == "Spletna stran - 20€")
result = 20;
$("#cena").val(result);
});
});
Based on you cshtml , i have tried to create a sample html. You can use the below code which match the value of the option with the current value of the select.
$(function() {
$("#artikel").change(function(e) {
var val1 = $("#artikel").val(),
result = "";
if (val1.match("Spletna aplikacija") != null)
result = 5;
if (val1.match("Namizna aplikacija") !== null)
result = 10;
if (val1.match("Mobilna aplikacija") !== null)
result = 13;
if (val1.match("Spletna stran") !== null)
result = 20;
$("#cena").val(result);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label>Artikel</label>
<div class="col-md-10">
<select id="artikel">
<option "">Select</option>
<option "Spletna aplikacija - 5€">Spletna aplikacija - 5€</option>
<option "Namizna aplikacija - 10€">Namizna aplikacija - 10€</option>
<option "Mobilna aplikacija - 13€">Mobilna aplikacija - 13€</option>
<option "Spletna stran - 20€">Spletna stran - 20€</option>
</select>
</div>
</div>
<div class="form-group">
<label>Cena</label>
<div class="col-md-10">
<input id="cena" value="">
</div>
</div>
Change your javascript code as mentioned bellow.
$(function () {
$("#artikel").change(function () {
var val1 = $(this).val();
var result = "";
switch (val1) {
case "Spletna aplikacija - 5€":
result = 5;
break;
case "Namizna aplikacija - 10€":
result = 10;
break;
case "Mobilna aplikacija - 13€":
result = 13;
break;
case "Spletna stran - 20€":
result = 20;
break;
}
$("#cena").val(result);
});
});

Categories

Resources