Asp.net core delete button not working properly - javascript

I have a view like this:
<div class="GridContainer">
<div>
<div class="row gridHeader">
<div class="small-9 columns">Member Name</div>
<div class="small-2 columns">Date Registered</div>
</div>
#foreach (var member in Model.Members)
{
<div class="row">
<div class="small-9 columns">#member.MemberName</a></div>
<div class="small-2 columns">#member.DateRegistered</div>
<input type="hidden" asp-for="#member.Id" />
<a id="btnMemberDelete" href="#">Delete</a>
</div>
}
</div>
my javascript:
<script type="text/javascript">
$(document).ready(function () {
$('#btnMemberDelete').click(function () {
var id = $(this).closest("div").find("input:hidden[name='member.Id']").val();
var url = '#Url.Action("DeleteMembers", "Member")' + "?id=" + id;
openMemberDialog(url);
});
});
</script>
The delete button only works for the very first row at the moment. If say I have 4 rows the other 3's delete button won't even register. It won't even open the dialog box. Is there something I'm missing here as the code seems to be correct to me.
Thanks!

Fiddle here
As answerd above you need to have a uniqe ID or use a class. in my solution above I use a class like so:
$(document).ready(function () {
$('.btnMemberDelete').click(function (e) {
e.preventDefault();
var id = $(this).closest("div").find("input:hidden[name='member.Id']").val();
console.log(id)
});
});
Also correct your html:
#foreach (var member in Model.Members)
{
<div class="row">
<div class="small-9 columns">#member.MemberName</a></div> // remove the '</a>' here
<div class="small-2 columns">#member.DateRegistered</div>
<input type="hidden" asp-for="#member.Id" />
<a class="btnMemberDelete" href="#">Delete</a>
</div>
}

You need to give a unique id for each delete button. Or you can give a classname instead of id to your anchor tag.
<div class="GridContainer">
<div>
<div class="row gridHeader">
<div class="small-9 columns">Member Name</div>
<div class="small-2 columns">Date Registered</div>
</div>
#foreach (var member in Model.Members)
{
<div class="row">
<div class="small-9 columns">#member.MemberName</a></div>
<div class="small-2 columns">#member.DateRegistered</div>
<input type="hidden" asp-for="#member.Id" />
<a class="btnMemberDelete" href="#">Delete</a>
</div>
}
</div>
<script type="text/javascript">
$(document).ready(function () {
$('.btnMemberDelete').click(function () {
var id = $(this).closest("div").find("input:hidden[name='member.Id']").val();
var url = '#Url.Action("DeleteMembers", "Member")' + "?id=" + id;
openMemberDialog(url);
});
});
</script>

Related

Using localStorage to pass data between different pages

I have a shopping basket where i want a user to be able to click on a button that takes them to a separate page whilst capturing their shopping basket contents (item names, quantities, prices, etc). At the moment i'm using localStorage to send just the item names to my new page however the only item that ever prints is the last item to be placed in a basket (i'm not sure how to stop localStorage overwriting data like it does).
This is the itemName section on the basket page.
<!--START: itemnamelink--><a id="itemName" href="product.asp?itemid=[ITEM_CATALOGID]">[ITEM_NAME]</a><!--END: itemnamelink-->
This is a script i have on my basket page.
jQuery( document ).ready(function($) {
var itemName = document.getElementById('itemName');
var arrayShop = [{name: itemName.textContent}];
if(localStorage.getItem("user") == null) {
localStorage.setItem("user",JSON.stringify([arrayShop]))
}
else{
var newArray = JSON.parse(localStorage.getItem("user"));
newArray.push(arrayShop);
localStorage.setItem("user", JSON.stringify(newArray))
}
});
This is the script on a new page
jQuery( document ).ready(function($) {
var hst = document.getElementById("add");
console.log(localStorage.getItem("user"));
var items = JSON.parse(localStorage.getItem("user"));
for (var i = 0; i < items.length; i++) {
hst.innerHTML += "<tr><td>" + items[i].name + "</td><td>"+ items[i].price +
"</td></tr>";
}
});
<!--HTML ON THE PAGE -->
<table id="add">
<tr><td>Name</td><td>Price</td></tr>
</table>
I'm getting the following output which is the last item in the basket (there's 4 items in the basket).
Name
110mm Chair
I should be getting.
Name
110mm Chair
Red Chair
Green Chair
Grey Chair
Below is my shopping cart
<div class="shoppingCartItems">
<div class="titles2">
<div class="item-info">[shoppingcart_items]</div>
<div class="item-qty">[shoppingcart_quantity]</div>
<div class="item-price">[shoppingcart_price]</div>
<div class="item-total">[shoppingcart_total]</div>
<div class="item-remove"> </div>
<div class="clear"></div>
</div>
<!--START: SHOPPING_CART_ITEM-->
<div class="row">
<div class="item-info">
<div class="product-image"><!--START: itemthumbnail--><img src="thumbnail.asp?file=[THUMBNAIL]" height="55" width="55" /><!--END: itemthumbnail--><!--START: thumbnailnolink--><img src="thumbnail.asp?file=[THUMBNAIL]" height="55" width="55" id="tnl" /><!--END: thumbnailnolink--></div>
<div class="product-name-options">
<!--START: itemnamelink--><a id="itemName" class ="itemName" href="product.asp?itemid=[ITEM_CATALOGID]">[ITEM_NAME]</a><!--END: itemnamelink-->
<!--START: itemnamenolink--><span id="spnItemName">[ITEM_NAME]</span><!--END: itemnamenolink-->
<!--START: itemoptions-->
<br />
View/Hide options<br />
<div id=opt[ITEM_ID] name=opt[ITEM_ID] style="display:none;">[OPTIONS]</div>
<!--END: itemoptions-->
<!--START: recurring_frequency-->
<div class="recurring_frequency">This item will Autoship every <strong>[recurring_frequency]</strong></div>
<!--END: recurring_frequency-->
<!--START: giftwraplink-->
<div class="giftwraplink"> <a onclick="showGiftWrap('[ITEM_ID]')">[giftwrap_link]</a> </div>
<!--END: giftwraplink--></div>
<div class="clear"></div>
</div>
<div class="item-qty">
<input type="text" name="qtyitemnum" value="[ITEM_QUANTITY]" size="3" maxlength="5" class="txtBoxStyle" />
<input type="hidden" name="coliditemnum" value="[ITEM_ID]" size="3" maxlength="5" />
[shoppingcart_updatecart]
</div>
<div class="item-price" id="itemPrice">[ITEM_PRICE] </div>
<div class="item-total">[ITEM_SUBTOTAL]</div>
<div class="item-remove"><i class="icon-cancel"></i></div>
<div class="clear"></div>
</div>
<!--END: SHOPPING_CART_ITEM-->
<div class="shoppingCartTotal">
<div class="clear"> </div>
<div class="item-total">[CARTSUBTOTAL]</div>
<div class="item-price">[shoppingcart_subtotal]</div>
<div class="clear"></div>
<!--START: DISCOUNTS-->
<div class="clear"> </div>
<div class="item-total">[DISCOUNTS]</div>
<div class="item-price">[checkout1_discounts]</div>
<div class="clear"></div>
<!--END: DISCOUNTS-->
<div class="clear"> </div>
<div class="item-total"><strong>[CARTTOTAL]</strong></div>
<div class="item-price"><strong>[shoppingcart_total]</strong></div>
<div class="clear"></div>
</div>
</div>
I am not getting your shopping cart properly how you are doing it.
but using below code as the reference you can solve your problem.
var uname = document.getElementById('uname1').value;
function checkFname(){
var fname = document.forms["form"]["fname"].value;
var chk_fname = fname.replace(/^[a-zA-z]{2,15}$/, '');
if (fname != chk_fname) {
document.getElementById("fname").className = '';
return true;
}
else if (fname == chk_fname) {
document.getElementById("fname").className = 'error';
return false;
}
}
function Register(){
var uname = document.getElementById('uname').value;
var user = {
'fname':document.getElementById('fname').value,
};
localStorage.setItem(uname,JSON.stringify(user));
}
function Validate(){
Register();
}
While inserting the data in local storage Register() function will take the username as key and user can be an array which can contain data.
That it is because you are overwriting, not adding. In your code you need to append elements to your storage, using your last record and adding the new one, like this:
var arrayShop = {name: 'Chair 2'};
if(localStorage.getItem("user") == null) {
localStorage.setItem("user",JSON.stringify([arrayShop]))
}
else{
var newArray = JSON.parse(localStorage.getItem("user"));
newArray.push(arrayShop);
localStorage.setItem("user", JSON.stringify(newArray))
}
In this example my 'Chair 1' is your new element to add, soo if you execute it two times it will add a new element that is what passed in arrayShop.

Need to append html element as user keep clicking a button with jquery

I am trying to append a div multiple times when clicking a button, the problem is that is only appending once. I need to append same div as user keeps clicking.
DIV I need to append multiple times is stored in a variable named $htmlDivForm in the jquery code.
I'm using bootstrap.
HTML code:
<div class="container">
<div class="row">
<div class="col-md-3">
<form id="formUser" action="index.html" method="post">
<div class="text-center">
<button id="moreFieldsBtn" class="btn" type="button" name="button">+</button>
</div>
</form>
</div>
<div class="col-md-9">
More Content...
</div>
</div>
</div>
jquery code:
var $moreFieldsBtn = $("#moreFieldsBtn");
var $formUser = $("#formUser");
var $htmlDivForm = $('<div class="form-group"><label class="labelName" for="inputText">Nombre</label><input class="form-control inputTextField" type="text" name="inputText" value=""></div>');
//Add input text field
$($moreFieldsBtn).click (function() {
$($formUser).append($htmlDivForm);
});
I had gone through your question.
I have Updated the example.
Removed the Object and just inserting plain HTML
var $moreFieldsBtn = $("#moreFieldsBtn");
var $formUser = $("#formUser");
var $htmlDivForm = $('<div class="form-group"><label class="labelName" for="inputText">Nombre</label><input class="form-control inputTextField" type="text" name="inputText" value=""></div>');
var htmltext = '<div class="form-group"><label class="labelName" for="inputText">Nombre</label><input class="form-control inputTextField" type="text" name="inputText" value=""></div>'
//Add input text field
$($moreFieldsBtn).click (function() {
$($formUser).append(htmltext);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-md-3">
<form id="formUser" action="index.html" method="post">
<div class="text-center">
<button id="moreFieldsBtn" class="btn" type="button" name="button">+</button>
</div>
</form>
</div>
<div class="col-md-9">
More Content...
</div>
</div>
</div>
<div>
You can't append the same div multiple times, you need to instantiate new divs and attach those. You also don't need to re-wrap the jQuery objects to attach the handlers:
var $moreFieldsBtn = $("#moreFieldsBtn");
var $formUser = $("#formUser");
//Add input text field
$moreFieldsBtn.click(function() {
var $htmlDivForm = $('<div class="form-group"><label class="labelName" for="inputText">Nombre</label><input class="form-control inputTextField" type="text" name="inputText" value=""></div>');
$formUser.append($htmlDivForm);
});

How to get the ID of the Current element clicked

I want to get the Value of the Current Element to be clicked.
I have a list of Checkboxes and selection of each I want to get the ID of it which is hidden.
My Code goes as follows:
$("#ModelListView").on("click", ".ModelCheckBox", function (element) {
var AnalysisID = $("#AnalysisID").val();
var ModelID = '';
});
HTML:
<div id="ModelListView"></div>
<script type="text/x-kendo-template" id="Modeltemplate">
<div class="section group fr">
<div class="col span_2_of_12">
#if(ACTIVE_MODELS_COUNT > 0){# <input class="ModelCheckBox" type="checkbox" checked/>#} else {# <input class="ModelCheckBox" type="checkbox" unchecked/> #}#
</div>
<div class="col span_4_of_12"><label>#:MODEL#</label></div>
<input id="Model_ID" type="hidden" value=#:MODEL_ID#/>
</div>
</script>
I want to get the Value of Model_ID that is kept hidden.
You can use $(this) and get the closest.
$(this) will be the element that's clicked.
.closest('.section.group') will return the "section group"-div. You might want to use #ModelListView instead of .section.group.
.find('#Model_ID').val() will return the value of the hidden field.
$("#ModelListView").on("click", ".ModelCheckBox", function (element) {
var AnalysisID = $("#AnalysisID").val();
var ModelID = $(this).closest('.section.group').find('#Model_ID').val();
alert(ModelID);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ModelListView">
<div class="section group fr">
<div class="col span_2_of_12">
<input class="ModelCheckBox" type="checkbox" checked/>
</div>
<div class="col span_4_of_12"><label>Label</label></div>
<input id="Model_ID" type="hidden" value="someValue"/>
</div>
</div>
Sidenote: be aware of using an ID in a template.

Javascript Remove a Template Element

I have a template that I will simplify as follows:
<script type="text/template" id="contactTemplate">
<div id="contactentry" class="row contact-info">
</div>
<div class="form-group">
<label for="name1">First Name</label>
<input type="text" class="form-control" id="FirstName" name="Contacts[{{ID}}].FirstName" required>
</div>
<div class="form-group minus">
<label for="contactMinus{{ID}}"> </label>
<a id="depminus{{ID}}"><i class="fa fa-minus-circle"></i>Remove</a>
</div>
</script>
I allow insertion of the template, multiple times via the following code, this part works:
<script type="text/javascript">
var clone = (function () {
var cloneIndex = -1;
var template = $('#contactTemplate').text();
return function () {
//Replace all instances of {{ID}} in our template with the cloneIndex.
return template.replace(/{{ID}}/g, ++cloneIndex);
}
})();//self executing function.
var contacts = $('#contacts')
$("#contactadd").on("click", function () {
contacts.append(clone());
window.controlManager.FindControls(contacts);
});
</script>
<div id='contacts'>
<div class="col col-lg-1">
<a id="contactadd"><i class="fa fa-plus-circle"></i>Add</a>
</div>
</div>
Now I am trying to figure out how to make javascript code to remove each element when/if the minus button is clicked (in the template).
I'm not sure what kindof code I could then use to delete the contacts, via the depminus{{ID}} control. Any tips to get me started?

How can I show alert box in struts 1.3.10?

How can i show alert box for validation in login form?
I got below output but i want alert box?
This is my index page: index.jsp
<html:form styleId="validate" action="/account_login" styleClass="account" method="post">
<div class="content controls single_advance">
<!-- <div class="form-row user-change-row">-->
<div class=form-row>
<div class=col-sm-3></div>
<div class=col-sm-4>
<bean:write name="account_bean" property="error" filter="false"/>
</div>
</div>
<div class="form-row">
<div class="col-md-12">
<div class=input-group>
<div class=input-group-addon> <span class=icon-user></span> </div>
<!--<input type=text class=form-control placeholder="Account Name"/>-->
<html:text property="name" styleClass="validate[required] form-control" styleId="Account_Name"/>
</div>
</div>
</div>
<div class=form-row>
<div class="col-md-12">
<div class=input-group>
<div class=input-group-addon> <span class=icon-key></span> </div>
<!--<input type=password class=form-control placeholder="Password"/>-->
<html:password property="password" styleClass="validate[required] form-control" styleId="Password"/>
</div>
</div>
</div>
<div class=form-row>
<div class="col-md-6 col-md-offset-3">
<input class="btn btn-default btn-block btn-clean btn-success" value="Log In" type="submit">
</div>
</div>
<!--<div class=form-row>
<div class="col-md-12"> Forgot your password? </div>
</div>-->
<div class=form-row>
<div class="col-md-12 tac"><strong>OR USE </strong></div>
</div>
<div class=form-row>
<div class="col-md-12"> <a class="btn btn-primary btn-block imeino"><span class="icon-mobile-phone"></span> IMEI NO LOGIN</a> </div>
</div>
</div>
</html:form>
This is my struts action class: account_actoin.java
if (account_name.equals(acc_name) && account_password.equals(acc_password)) {
HttpSession http_session = request.getSession(true);
http_session.setAttribute("login_name", acc_name);
ArrayList<String> name_list = new ArrayList<String>();
Query enc_password = session.createQuery("from account_dao");
List list = enc_password.list();
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
account_dao account = (account_dao) iterator.next();
System.out.println("Id : " + account.getId());
System.out.println("Account Name : " + account.getName());
System.out.println("Account Password : " + account.getPassword());
int i = 0;
name_list.add(i,account.getName());
i++;
}
request.setAttribute("namelist", name_list);
dealer_bean Bean = new dealer_bean();
Bean.setCustomerList(name_list);
System.out.println("List : "+name_list);
return mapping.findForward(SUCCESS);
} else {
fromBean.setError("<span style='color:red'><h6>Login failed.</h6></span>");
return mapping.findForward(FAILURE);
}
How can I show error (or) success message in alert box?
Append after the html:form close tag the next code and try:
<logic:present name="account_bean" property="error">
<div>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
// When DOM is ready
$(function() {
$("#errorDialog").dialog({
title: "Login",
autoOpen: false,
resizable: false,
show: "clip",
hide: "clip",
modal: true,
dialogClass: "ui-state-active"
});
});
// When Window is ready
$(window).load(function() {
$("#errorDialog").dialog("open");
});
</script>
<div id="errorDialog">
<bean:write name="account_bean" property="error" filter="false"/>
</div>
</div>
</logic:present>
Simply try using struts logic tags for your purpose. Here i used jQuery ready() function,
<logic:present name="account_bean" property="error">
<script>
$(document).ready(function() {
alert('Login failed.');
});
</script>
</logic:present>
Hope this helps..
I haven't tried it and I am not even sure if this works. It was too long to be written as a comment.
Create a field in your form bean as follows:
public class MyForm{
String isUserValid;
//its getters and setters
}
And then in your account_actoin.java
if (account_name.equals(acc_name) && account_password.equals(acc_password)) {
//rest of your code
formBean.setIsUserValid("Y")//------------Add this
return mapping.findForward(SUCCESS);
else {
formBean.setIsUserValid("N")//--------And this
return mapping.findForward(FAILURE);
}
In your jsp file add a hidden input and the following script as follows:
<head>
<script type="text/javascript">
$(document).ready(function(){
var isLoggedIn = $("#isUserValid").val();
if(isLoggedIn == "N"){
alert("Log in failed");
}
});
</script>
</head>
<body>
<input type="hidden" id="isUserValid" name="isUserValid" />

Categories