Search country names with JavaScript and display country details - javascript

In my project I want to get a country flag while searching, with an API call, and on clicking on that flag it should redirect to another page and display the respective country details.
I tried with a JavaScript API call, in that I am getting the country details and the flag on the same page after clicking on search, but I want to display details other than flags in another page. After clicking on the flag I want to display the country details.
$("form").submit(function(e) {
e.preventDefault();
$("#display").empty();
let name = e.currentTarget.name.value;
if(!name){
alert("Enter name");
return;
}
getCountryName(name).then(result =>{
result.forEach(element => {
var card = $('<div>', {class: "card"}).appendTo('#display');
var country = $('<div>', {class: "country-info"}).appendTo(card);
var img = $('<a href="https://restcountries.eu/rest/v2/name/${name}"><div>',
{class: "img"}).appendTo(country);
$('<img>', {src: element.flag}).appendTo(img);
var text = $('<div>', {class: "right-text"}).appendTo(country);
$('<p>', {text: "Name: " + element.name}).appendTo(text);
$('<p>', {text: "Top Level Domain: " +
element.topLevelDomain}).appendTo(text);
$('<p>', {text: "Capital: " + element.capital}).appendTo(text);
$('<h4>', {text: 'Currencies:'}).appendTo(text);
element.currencies.forEach(element =>{
var currencies = $('<div>', {
class: "currencies"
}).appendTo(text);
$('<span>', {text: element.code + " "}).appendTo(currencies);
})
});
}).catch(err =>console.log(err));
});
async function getCountries(){
const response = await
fetch(`https://restcountries.eu/rest/v2/all`);
const responseData = await response.json();
return responseData;
}
async function getCountryName(name){
const response = await
fetch(`https://restcountries.eu/rest/v2/name/${name}`);
const responseData = await response.json();
return responseData;
}
<html lang="en" >
<head>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<form>
<div class="search-group ">
<label for="name">Enter country</label>
<input class="search-line" type="search" name="name">
<br/>
<input class="search-line" type="submit" id="search" value="Search
by Name">
</div>
</form>
<div id="display" class="search-line"></div>
</div>
I want to get the country details in another page after clicking on a country flag. Now i am getting the country details and flags on the same page.

You already got all details with one call, you can hide the details and just bind an onClick event to the image by clicking on it, show the details and hide the flag. I just added some css and a javascript function to handle that, and if you want to redirect to another page and show the details there, simply add another page and pass down the details and show there. check out the changes I made below
<html lang="en" >
<head>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256 CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
</head>
<style media="screen">
.right-text {
display: none;
}
</style>
<body>
<div class="container">
<form>
<div class="search-group ">
<label for="name">Enter country</label>
<input class="search-line" type="search" name="name">
<br/>
<input class="search-line" type="submit" id="search" value="Search
by Name">
</div>
</form>
<div id="display" class="search-line"></div>
</div>
<script src="main.js" charset="utf-8"></script>
</body>
</html>
and your main.js file
$(document).ready(function() {
$("form").submit(function(e) {
e.preventDefault();
$("#display").empty();
let name = e.currentTarget.name.value;
if(!name){
alert("Enter name");
return;
}
getCountryFlag(name).then(result =>{
console.log(result[0].flag);
result.forEach(element => {
var card = $('<div>', {class: "card"}).appendTo('#display');
var country = $('<div>', {class: "country-info"}).appendTo(card);
var img = $('<a id="img-link" href="#" onClick="showInfo()"><div>',
{class: "img"}).appendTo(country);
$('<img>', {src: element.flag}).appendTo(img);
var text = $('<div>', {class: "right-text"}).appendTo(country);
$('<p>', {text: "Name: " + element.name}).appendTo(text);
$('<p>', {text: "Top Level Domain: " +
element.topLevelDomain}).appendTo(text);
$('<p>', {text: "Capital: " + element.capital}).appendTo(text);
$('<h4>', {text: 'Currencies:'}).appendTo(text);
element.currencies.forEach(element =>{
var currencies = $('<div>', {
class: "currencies"
}).appendTo(text);
$('<span>', {text: element.code + " "}).appendTo(currencies);
})
});
}).catch(err =>console.log(err));
});
});
async function getCountryFlag(name){
const response = await
fetch(`https://restcountries.eu/rest/v2/name/${name}`);
const responseData = await response.json();
return responseData;
}
function showInfo() {
console.log($('.right-text'));
$('.right-text').css('display', 'block');
$('img').css('display', 'none');
}

Related

Local storage and window.location.href.replace

I and my course mate are trying to write a code where when the order button is clicked it should save on local storage and redirect to an order page.
So far when we click on order it is not registered in the application/local storage section of the google developer tool and thus does not redirect to a new page.
We put an eventlistener to show a console.log for when we click, just to be sure the buttons are in order(this part is not important).
We also used an online javascript validator to eliminate typos and errors.
Also do we need any specific code on the order.html file to interface with local storage?
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>grc</title>
<link rel="stylesheet" href="css/style.css" type="text/css">
</head>
<body>
<header>
<nav>
<ul>
<li>Home</li>
<li>Groceries</li>
<li>Contact</li>
</ul>
</nav>
</header>
<main>
<aside><img class="imgclass1" src="images/rounded logo.png" alt="Grocer Nigeria"></aside>
<article class="preinventory">
<section class="columns-desktop">
<div class="inventory">
<img class="sales" src="images/tomato.jpg" alt="Tomato"/>
<div class="columns">
<div class="title">Tomato</div>
<div class="Price">$100</div>
</div>
<p class="Desc"> Our Tomato2</p>
<button data-order="Tomato2">Order</button>
</div>
<div class="inventory">
<img class="sales" src="images/tomato.jpg" alt="Tomato"/>
<div class="columns">
<div class="title">Tomato</div>
<div class="Price">$100</div>
</div>
<p class="desc"> Our Tomato</p>
<button data-order="Tomato">Order</button>
</div>
</section>
</article>
</main>
<footer>
<nav>
<ul>
<li>Home</li>
<li>Groceries</li>
<li>Contact</li>
</ul>
</nav>
</footer>
<script type="text/javascript">
window.addEventListener("DOMcontentLoaded", function(e){
const orderButtons= document.querySelectorAll("button[data-order]");
orderButtons.forEach(function(button){
button.addEventListener("click",function(e){
const button= e.currentTarget;
const container= button.parentNode;
const order={
id:button.getAttribute("data-order"),
title: container.querySelector(".title").innerText,
price1: container.querySelector(".Price").innerText,
desc:container.querySelector(".desc").innerText
};
localStorage.setItem('order', JSON.stringify(order));
const url = window.location.href.replace("grc.html","order.html");
window.location.href = url;
});
});
});
window.addEventListener("DOMcontentLoaded", function(e){
console.log("The page is loaded.");
});
const orderButtons= document.querySelectorAll("button[data-order]");
orderButtons.forEach(function(button){
button.addEventListener("click", function(e){
console.log("The button was clicked.");
});
});
</script>
</body>
</html>
**Below is what I see when I run the live server**
<!-- Code injected by live-server -->
<script type="text/javascript">
// <![CDATA[ <-- For SVG support
if ('WebSocket' in window) {
(function() {
function refreshCSS() {
var sheets = [].slice.call(document.getElementsByTagName("link"));
var head = document.getElementsByTagName("head")[0];
for (var i = 0; i < sheets.length; ++i) {
var elem = sheets[i];
head.removeChild(elem);
var rel = elem.rel;
if (elem.href && typeof rel != "string" || rel.length == 0 || rel.toLowerCase() == "stylesheet") {
var url = elem.href.replace(/(&|\?)_cacheOverride=\d+/, '');
elem.href = url + (url.indexOf('?') >= 0 ? '&' : '?') + '_cacheOverride=' + (new Date().valueOf());
}
head.appendChild(elem);
}
}
var protocol = window.location.protocol === 'http:' ? 'ws://' : 'wss://';
var address = protocol + window.location.host + window.location.pathname + '/ws';
var socket = new WebSocket(address);
socket.onmessage = function(msg) {
if (msg.data == 'reload') window.location.reload();
else if (msg.data == 'refreshcss') refreshCSS();
};
console.log('Live reload enabled.');
})();
}
// ]]>
</script>
</body>
</html>
The issue here is that the event DOMContentLoaded does not fire.
Here is how I have used the load event instead; for redirection, I have simply used URL search params (because I don't know what your other html file looks like) although you may use your other html document instead.
The snippet is below
However note: Stackoverflow will not allow the JavaScript to run, and will throw a securityError. To run this code you must save it on your computer or use a jsFiddle
function continue_ordering() {
alert("Now continue with order");
};
window.addEventListener("load", function(e) {
const orderButtons = document.querySelectorAll("button[data-order]");
orderButtons.forEach(function(button) {
button.addEventListener("click", function(e) {
const button = e.currentTarget;
const container = button.parentNode;
const id = button.getAttribute("data-order");
const order = {
id,
title: container.querySelector(".title").innerText,
price1: container.querySelector(".price").innertext,
desc: container.querySelector(".desc").innerText
};
localStorage.setItem("order-" + id, JSON.stringify(order));
window.location.search = "?ordering=true&order-id=" + id;
});
});
});
window.addEventListener("load", function(e) {
if (window.location.search.search("ordering=true") != -1) {
console.log("User is ordering");
const params = new URLSearchParams(location.search)
const id = params.get("order-id");
if (!id || id == null) throw "There is no order id, error. Remove the ?ordering=true from the url and try again.";
const order_info = JSON.parse(localStorage.getItem("order-" + id));
if (!order_info) throw "Order information is not present: try ordering again. Remove the ?ordering=true from the url";
console.log("Order info is:\n", order_info);
document.getElementById("ordering").removeAttribute("hidden");
return;
};
document.getElementById("make-order").removeAttribute("hidden");
});
const orderButtons = document.querySelectorAll("button[data-order]");
orderButtons.forEach(function(button) {
button.addEventListener("click", function(e) {
console.log("The button was clicked.");
});
});
<div id="make-order" hidden>
<button data-order="test">Order</button>
<div class="title">This is the title</div>
<div class="price">130 USD</div>
<div class="desc">Lorem</div>
</div>
<div id="ordering" hidden>
<h1>
You are ordering.
<br> Choose
Stop ordering Or Continue with order
</h1>
</div>
The DOMcontentLoaded event has already fired by the time that code hooks it.
Check this post;
Code inside DOMContentLoaded event not working

Using inputs in HTML to run functions

so I am working on a stock market simulator using HTML and JS. I have a api here that gets current stock prices. Here is my HTML http://pastebin.com/ymcGKtin Sorry about pastebin not very good at formatting for SO. But in the function add stock I am trying to push the submitted form stockto the array stocks. However I have run into a problem trying to figure out how to get the submitted form stock and push it to the array. If I could get some pointers on how to do this it would be appricated. To be specific I would like help on getting the attribute stock pushed to the array Stocks. Ideas?
var Market = {};
var Stocks = [];
Market.getQuote = function(symbol, fCallback){
this.symbol = symbol;
this.fCallback = fCallback;
this.DATA_SRC = "http://dev.markitondemand.com/Api/v2/Quote/jsonp";
this.makeRequest();
}
Market.getQuote.handleSuccess = function(jsonResult){
this.fCallback(jsonResult);
}
Market.getQuote.handleError = function(jsonResult){
console.error(jsonResult);
}
Market.makeRequest = function () {
//Abort any open requests
if (this.xhr) { this.xhr.abort(); }
//Start a new request
this.xhr = $.ajax({
data: { symbol: this.symbol },
url: this.DATA_SRC,
dataType: "jsonp",
success: this.handleSuccess,
error: this.handleError,
context: this
});
};
function addStock(){
alert("derp");
// Stocks.push(ele.getAttribute)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Stock Market Game PRE ALPHA BETA</title>
</head>
<body>
<form onsubmit = "addStock()">
<input type="text" name="stock" value =""><br><br>
<input type="submit" value="Get Price">
</form>
</body>
</html>
With JQuery you could use find on the form-object (this in the onsubmit-handler):
...
function addStock(form){
var value = $(form).find('input[name="stock"]').val();
alert(value);
Stocks.push(value);
//prevents a submit of the form
return false;
}
</SCRIPT>
<form onsubmit = "return addStock(this);">
<input type="text" name="stock" value =""><br><br>
<input type="submit" value="Get Price">
</form>
...
Changed the addStock() function to use the form element collection method.
function addStock(){
var xForm = document.forms[0];
var xField = xForm.elements[0];
alert("Stock: "+xField.value);
Stocks.push(xField.value);
console.log(Stocks);
}
var Market = {};
var Stocks = [];
Market.getQuote = function(symbol, fCallback) {
this.symbol = symbol;
this.fCallback = fCallback;
this.DATA_SRC = "http://dev.markitondemand.com/Api/v2/Quote/jsonp";
this.makeRequest();
}
Market.getQuote.handleSuccess = function(jsonResult) {
this.fCallback(jsonResult);
}
Market.getQuote.handleError = function(jsonResult) {
console.error(jsonResult);
}
Market.makeRequest = function() {
//Abort any open requests
if (this.xhr) {
this.xhr.abort();
}
//Start a new request
this.xhr = $.ajax({
data: {
symbol: this.symbol
},
url: this.DATA_SRC,
dataType: "jsonp",
success: this.handleSuccess,
error: this.handleError,
context: this
});
};
function addStock() {
var xForm = document.forms[0];
var xField = xForm.elements[0];
alert("Stock: " + xField.value);
Stocks.push(xField.value);
console.log(Stocks);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Stock Market Game PRE ALPHA BETA</title>
</head>
<body>
<form onsubmit="addStock()">
<input type="text" name="stock" value="">
<br>
<br>
<input type="submit" value="Get Price">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
</body>
</html>

Increase in number of divs, while using jsPlumb

I have created three div elements in an HTML page, each of these 3 div elements contain a text box i.e. an input element in it. One div, is made a source while other two are made target. The HTML page has a button name toggle.
The initial connection between source div and one of the target div is created with the help of drag and drop. When toggle is clicked, it will remove the connection between the source and the target, and will create the new connection between source and the other target. Now, when performing analysis using google chrome developer tools over this scenario, the number of div elements keep on increasing by 2 for every toggle.
<!DOCTYPE html>
<html>
<head>
<title>
jsplumb_demo
</title>
<script src="./dist/libs/jquery.js"></script>
<script src="./src/jquery-ui.min.js"></script>
<script src="./src/jquery.jsPlumb-1.7.6-min.js"></script>
<script>
var connection12 = undefined, connection13 = undefined;
jsPlumb.ready(function() {
var exampleGreyEndpointOptions = {
endpoint:"Rectangle",
paintStyle:{ width:10, height:10, fillStyle:'#666' },
isSource:true,
connectorStyle : { strokeStyle:"#666" },
isTarget:true,
container:$('#container'),
connector : "Straight",
deleteEndpointsOnDetach: true
};
jsPlumb.makeSource($('div.source'), exampleGreyEndpointOptions);
jsPlumb.makeTarget($('div.target'),exampleGreyEndpointOptions);
jsPlumb.makeTarget($('div.target1'),exampleGreyEndpointOptions);
init = function(connection){
};
connectionDelete = function(){
if(connection12 !== undefined){
jsPlumb.detach(connection12);
jsPlumb.unmakeTarget($('div.target'));
connection13 = jsPlumb.connect({source : $('#source'), target : $('#target1')},exampleGreyEndpointOptions);
connection12 = undefined;
}
else{
jsPlumb.detach(connection13);
jsPlumb.unmakeTarget($('div.target'));
connection12 = jsPlumb.connect({source : $('#source'), target : $('#target')},exampleGreyEndpointOptions);
connection13 = undefined;
}
};
});
jsPlumb.doWhileSuspended(function(){
jsPlumb.bind("connection", function(connInfo, originalEvent) {
init(connInfo.connection);
//alert("Source div id = " + connInfo.sourceId + " Target div id = " + connInfo.targetId);
var input = "input#" +connInfo.sourceId;
var inputval = $(input).val();
var output = "input#" +connInfo.targetId;
$(output).val(inputval + " from " + connInfo.sourceId);
connInfo.targetId ==='target'?connection12 = connInfo : connection13 = connInfo;
});
jsPlumb.bind("click", function(conn, originalEvent) {
if (confirm("Delete connection from " + conn.sourceId + " to " + conn.targetId + "?"))
jsPlumb.detach(conn);
});
jsPlumb.bind("connectionDrag", function(connection) {
// alert("connection " + connection.id + " is being dragged. suspendedElement is ", connection.suspendedElement, " of type ", connection.suspendedElementType);
});
jsPlumb.bind("connectionDragStop", function(connection) {
// alert("connection " + connection.id + " was dragged");
});
jsPlumb.bind("connectionMoved", function(params) {
//alert("connection " + params.connection.id + " was moved");
});
});
</script>
</head>
<body>
<div id="container">
<div class="source" id="source" style="position: absolute;left: 200px" >
<input/>
</div>
<div class="target" id="target" style="position: absolute;left: 600px" >
<input />
</div>
<div class="target1" id="target1" style="position: absolute;left: 600px; top:200px" >
<input />
</div>
</div>
<button name="delete" type="button" onclick="connectionDelete()">Toggle</button>
</body>
</html>
Edit :-
Fiddle link

How to add to my JSON Object using a form

I'm trying to figure out how to add my object from a form. Any ideas how I can add a new name and photo_url to the end of my object?
Thanks,
data = [
{name: "Mark-Paul Gosselaar", photo_url: ""},
{name: "Delta Burke", photo_url: "img/avatars/delta.png"},
{name: "Alf", photo_url: "img/avatars/alf.png"},
{name: "Jaleel White", photo_url: "img/avatars/jaleel.png"},
{name: "Ralph Macchio", photo_url: "img/avatars/ralph.png"},
{name: "Candace Cameron", photo_url: "img/avatars/candace.png"},
{name: "Patrick Duffy", photo_url: "img/avatars/pduff.png"},
{name: "Arnold Schwartzengger", photo_url: "img/avatars/arnold.png"}
];
//MY CODE
$(document).ready(function() {
var employee = data;
var directory = $("#directory");
//SORT THROUGH THE JSON DATA AND REVERSE IT
function reverseArr(input) {
for (var i = input.length - 1; i >= 0; i--) {
var photoPlacement = employee[i].photo_url;
//CHECKS TO SEE IF A PHOTO_URL OBJECT HAS SOMETHING IN IT, IF IT DOESN'T THEN INJECTS THE DEFAULT IMAGE
if (photoPlacement.length <= 0) {
photoPlacement = 'img/default.png'
} else {
photoPlacement = employee[i].photo_url;
}
var employeePost = "<div class='employee'><div id='photo'><img src=" + photoPlacement + "></div><div id='closeButton' class='close'><img src='img/close.png'></div><div class='empName'>" + employee[i].name + "</div></div>";
console.log(employee[i].name);
console.log(employee[i].photo_url);
directory.append(employeePost);
}
}
var b = reverseArr(employee);
//SHOW THE "X" (CLOSE) BUTTON
$('.employee').hover(
function() {
$(this).children("#closeButton").removeClass("close")
$(this).children("#closeButton").addClass("showClose")
//IF THE "X" (CLOSE) BUTTON IS CLICKED, DELETE PARENT DIV
$(this).children("#closeButton").click(function(event) {
event.preventDefault();
$(this).parent(".employee").remove();
})
},
function() {
$(this).children("#closeButton").removeClass("showClose")
$(this).children("#closeButton").addClass("close")
}
);
//IF FORM BUTTON IS CLICKED, SUBMIT NEW DATA TO JSON OBJECT
$(":button").click(function(event) {
event.preventDefault();
});
});
This is how my HTML is formatted and need to have whatever name you type in the first input box to be added to data.
<!DOCTYPE html>
<html>
<head>
<link href="css/application.css" rel="stylesheet">
</head>
<body>
<div id="main-content">
<!-- The page width is 817px -->
<!-- Example of using the form CSS to help you out. -->
<form>
<div>
<label>Full Name</label>
<input name="name" type="text" required />
</div>
<div>
<label>Photo URL</label>
<input name="photo_url" />
</div>
<button type="submit">Create</button>
</form>
<hr />
<!-- Employee list goes here. There is initial data for you in application.js -->
<div id="directory">
</div>
</div>
<script src="js/vendor/jquery.min.js" type="text/javascript"></script>
<script src="js/vendor/underscore.js" type="text/javascript"></script>
<script src="js/application.js" type="text/javascript"></script>
<script src="js/main.js" type="text/javascript"></script>
</body>
</html>
Bind the form and listen to submit event. Convert the form to json object and push to data.
$(function() {
//listen to form submit
$("form").on("submit", function(event) {
event.preventDefault();
//serialize form to object
var formData = $(this).serializeObject();
data.push(formData);
console.log(data);
$("#data").html(JSON.stringify(data));
});
});
Plnkr - http://plnkr.co/edit/dhLqCkXmpGHit78ZGAxZ?p=preview
Convert form data to JavaScript object with jQuery

how to hide freshly added div of view in MVC?

I am developing MVC 3 application and using razor syntax.
In this application I am giving commenting facility.
I have added the Comment link in every Div. . When user click on that comment link, it loads the partial view which contains group of controls for Adding comments.
Now my issue is regarding Deleting fresh comments.
I have code which delete already saved comments..Its working perfectly...
Now the problem is When user enters new comment and try to delete it wont get deleted...
see the blue squre.
You can understand by this image...
my code is...
<script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script>
#model IEnumerable<CRMEntities.Comment>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
//Button which Saves currently added comment in DB as well display on screen...
<script src="../../Scripts/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#AddCommentButton').click(function ()
{
// alert("clicked");
$.ajax({
type: 'post',
url: '/Comment/SaveComments',
dataType: 'json',
data:
{
'comments' : $('#Comment').val(),
'EType' : #Html.Raw(Json.Encode(ViewBag.EType)),
'EId' : #Html.Raw(Json.Encode(ViewBag.EId))
},
success: function (data) {
$("p.p12").append('<div style="background-color:#FAFAFA;">Recently Added... <br />' + data.OwnerName + ''+ data.cmtDateTime +'<button type="button" id=' + data.Id + ' class="deleteComment">Delete</button></span><br />' + data.msg + '</div>')
}
});
});
});
</script>
<script src="../../Scripts/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".ShowComments").click(function () {
$(".ParentBlock").slideToggle("slow");
});
});
</script>
</head>
<body>
#{
<div class="ParentBlock">
#foreach (var item in Model)
{
<div class="OwnerClass" id="OwnerName">
<span class="EmpName"> #Html.ActionLink(item.Owner.FullName, "Details", "EMployee", new { id = item.OwnerId }, new { #style = "color:#1A6690;" })</span>
#Html.DisplayFor(ModelItem => item.CommentDateTime)
<span class="EmpName"><button type="button" id = "#item.Id" class="deleteComment">Delete</button></span>
<p class="CommentP">
#Html.DisplayFor(ModelItem => item.CommentText)
</p>
</div>
}
<p class="p12">
</p>
</div>
<p id="ClassPara" class="ShowComments" onclick="chkToggle()">Show All Comments</p>
}
#Html.TextArea("Comment", "", 5, 80, "asdsd")
<input type="button" value="Add Comment" id="AddCommentButton"/>
<input type="button" value="Clear" onclick="clearText()"/>
<br />
</body>
</html>
<script src="../../Scripts/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
// Working code - Deletes the comment from DB and removes hide the current Div
////////////////////////////////////////////////////////
$(document).ready(function () {
$(".deleteComment").click(function ()
{
alert("asd");
var Id = $(this).attr("id");
var self = this;
var url1="#Html.Raw(Url.Action("DeleteComment", "Comment", new { id = "idValue" }))";
url1=url1.replace("idValue",Id );
alert(url1);
$.ajax(
{
type: 'post',
url: '/Comment/DeleteComment',
dataType: 'json',
data:
{
'EId' : Id
},
success: function (data)
{
alert ("Hello");
$(self).closest("div").hide("slow");
}
});
});
});
</script>
In the success method when you append the new div, just add a class to the delete button that has a CSS of display:none
For example:
$("p.p12").append('<div style="background-color:#FAFAFA;">Recently Added... <br />' + data.OwnerName + ''+ data.cmtDateTime +'<button type="button" id=' + data.Id + ' class="deleteComment hidden">Delete</button></span><br />' + data.msg + '</div>')
CSS:
.hidden { display: none;}
When you are ready to show it, you can simply remove the class from the button.

Categories

Resources