I am trying to make sure that at least one 'input checkbox is checked in this list there is about 10 items but I am not sure how to do this? Do I need a flag in the model?
<div>* Data</div>
#Html.ValidationMessageFor(x => x.flgData,"", new { #class = "text-danger" })
<ul>
#foreach (var item in Model.ListOfData)
{
<li>
<input type="checkbox" value="#item.Value" name="chk" />
<label asp-for="#item.Selected">#Html.Raw(#item.Name)</label>
<input type="hidden" asp-for="#item.DictionaryId" />
<input type="hidden" asp-for="#item.Name" />
</li>
}
</ul>
You could loop though all the checkbox and check if it is checked
HTML
<input type="button" id="btnSubmitCB" value="Submit" class="btn btn-primary" />
<input type="checkbox" class="chkbox" value="Bike" /> Bike
<input type="checkbox" class="chkbox" value="Car" /> Car
<input type="checkbox" class="chkbox" value="Boat" /> Boat
JQuery
$(document).ready(function () {
$('#btnSubmitCB').click(function () {
var cbChecked = false;
$('input[type=checkbox]').each(function () {
if (this.checked) {
cbChecked = true;
return false;
}
});
if (cbChecked) {
alert("At least one checkbox is checked");
}
else {
alert("No checkbox is checked");
}
});
});
Another way without using .each function
$(document).ready(function () {
$('#btnSubmitCB').bind("click", function () {
let checkedCount = $('input[type=checkbox]:checked').length;
if (checkedCount == 0) {
alert("no checkbox has been checked")
}
else {
alert("checkbox has been checked");
}
});
});
Related
I have an edit button in each row of my Datatable. I have two actions for editing. One for Getting data in a Datatable and the other one for posting my information. The code behind my Edit button in the my Home Index is:
{
"data": "Id",
"render": function (data, type, full, meta) {
return `<div class="text-center"> <a class="btn btn-info"
href="/Home/EditGet/` + data + `" >Edit</a> </div> `;
}
and my home controller methods are:
/// Get Edit
[HttpGet]
[Route("{Id}")]
public IActionResult EditGet(int? id)
{
if (id == null || id == 0)
{
return NotFound();
}
var obj = _sv.OpenRecord(id);
if (obj == null)
{
return NotFound();
}
return View("EditGet", obj);
}
/// Post Edit
[HttpPost]
public IActionResult EditPost(SalesVeiwModel sales)
{
if (ModelState.IsValid)
{
var res= _sv.Update(sales.Comment);
if (res==null )
{
return Json(data: "Not found");
}
return RedirectToAction("EditGet");
}
return Json(data: "Is not valid");
}
And finally my EditGet view is like bellow:
<form id="contact-form" method="post" asp-controller="Home" asp-
action="EditPost" role="form" >
<input asp-for="Id" hidden />
<div class="form-group">
<label>Invoice Nomber</label>
<input id="form_IBNo" type="text" class="form-control" disabled asp-for="IBNo">
</div>
.
.
.
<div class="col-md-12">
<input type="submit" class="btn btn-success btn-send" value="Confirm" asp-
controller="Home" asp-action="EditGet">
</form>
You should have two buttons,one call EditGet,one call EditPost,here is a demo:
<form id="contact-form" method="post" asp-controller="Home" asp-
action="EditPost" role="form" >
<input asp-for="Id" hidden />
<div class="form-group">
<label>Invoice Nomber</label>
<input id="form_IBNo" type="text" class="form-control" disabled asp-for="IBNo">
</div>
.
.
.
<div class="col-md-12">
<input type="submit" class="btn btn-success btn-send" value="Confirm">
<a class="btn btn-success btn-send" value="Confirm" asp-controller="Home" asp-action="EditGet" asp-route-id="1">EditGet</a>
</div>
</form>
This is my view code.
#using (Html.BeginForm())
{
#Html.LabelFor(m=>m.GroupID)
#Html.DropDownListFor(m => m.GroupID, Model.GroupList, "Please select", new { id = "ddlgrp" })
if (ViewBag.selectedperms!=null)
{
foreach(var permission in Model.Permissions)
{
<label>
#Html.RadioButtonFor(m=>m.perm_id,permission.perm_id)
<span>#permission.perm_levelname</span>
</label>
}
}
else
{
foreach(var permission in Model.Permissions)
{
<label>
#if (Model.perm_id.Equals(ViewBag.selectedperms))
{
#Html.RadioButtonFor(m=>m.perm_id,permission.perm_id,true)
<span>#permission.perm_levelname</span>
}
else
{
#Html.RadioButtonFor(m=>m.perm_id,permission.perm_id)
<span>#permission.perm_levelname</span>
}
</label>
}
}
<p><input type="submit" value="Submit" /></p>
This is my jquery code.
$(document).ready(function () {
$("#ddlgrp").change(function () {
$("#log").ajaxError(function (event, jqxhr, settings, exception) {
alert(exception);
});
var grpselected = $("select option:selected").val();
alert(grpselected);
$.get('#Url.Action("CheckPermissions")',
{ id: grpselected }, function (data) {
});
});
});
This is actionmethod
public ActionResult CheckPermissions(int id)
{
tblperm od = new tblperm();
var selectedperms = (from c in db.tblperm where c.grp_id==id select c.perm_id).SingleOrDefault();
ViewBag.selectedperms = selectedperms;
return View(od);
}
Assume for groupip id 1 there is a permisson with permid 1. So when i select 1 from dropdwon corresponding dropdown with id 1 should be checked. I have tried with above code but its not working. Can anybody suggest me where i am going wrong?
I think you need something like following snippet.
$("#GroupID").change(function () {
$('input[name="perm_id"][value="' + this.value + '"]').prop('checked', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="GroupID">
<option value="">Select group</option>
<option value="1">Group 1</option>
<option value="2">Group 2</option>
<option value="3">Group 3</option>
<option value="4">Group 4</option>
</select>
<input type="radio" value="1" name="perm_id" /><label>Permission 1</label>
<input type="radio" value="2" name="perm_id" /><label>Permission 2</label>
<input type="radio" value="3" name="perm_id" /><label>Permission 3</label>
<input type="radio" value="4" name="perm_id" /><label>Permission 4</label>
Update
Action method
public ActionResult CheckPermissions(int id)
{
tblperm od = new tblperm();
var selectedperms = (from c in db.tblperm where c.grp_id == id select c.perm_id).SingleOrDefault();
return Json(selectedperms, JsonRequestBehavior.AllowGet);
}
jQuery
$("#ddlgrp").change(function () {
var grpselected = $(this).val();
$.getJSON('#Url.Action("CheckPermissions")', { id: grpselected }, function (data) {
$('input[name="perm_id"][value="' + data + '"]').prop('checked', true);
});
});
When I use a move item from a selection list to another list using jQuery it moves well but when I reload the page it goes back to the previous list. I want to know how can I save it so when I reload the page it doesn't go back?
<script>
$(document).ready(function () {
$('#btnRight').click(function (e) {
var selectedOpts = $('#lstBox1 option:selected');
if (selectedOpts.length == 0) {
alert("Nothing to move.");
e.preventDefault();
}
$('#lstBox2').append($(selectedOpts).clone());
$(selectedOpts).remove();
e.preventDefault();
});
$('#btnLeft').click(function (e) {
var selectedOpts = $('#lstBox2 option:selected');
if (selectedOpts.length == 0) {
alert("Nothing to move.");
e.preventDefault();
}
$('#lstBox1').append($(selectedOpts).clone());
$(selectedOpts).remove();
e.preventDefault();
});
$('#btnRight2').click(function (e) {
var selectedOpts = $('#lstBox2 option:selected');
if (selectedOpts.length == 0) {
alert("Nothing to move.");
e.preventDefault();
}
$('#lstBox3').append($(selectedOpts).clone());
$(selectedOpts).remove();
e.preventDefault();
});
$('#btnLeft2').click(function (e) {
var selectedOpts = $('#lstBox3 option:selected');
if (selectedOpts.length == 0) {
alert("Nothing to move.");
e.preventDefault();
}
$('#lstBox2').append($(selectedOpts).clone());
$(selectedOpts).remove();
e.preventDefault();
});
});
</script>
#foreach (var item in Model)
{
<hr />
<table>
<tr>
<td style='width:160px;'>
<b>TO DO:</b><br />
<select multiple="multiple" id='lstBox1'>
<option>#Html.DisplayFor(model => item.Events.Vanue)</option>
</select>
</td>
<td style='width:50px;text-align:center;vertical-align:middle;'>
<input type="button" id="btnRight" value="-" />
<br /><input type="button" id="btnLeft" value="<" />
</td>
<td style='width:200px;'>
<b>IN PROGRESS: </b><br />
<select multiple="multiple" id='lstBox2'>
</select>
</td>
<td style='width:50px;text-align:center;vertical-align:middle;'>
<input type="button" id="btnRight2" value="-" />
<br /><input type="button" id="btnLeft2" value="<" />
</td>
<td style='width:160px;'>
<b>DONE: </b><br />
<select multiple="multiple" id='lstBox3'>
</select>
</td>
</tr>
</table>
You need to find a way to save the website's state. There are a lot of options. You can start with this article on localStorage. I found it be a good primer.
What I want to achieve is once the data got saved into database, when it goes back to client, it will automatically update the observable array. But somehow I couldn't make it happen.
This is my Server side code:
[HttpGet]
public JsonResult GetTasks()
{
var tasks = context.ToDoTasks.ToList();
return Json(tasks.Select(c => new TaskViewModel(c)).ToList(), JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult AddTask(string text, string date)
{
var nTask = new ToDoTask()
{
Text = text,
Date = DateTime.ParseExact(date, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture),
IsDone = false,
Order = 1,
};
context.ToDoTasks.Add(nTask);
context.SaveChanges();
return Json(new TaskViewModel(nTask), JsonRequestBehavior.AllowGet);
}
This is my cshtml file code:
<form>
<div class="controls controls-row" style="margin-top:40px;">
<input class="span7" type="text" placeholder="Task to do" style="margin-right:4px;" id="oText">
<div id="task-date" class="input-append date">
<input data-format="MM/dd/yyyy" type="text" placeholder="MM/dd/yyyy" name="taskDate" id="oDate" />
<span class="add-on">
<i data-time-icon="icon-time" data-date-icon="icon-calendar">
</i>
</span>
</div>
<button class="btn" type="submit" style="margin-top:-10px;" data-bind="click: save">+</button>
</div>
<div class="controls">
<label class="checkbox">
<input type="checkbox"> Mark all as complete
</label>
</div>
<div id="task-section" style="margin-top:20px;">
<ul data-bind="foreach: Tasks">
<!-- ko if: IsDone -->
<li>
<span><input type="checkbox" style="margin:-5px 5px 0px 0px;" data-bind="checked: IsDone" /></span>
<del><span data-bind="text: Text"></span></del>
<del><span class="task-date" data-bind="text: Date"></span></del>
</li>
<!-- /ko -->
<!-- ko ifnot: IsDone -->
<li>
<span><input type="checkbox" style="margin:-5px 5px 0px 0px;" data-bind="checked: IsDone" /></span>
<span data-bind="text: Text"></span>
<span class="task-date" data-bind="text: Date"></span>
</li>
<!-- /ko -->
</ul>
</div>
<div class="clearfix" style="margin-top:30px;">
<span class="pull-left" style="font-weight:bold;"><span data-bind="text: oItemLeft"></span> item left</span>
<span class="pull-right badge" style="cursor:pointer;" data-bind="click: remove">Clear # completed item</span>
</div>
</form>
And finally my JS:
var ViewModel = function (data) {
var self = this;
self.Tasks = ko.mapping.fromJS(data, {}, self.Tasks);
self.oItemLeft = ko.computed(function () {
var i = 0;
data.forEach(function (entry) {
if (!entry.IsDone) i++;
});
return i;
});
self.save = function () {
$.ajax({
url: "Home/AddTask",
type: "POST",
data: { text: $('#oText').val(), date: $('#oDate').val() },
success: function (response) {
ko.mapping.fromJS(response, ViewModel);
}
});
};
self.remove = function () {
alert('delete');
}
}
$(function () {
$.getJSON("/Home/GetTasks/", null, function (data) {
ko.applyBindings(new ViewModel(data));
});
// for datepicker
$('#task-date').datetimepicker({
language: 'pt-BR',
pickTime: false
});
});
self.save = function () {
$.ajax({
url: "Home/AddTask",
type: "POST",
data: { text: $('#oText').val(), date: $('#oDate').val() },
success: function (response) {
var task = ko.mapping.fromJS(response);
self.Tasks.push(task);
}
});
};
Also for oItemLeft you should be referring to self.Tasks instead of data:
self.oItemLeft = ko.computed(function () {
var i = 0;
self.Tasks().forEach(function (entry) {
if (!entry.IsDone) i++;
});
return i;
});
I have this code
#if (ViewBag.TechnologyNames != null)
{
foreach (var technologyName in ViewBag.TechnologyNames)
{
if (#technologyName.TechnologyID == -1)
{
<div class="CheckBoxItem">
<input type="checkbox" name="option1" id="allTechnology" value="#technologyName.TechnologyID" checked="checked" />
#technologyName.Name
</div>
}
else
{
<input type="checkbox" name="option2" id="tech" value="#technologyName.TechnologyID" />
#technologyName.Name
}
}
}
What I need is somehow to add #technologyName.TechnologyID to id="tech" to have at the end
id="tech_123"
How I can do it?
Thank you!
try this (basically adding parenthesis around the property):
<input type="checkbox" name="option2" id="tech_
#(technologyName.TechnologyID)" value="#technologyName.TechnologyID" />