I am trying to validate specific divs I have looked all over google and I can't find any examples for the way I am doing my validation. I have 2 divs I want to be able to click a button and validate the first div and then I want that div to hide and validate the second div. I have wrote some jquery code that hides the first div but I only want to do this to happen once that specific div is validated.
MARKUP
<div id="contentone">
<table>
<tr>
<td>game console</td>
<td><%=Html.TextBox("console", ViewData["console"] ?? "") %></td>
</tr>
<tr>
<td>manafacturer</td>
<td><%=Html.TextBox("manaf", ViewData["manaf"] ?? "") %></td>
</tr>
</table>
</div>
<div id="contenttwo">
<table>
<tr>
<td>description</td>
<td><%=Html.TextBox("desc", ViewData["desc"] ?? "") %></td>
</tr>
<tr>
<td>Available games</td>
<td><%=Html.TextBox("games", ViewData["games"] ?? "") %></td>
</tr>
</table>
</div>
<button id="hide" type="button">Test1</button>
<script>
$(document).ready(function(){
$("#hide").click(function(){
$("#contentone").hide();
});
});
</script>
CONTROLLER
[AcceptVerbs("POST")]
public ActionResult ConsoleQues(string console, string manaf, string desc, string games)
{
ViewData["console"] = console;
ViewData["manaf"] = manaf;
ViewData["desc"] = desc;
ViewData["games"] = games;
if (string.IsNullOrEmpty(console))
ModelState.AddModelError("console", "Please enter console name ");
if (string.IsNullOrEmpty(manaf))
ModelState.AddModelError("manaf", "please enter manafactuer name");
if (string.IsNullOrEmpty(desc))
ModelState.AddModelError("desc", "Please enter description name ");
if (string.IsNullOrEmpty(games))
ModelState.AddModelError("games", "please enter game name");
Create function for validating both divs:
function IsValid(divid) {
var $div = $('#' + divid);
var result = true;
$.each($div.find("input[type='text']"), function (i, input) {
if ($(input).val().length == 0 || $.trim($(input).val()) == '') {
result = false;
return;
}
});
return result;
}
Check validity and hide contentone div
if (IsValid('contentone')) {
$('#contentone').hide();
}
Related
Basically I want my code to update the textarea as users put a check in a checkboxes inside a table. If a checkbox is checked, a username will be placed in textarea along with line breaks. If unchecked, it will remove from textarea. After that, a button will submit every string inside the textarea.
#using (Html.BeginForm())
{
#Html.AntiForgeryToken();
<td align="center">
<form>
<div style="max-width:50%" class="form-group #if (ViewBag.ErrorMessageDelete != null)
{ <text>has-error</text> } ">
#Html.TextArea("deleteRequest", string.Empty, 5, 100, null)
#if (ViewBag.ErrorMessageDelete != null)
{
<span class="help-block">#ViewBag.ErrorMessageDelete</span>
}
</div>
<button class="btn btn-primary" onclick="return confirm ('Removing these members, are you sure?')">Remove User(s)</button>
</form>
</td>
}
and this is my current checkbox
<td align="center" style="width:5%">
#Html.CheckBox("toBeDeleted", new { onclick = "deleteRequest = deleteRequest + item.username + <br>" });
</td>
I used textarea because I want users to be able to input usernames on their own without using checkboxes. Is it possible to do it in MVC ASP.NET in Visual Studio?
Don't do this with click event. Use change event on checkbox.
You can also try with the array. If the checkbox is checked add item to array, if not remove it. After that convert array to string, and set a value to textarea. Delete and push logic you have to implement by your own.
<td align="center" style="width:5%">
#Html.CheckBox("toBeDeleted", new { onchange="testfunc(this)", data_username = item.username });
</td>
<script>
var result = [];
function testfunc(elem) {
var username = $(elem).attr("data-username");
if($(elem).is(':checked')) {
result.push(username )
}
else{
var index = result.indexOf(username);
if (index > -1) {
result.splice(index, 1);
}
}
$("#deleteRequest").val(result.join("\n"));
}
</script>
I am working on an ecommerce site where I am stuck on the cart management. Basically before login, products are kept in a session and I am trying to update the product quantity stored in the session using Ajax. I mean whenever I write in the 'Quantity To Change', the changed value should be reflected in the 'Quantity' column.
Note: I've shortened the post and figured out why it wasn't firing while debugging. Actually I was unable to get the id of the associated product. Now it passes the id. That's it. Now I've another issue - The TextBox are being created dynamically with a for loop. I used developer tools to figure out how the TextBoxes are generated dynamically and it is something like this:
For Product 1: cartDetails_0__Quantity
For Product 2: cartDetails_1__Quantity
I am wondering how to grab the quantity or values from the dynamically generated TextBoxes. If I put the generated id from HTML directly to Ajax, then it updates the quantity. Otherwise it doesn't. I've tried to use a loop in Ajax but I think, I am getting it wrong. Please see the View.
The view:
<table border="1" width="100%" cellpadding="4">
<thead>
<tr>
<th style="text-align:center;">Name</th>
<th style="text-align:center;">Price</th>
<th style="text-align:center;">Quantity</th>
<th style="text-align:center;">Quantity To Change</th>
</tr>
</thead>
<tbody>
#if (ViewBag.CartDetails != null)
{
for (int i = 0; i < cartDetails.Count(); i++)
{
<tr>
<td style="text-align: center; display:none;">#Html.DisplayFor(model => cartDetails[i].ProductId)</td>
<td id="ID" style="text-align: center;">#Html.DisplayFor(model => cartDetails[i].ProductName)</td>
<td style="text-align: center;">#Html.DisplayFor(model => cartDetails[i].Price)</td>
<td style="text-align: center;">#Html.DisplayFor(model => cartDetails[i].Quantity, new { #class = "quantityUpdate" })</td>
<td style="text-align: center;">#Html.TextBoxFor(model => cartDetails[i].Quantity, new { #class = "quantity", data_id = cartDetails[i].ProductId } )</td>
</tr>
}
}
</tbody>
</table>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
var url = '#Url.Action("UpdateCart")';
$(".quantityUpdate").change(function () {
var id = $(this).data('id');
var i = 0;
$('.quantityUpdate').each(function (i, item) {
$.post(url, { id: id, Quantity: $("#cartDetails_"+i+"__Quantity").val() }, function (response) {
if (response) {
$("#TotalPrice").load(window.location + " #TotalPrice");
}
});
})
alert(id);
alert($("#cartDetails_"+i+"__Quantity").val());
});
Here is an image sample that I am trying:
$('.quantity').change(function(){
$('.quantityUpdate').val($('.quantity').val());
// put code here
});
Instant Change
$('.quantity').keyup(function(){
$('.quantityUpdate').val($('.quantity').val());
// put code here
});
If the idea is to call ajax when you change the value in .quality textbox then this is how you should do:
$('.quantity').change(function(){
//your ajax call
});
I am working on asp.net MVC 4 application. I have created a list using foreach loop and declared a variable to show record number. Each row has a delete icon, which when clicked, deletes that record and hides that row. this works fine except one issue. When user deletes first record or any record in middle of list, I want the record number of all the rows to be updated accordinlgy.
Here is razor view code:
#{
int i = 1;
foreach (var item in cartItem.CartItemsByStore)
{
<tr id="cartrow-#item.CartItemID">
<td class="transaction">#i</td>
<td class="item-details">
<img src="/images/tmp/order-product.jpg" width="63" height="63">
<div class="desc">
<span>
<p>#item.ItemName</p>
</span>
</div>
</td>
<td class="date-time">15 Jun 2014</td>
<td class="action">
X
</td>
</tr>
<tr class="sp" id="sp-#item.CartItemID">
<td colspan="20"></td>
</tr>
i++;
}
}
and here is deletion code:
$(function () {
// Document.ready -> link up remove event handler
$(".removeCartItem").click(function () {
if (confirm("Click OK if you want to delete this record; otherwise, click 'Cancel'")) {
// Get the id from the link
var recordToDelete = $(this).attr("data-id");
if (recordToDelete != '') {
// Perform the ajax post
$.post("/Cart/DeleteCartItem", { "id": recordToDelete },
function (data) {
// Successful requests get here
$('#cartrow-' + recordToDelete).fadeOut('hide');
$('#sp-' + recordToDelete).fadeOut('hide');
$('#spCartCount').text(data);
$('#row-' + recordToDelete).fadeOut('hide');
});
}
}
});
});
Try this
Partial view : "Store.csthml"
#model IEnumerable<CartItemsByStore>
#{
int i = 1;
foreach (var item in Model)
{
<tr id="cartrow-#item.CartItemID">
<td class="transaction">#i</td>
<td class="item-details">
<img src="/images/tmp/order-product.jpg" width="63" height="63">
<div class="desc">
<span>
<p>#item.ItemName</p>
</span>
</div>
</td>
<td class="date-time">15 Jun 2014</td>
<td class="action">
X
</td>
</tr>
<tr class="sp" id="sp-#item.CartItemID">
<td colspan="20"></td>
</tr>
i++;
}
}
CartController:
public ActionResult ReturnView()
{
//populate model
IEnumerable<CartItemsByStore>model =db.GetItemsByStore();
return PartialView("Store",model)
}
public ActionResult DeleteCartItem(int id)
{
//delete
return RedirectToAction("ReturnView");
}
Main View:
<div id="divStore">
#Html.Partial("Store",cartItem.CartItemsByStore)
</div>
$(".removeCartItem").click(function () {
if (confirm("Click OK if you want to delete this record; otherwise, click 'Cancel'")) {
// Get the id from the link
var recordToDelete = $(this).attr("data-id");
if (recordToDelete != '') {
// Perform the ajax post
$.post("/Cart/DeleteCartItem", { "id": recordToDelete },
function (data) {
// Successful requests get here
$("#divStore").html(data);
});
}
}
});
I have some fields in a repeater and I need to validate them.
Here is the scenario:
When the page loads I get a set of fields just once(first name, last name etc.) and I get a link "Add another user", if you click the link it adds the same fields again on the bottom.
Now for the code part:
In my case I needed to run the repeater 4 times (so the fields are on the page 4 times from the begining). Then I hide them as I hide the <div> that contains them. When the button is clicked I show the first hidden div and so on.
Some code(not all):
<asp:Repeater ID="rptOtherPeople" runat="server">
<HeaderTemplate>
<table>
<thead>
<tr>
<td>
<h3>Други лица</h3>
</td>
</tr>
</thead>
<tbody class="GridBody">
</HeaderTemplate>
<ItemTemplate>
<tr class="GridRow" id="personRow" style="display: none">
<td>
<asp:TextBox ID="txtFirstName" CssClass="mid-inp" Text="" runat="server"></asp:TextBox>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</tbody>
</table>
</FooterTemplate>
</asp:Repeater>
And here is that javascript that shows the next row:
$(document).ready(function () {
var peopleNum = 1;
if ($(".GridBody tr").length > 0) {
var tr = $(".GridBody tr")[0];
tr.style.display = 'table-row';
tr.setAttribute('hidden', 'false');
var anc = tr.getElementsByTagName('a');
}
if ($(".GridBody tr").length > 0 && peopleNum > 0) {
for (i = 0; i < peopleNum; i++) {
var tr = $(".GridBody tr")[i];
tr.style.display = 'table-row';
tr.setAttribute('hidden', 'false');
if (i > 0) {
var anc = tr.getElementsByTagName('a');
if (anc[i] != undefined)
anc[i].style.display = 'none';
}
}
}
})
function addPerson() {
var body = $(".GridBody");
var indexOfNextRow = $('tr[class="GridRow"][hidden="false"]').length;
var tr = $(".GridBody tr")[indexOfNextRow];
tr.style.display = 'table-row';
tr.setAttribute('hidden', 'false');
}
The Problem: For example I want the field to be required. I put a RequiredFieldValidator and I disable it in some cases and enable it in others. The thing is that I get 4 RequiredFieldValidators on the page and I can only turn ALL of them on or off at once. I want to activate just one of them. I couldn't find a way to do that because they are pretty much identical. Any ideas?
I assume that I can not sort this out in the code behind. Can I work with just one RequiredFieldValidator via javascript(how do I identify the one I want).
Some people prefer jquery validation. Is it applicable in this case and how(I have never used jquery validation before)?
EDIT 1
Ok the controls are not identical. In the browser the generated ID is: ctl00_SPWebPartManager1_g_f6926ea5_98ba_46c1_b157_4f1ddc46885d_ctl00_Step21_otherPeople_rptOtherPeople_ctl01_rv1 , but I can not access the validator from here in my Javascript
You can disable the validators either server side or client side.If i understood your question , the thing you looking for is disabling a specific vaidator say required field validator.For that here is a simple javascript code to disable the validators.
function DisableRFValidators() {
var ValidatorToDisable = document.getElementById("RequiredFieldValidator2");
ValidatorEnable(ValidatorToDisable, false);
}
Fixed it! Here is the code:
$("#aspnetForm").validate();
$(".required").each(function (index) {
if ($(this).attr("id").indexOf("txtFirstName") >= 0) {
$(this).rules("add", {
required: true,
minlength: 3,
messages: {
required: "<div class='val' style='color:red'>Name is Required!</div>",
minlength: "<div class='val' style='color:red'>Minimum number of symbols = 3!</div>"
}
});
}
else if ($(this).attr("id").indexOf("txtFirstName") >= 0){
$(this).rules("add", {
required: false
});
}
});
function validateData() {
var result = $("#aspnetForm").valid();
return result;
}
function btnNextClick(btn_this) {
var btnNext = document.getElementById("<%=btnMoveNextHidden.ClientID%>");
if (btnNext != null && validateData() == true) {
btnNext.click();
}
}
<%foreach (var indication in Model.FindAll(m => m.Model != null && m.Model.Trx != null).OrderBy(m => m.Model.Trx.PrimarySponsor.Company))
{ %>
<tr>
<td><%= indication.DisplayUser %></td>
<td><%= indication.ActiveIndicationUsers[0].FullName %></td>
<td><%= string.IsNullOrEmpty(indication.Model.Trx.PrimarySponsor.Company) ? "Not Yet Saved" : indication.Model.Trx.PrimarySponsor.Company %></td>
<td><%= indication.TimeOpened.ToString(Chatham.Web.Data.Constants.Format.DateTimeSecondsFormatString) %></td>
<td><%= indication.Model.Trx.ProductCollection[0].ProductTypeFriendlyName %></td>
<td><%= (!indication.Model.Trx.ID.HasValue) ? "Not Yet Saved" : indication.Model.Trx.ID.Value.ToString() %></td>
<td><input type="button" value="Open" name="<%= (!indication.Model.Trx.ID.HasValue) ? "Not Yet Saved" : indication.Model.Trx.ID.Value.ToString() %>" /></td>
</tr>
<%} %>
So that above table, as you can see, is dynamically generated. How do I handle the button click? I also want to pass the name attribute of the button into whatever method handles the button click.
Thanks!
You can use the live function of jQuery.
Try this:
$(function(){
$("td input[type=button][value=Open]").live("click", function(e){
var btn = $(this);
alert(btn.attr("name"));
});
})
The same way you would handle a regular button click. Dynamically create the code to handle regular button clicks in the http code you're generating.
That code is tragic and screaming for refactoring. Just looking at it my eyes hurt. You are not encoding strings thus making this code vulnerable to XSS attacks.
So as always in ASP.NET MVC you start with a view model:
public class MyViewModel
{
public string DisplayUser { get; set; }
public string ActiveIndicationsUserFullname { get; set; }
public string Company { get; set; }
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}")]
public DateTime TimeOpened { get; set; }
public string TrxId { get; set; }
}
then you will have a controller action which will fetch the model from the repository and map it to the view model. You could use AutoMapper to simplify this mapping. It's in the mapping layer that you will transform everything to be ready to be directly used by the view so that this views doesn't resemble to a horrible tag soup:
public ActionResult Foo()
{
// it's here that you should do the LINQ queries, etc ...
// not in the view. Views are not supposed to fetch any data
// and to be intelligent. Views should be dumb and only render
// the preformatted data that they have been fed by the controller action
IEnumerable<SomeModel> model = ...
IEnumerable<MyViewModel> viewModel = Mapper.Map<IEnumerable<SomeModel>, IEnumerable<MyViewModel>>(model);
return View(viewModel);
}
next we get to the strongly typed view where we will be using Display Templates:
<table id="myTable">
<thead>
<tr>
<th>DisplayUser</th>
<th>ActiveIndicationsUserFullname</th>
<th>Company</th>
<th>TimeOpened</th>
<th>TrxId</th>
</tr>
</thead>
<tbody>
<%= Html.DisplayForModel()
</tbody>
</table>
and in the corresponding display template (~/Views/Shared/DisplayTemplates/MyViewModel.ascx):
<%# Control
Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<AppName.Models.MyViewModel>" %>
<tr>
<td><%= Html.DisplayFor(x => x.DisplayUser) %></td>
<td><%= Html.DisplayFor(x => x.ActiveIndicationsUserFullname) %></td>
<td><%= Html.DisplayFor(x => x.Company) %></td>
<td><%= Html.DisplayFor(x => x.TimeOpened) %></td>
<td><%= Html.DisplayFor(x => x.TrxId) %></td>
<td>
<input type="button" value="Open" name="<%= Model.TrxId %>" />
</td>
</tr>
and finally you could use jquery to attach to the click of this button and fetch the name:
$(function() {
$('#myTable button').click(function() {
var btn = $(this);
alert(btn.attr('name'));
});
});