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

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.

Related

How to set date mask in fields

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.

setting the readonly value in the html table for a specific line at the start of the form

I try to set readonly fields for specific lines where "sth" is set in select box
the code is executed when the page is loaded / at the start of the form
i tried:
.js file
$(document).ready(function () {
$(".ecp-row").each(function () {
var start = $(this).find(".start");
var end = $(this).find(".end");
var hours = $(this).find(".gethours");
var selectboxlist = $(this).find(".selectboxlist").eq(0).val();
if (selectboxlist === "sth") {
alert("test"); // it works
start.readOnly = true; // it doesnt work
end.readOnly = true; // it doesnt work
hours.readOnly = true; // it doesnt work
}
});
});
html
#for (int nr_rows = 0; nr_rows < #ViewBag.sthelse; nr_rows++)
{
<tr class="ecp-row">
<td id="td3" >#Html.TextBoxFor(m => m.Model7[nr_rows].a, new { #class = "start"})</td>
<td id="td4" >#Html.TextBoxFor(m => m.Model7[nr_rows].b, new { #class = "end" })</td>
<td id="td5" >#Html.TextBoxFor(m => m.Model7[nr_rows].c, new { #class = "gethours" })</td>
<td id="td6" >#Html.DropDownListFor(m => m.Model7[nr_rows].sth, new SelectList(Enum.GetValues(typeof(sth))), " ", new { #class = "selectboxlist" })</td>
</tr>
}
As stated in the comment, you problem is that you are trying to execute javascript code on a jquery object.
You can either use start[0].readOnly = true; or start.attr("readOnly","true");
Demo
$(document).ready(function() {
$(".ecp-row").each(function() {
var start = $(this).find(".start");
alert("test"); // it works
//start[0].readOnly = true;
start.attr("readOnly","true");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
<tr class="ecp-row">
<td id="td3"><input class="start" /></td>
</tr>
</tbody>
</table>
If you want to change readonly,you can use prop or attr:
prop:
var start = $(this).find(".start");
start.prop("readonly", true);
attr:
var gethours = $(this).find(".gethours");
gethours.attr("readonly", true);
And here's the difference between them.
demo:
#for (int nr_rows = 0; nr_rows < #ViewBag.sthelse; nr_rows++)
{
<tr class="ecp-row">
start<td id="td3">#Html.TextBoxFor(m => m.Model7[nr_rows].a, new { #class = "start" })</td>
end<td id="td4">#Html.TextBoxFor(m => m.Model7[nr_rows].b, new { #class = "end" })</td>
gethours<td id="td5">#Html.TextBoxFor(m => m.Model7[nr_rows].c, new { #class = "gethours" })</td>
</tr>
}
#section scripts{
<script>
$(function () {
var start = $(this).find(".start");
start.prop("readonly", true);
var gethours = $(this).find(".gethours");
gethours.attr("readonly", true);
})
</script>
}
result:
your are setting readonly property to true wrongly try instead jquery attr() method
var start = $(this).find(".start");
start.attr("readOnly","true");// set readonly to true

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);
});

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