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

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

Related

Filter function in JavaScript

I'm currently working on an e-commerce site and I'm stuck on the search page, especially when filtering the products.
**
This is the HTML code for the product card:**
<div class="product-seller-item" data-brand="Louis Vuitton" data-category="Helmets">
<div class="product-page-seller-item-header">
<img src="/Images/user.png" alt="User profile image">
<p>citygirl1996</p>
</div>
<img class="product-page-seller-item-body-image" src="/Images/Products/product1.png" alt="">
<div class="product-page-seller-item-footer">
<div class="product-page-seller-item-footer-flex">
<p>£15.00</p>
</div>
<p class="product-page-seller-item-footer-description">Juicy Couture</p>
</div>
</div>
And this is the code for the checkbox:
<label class="container">Helmets
<input type="checkbox" value="Helmets">
<span class="checkmark"></span>
</label>
<label class="container">Louis Vuitton
<input type="checkbox" value="Louis Vuitton">
<span class="checkmark"></span>
</label>
And this is the code for JavaScript:
const checkboxes = document.querySelectorAll('input[type="checkbox"]');
const products = document.querySelectorAll('.product-seller-item');
for (let i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('change', function () {
for (let j = 0; j < products.length; j++) {
let productVisible = false;
for (let k = 0; k < checkboxes.length; k++) {
if (checkboxes[k].checked && products[j].dataset.category === checkboxes[k].value) {
productVisible = true;
break;
} else if (checkboxes[k].checked && products[j].dataset.brand
&& products[j].dataset.brand === checkboxes[k].parentElement.textContent.trim()) {
productVisible = true;
break;
}
}
if (productVisible) {
products[j].style.display = 'block';
} else {
products[j].style.display = 'none';
}
}
});
}
The problem is as follows, when I select the Helmets category, it shows me all of them, everything works perfectly, but when I select the brand, it doesn't hide the product that doesn't match.
If the products have a category you can use filtermethod, that will return you a new array with the elements that have this conditions. For example:
const products = document.querySelectorAll('.products'):
const categories = document.querySelectorAll('input[type=checkbox]');
const filteredProducts
= products.filter(product => product.category == categories.checked);

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.

How to persist selection checkbox state when paging or changing tab on the kendo grid

I want to persist selection of checkbox while paging or moving on other tab in kendo grid .I have referred "How to keep current checkbox state when paging on the grid" here and but i didn't get value of checked and checkbox and also confused with the steps.Please guide in detail.I have attached code below.I have attached script code kendo ui code and html code below.Also thought to use Session to store values of selected checkbox but i don't know is it right way or not.
Please guide me as soon as possible.
<div class="dashboardCharts" id="grid-display">
<div class="count-detail-top right">
<div class="count-detail-bg right">
<ul id="ulOptions">
<li id="Employee" data-type="employee">Employee</li>
<li id="Visitor" data-type="visitor">Visitor</li>
</ul>
</div>
</div>
#(Html.Kendo().Grid<xyz.Models.abcModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(c => c.Employee_id).Title("Alert On").Width(200)
.ClientTemplate("<input type=\"checkbox\" class=\"checkbox\" data-id=\"#= Employee_id#\"/>").Sortable(false);
columns.Bound(c => c.Employee_name).Title("Employee Name");
})
.NoRecords("No Records Found")
.Events(e => e.DataBound("onDataBound"))
.DataSource(dataSource => dataSource
.Transport(transport =>
transport
.Read(read => read.Url(DataUrl))
.ParameterMap("parameterMap")
))
)
</div>
//code in script :
<script>
function onDataBound(e) {
$(".checkbox").bind("click", function (e) {
e.stopPropagation();
$(e.target).closest("tr").toggleClass("k-state-selected");
var tr = $(e.target).closest("tr");
var chk = $(tr).find(".checkbox");
var selected = $(chk).attr("data-id");
var a = selectedIDs.includes(selected);
if (a != true) {
if ($(chk).prop("checked")) {
selectedIDs.push(selected);
}
else {
selectedIDs.pop(selected);
}
}
});
var gridDataView = $("#grid").data().kendoGrid.dataSource.view();
for (var i = 0; i < gridDataView.length; i++) {
var panelApplicationId = gridDataView[i].Checkbox;
if (ShouldBeChecked(panelApplicationId)) {
$('#grid tr td input').eq(i).prop("checked", true);
}
}
}
$(document).on('click', 'input.checkbox', function (e) {
var checked = $(this).prop("checked");
var gridDataView = $("#grid").data().kendoGrid.dataSource.view();
console.log(gridDataView);
var idx = $(this).closest("tr").find("td:nth-child(1)").text();
var gridData = $("#grid").data().kendoGrid.dataSource.data();
for (var i = 0; i < gridData.length; i++) {
if (gridData[i].ID == idx) {
gridData[i].Checkbox = checked;
break;
}
}
});
function ShouldBeChecked(panelApplicationId) {
var shouldBeChecked = false;
var gridData = $("#grid").data().kendoGrid.dataSource.data();
for (var i = 0; i < gridData.length; i++) {
if (gridData[i].Checkbox == panelApplicationId) {
if (gridData[i].Checkbox) {
shouldBeChecked = true;
}
break;
}
}
return shouldBeChecked;
}
</script>
code for selected checkbox and and not selected checkbox.
<input type="checkbox" class="checkbox" data-id="34" checked="checked">
<input type="checkbox" class="checkbox" data-id="30">
As mentioned by OP in question-comment as of the 2017 R2 release, there is a grid-option persistselection
Kendo-versions before that, can add their own code, storing the selection in the change-event, and restoring it in the databoundevent as shown by Kendo in persist-row-selection:
change: function (e, args) {
var grid = e.sender;
var items = grid.items();
items.each(function (idx, row) {
var idValue = grid.dataItem(row).get(idField);
if (row.className.indexOf("k-state-selected") >= 0) {
selectedOrders[idValue] = true;
} else if (selectedOrders[idValue]) {
delete selectedOrders[idValue];
}
});
},
dataBound: function (e) {
var grid = e.sender;
var items = grid.items();
var itemsToSelect = [];
items.each(function (idx, row) {
var dataItem = grid.dataItem(row);
if (selectedOrders[dataItem[idField]]) {
itemsToSelect.push(row);
}
});
e.sender.select(itemsToSelect);
}
(See also this SO-question.)

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