how to hide freshly added div of view in MVC? - javascript

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.

Related

Assign JSON to value in input

<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" ></script>
<script type="text/javascript">
window.onload = function() {
$.getJSON('https://api.ipify.org/?format=json', function(data) {
$('.myip').text(data.ip);
});
};
</script>
<script type="text/javascript" src="https://api.ipify.org/?format=json"></script>
<script>
$('.send').on('click', function() {
document.getElementById('welcomeDiv').style.display = "block";
$.getJSON('https://ipapi.co/' + $('.ip').val() + '/json', function(data) {
$('.city').text(data.city);
$('.country_name').text(data.country_name);
$('.country_code').text(data.country_code);
$('.region').text(data.region);
$('.region_code').text(data.region_code);
$('.postal').text(data.postal);
$('.timezone').text(data.timezone);
$('.latitude').text(data.latitude);
$('.longitude').text(data.longitude);
$('.ip').text(data.ip);
$('.org').text(data.org);
$('.asn').text(data.asn);
});
});
</script>
<input type="text" name="ip" id="ip" maxlength="15" class="ipnput ip" value="">
<button type="button" class="submit send" id="showDiv" value="Check">Check</button>
In the javascript portion, I'm using ipify to grab the visiting users IP. I'd like to attach it to the html input value on load while running the second part of the JS that makes a call to ipapi with that ipify ip. New to JS so hoping someone could steer me in the right direction, thank you.
You got it pretty much right, but errors come from the typo.
In the onload handler you are targeting $('.myip') when in the HMTL you don't have an input with such classs. Also you need to use .val jQuery method.
Also the script element with ipify.org call in src is extra, not needed.
Try this:
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" ></script>
<script type="text/javascript">
window.onload = function() {
$.getJSON('https://api.ipify.org/?format=json', function(data) {
$('.ip').val(data.ip);
});
};
</script>
<script>
$('.send').on('click', function() {
document.getElementById('welcomeDiv').style.display = "block";
$.getJSON('https://ipapi.co/' + $('.ip').val() + '/json', function(data) {
$('.city').text(data.city);
$('.country_name').text(data.country_name);
$('.country_code').text(data.country_code);
$('.region').text(data.region);
$('.region_code').text(data.region_code);
$('.postal').text(data.postal);
$('.timezone').text(data.timezone);
$('.latitude').text(data.latitude);
$('.longitude').text(data.longitude);
$('.ip').text(data.ip);
$('.org').text(data.org);
$('.asn').text(data.asn);
});
});
</script>

Search country names with JavaScript and display country details

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

Using Jquery chosen in jquery ajax

I am using jquery chosen and calling ajax on change drop down but records are not displaying. This code which I am using after changing drop down.
$.ajax({
type: "POST",
url: "MY URL",
data: {
sno: $(this).val()
},
success: function (resp) {
var resp = jQuery.parseJSON(resp);
if (resp.length == 0) {
$("#site").html('<option value="0" selected>Select Site</option>');
} else {
$.each(resp, function (i, item) {
$('#site').append($('<option>', {
value: item.siteNameID + '-' + item.siteName,
text: item.siteName
}));
});
}
},
error: function (resp) {
console.log('error');
}
});
One thing I have noticed jquery chosen applying on my select box but data which I am fetching from server side is not adding in that select box
You will need to call the chosen update trigger after you add items to your select list dynamically in order for them to show up. Use the following line after you have appended items and they should be displayed in your list.
$('#site').trigger("chosen:updated");
I think my code is not the answer for your question, but this mimics adding options to select... just click the add button...
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<button onclick="add()">Add</button>
<select id="select"></select>
<script>
var json = [{title:"lorem",value:1},
{title:"john doe",value:2},
{title:"foo",value:3},
];
function add(){
$("#select").empty();
for(var x = 0; x<json.length; x++){
var option = '<option value="'+json[x].value+'"> '+json[x].value+'-'+json[x].title+'</option>';
$("#select").append($(option));
}
}
</script>
</body>
</html>

Adding a simple confirm/cancel dialog in jQuery 1.4.2

I have put a clickable span into every list item and it works fine.
For the moment it invokes a simple alert.
Now I would like to add a simple cancel/confirm dialog. Each selection should call a function.
Here is my code (note the alert where the span click invokes):
<%# Reference Control="~/KPIP/Controls/MultiUpload.ascx" %>
<%# Register Src="~/KPIP/Controls/MultiUpload.ascx" TagName="MultiUpload" TagPrefix="tetrada" %>
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Entry.aspx.vb" Inherits="KPIP_Entry" %>
var barcodes = { <%# BarcodeArray %> }
kpip.viewAttachment = function (url) {
$("#entryViewer").attr("src", "../Viewer.aspx?image=" + url);
}
function resizeViewer() {
$("#entryViewer").hide();
$("#attachments").hide();
$("#entryViewer").width($("#entryForm").width() - 320 - 4);
$("#entryViewer").height($("#entryForm").height() - $("#header").height() - 4);
$("#attachments").height($("#entryForm").height() - $("#header").height() - 4);
$("#attachments").show();
$("#entryViewer").show();
}
$(function () {
$.each(barcodes, function(key, value) {
$("#barcodesList").append("<li>" + key + "</li>");
});
deleteButton = $('<span />').addClass('deleteButton').text('Delete');
$('ul#barcodesList li').append(deleteButton);
if ($("#barcodesList").children().size() > 0) {
$("#barcodesList").after('<div id="barcodesShadow" class="cc_panelShadow"></div>');
}
$("#barcodesList > li").click(function () {
$(this).children(".children").toggle();
$("#barcodesList > li").removeClass("clicked");
$(this).addClass("clicked");
$("#selectedBarcode").val($(this).text());
var params = '{ barcode : "' + $(this).text() + '", path : "' + barcodes[$(this).text()] + '" }';
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Entry.aspx/Attach",
dataType: "json",
data: params,
success: function () {
$("#dummyPostbackButton").click();
},
error: function (request, status, error) {
alert("Error attaching barcode file.");
}
});
});
$("#barcodesList > li > span").click(function(e) {
e.stopPropagation();
var partxt = $(this).parent().clone().children().remove().end().text();
alert(partxt);
});
$(window).bind("resize", function () {
setTimeout(function () { resizeViewer(); }, 10);
});
setTimeout(function () { resizeViewer(); }, 10);
$("#barcodesList > li").each(function () {
if ($(this).text() != $("#selectedBarcode").val()) { return; }
$(this).addClass("clicked");
});
});
</script>
</head>
<body>
<form id="entryForm" runat="server">
<div id="header" class="ContentHeader">
<asp:Label runat="server" CssClass="ContentHeaderLabel" Text="<%$ Resources: Header.Text %>"/>
</div>
<div id="attachments">
<asp:Label class="tetradaGroupLabel" runat="server" Text="<%$ Resources: AttachmentsPanel.Text %>" />
<tetrada:MultiUpload ID="upload" runat="server" />
<asp:Panel ID="BarcodesListPanel" runat="server">
<asp:Label class="tetradaGroupLabel" runat="server" Text="<%$ Resources: BarcodesPanel.Text %>" />
<ul id="barcodesList"></ul>
</asp:Panel>
<asp:HiddenField ID="selectedBarcode" runat="server" />
<asp:Button ID="dummyPostbackButton" runat="server" CausesValidation="false" />
</div>
<iframe id="entryViewer" frameborder="0" runat="server"></iframe>
</form>
</body>
</html>
I tried putting dialog in several places and opening it in click event, but nothing happens. Can some one please help me out here?
Best regards, no9.
If bu simple you mean native,use confirm instead of alert;
confirm("Your Text")//Return true if user pressed ok
// false otherwise
so you can do something like:
if(confirm("Your Text")){
//do stuff
}
If you want to add a confirm dialog box to your code
It looks like
var choice = confirm("Are you sure?");
And validates if the user clicks yes || no
if(choice == true) {
//then do something here
}
Hope it helps..
There is a plugin for that: Simple Confirm Dialog (many other similar plugins are out ther, too, I guess).

Javascript function in Partial view can't access Javascript variable defined in page (MVC 3)

I am trying to learn to use Knockoutjs but I am facing a problem
this is the scenario:
I have a page where I define a Knockoutjs viewModel as follow
$(document).ready(function () {
var viewModel = {
selectedColumns: ko.observableArray()
};
ko.applyBindings(viewModel);
});
Now with an Ajax request I add to the page a checkbox which I want to bind to the viewModel
<input type='checkbox' id='someId' data-bind='attr: { value: 'someValue' }, checked: $root.selectedColumns'>
$(document).ready(function() {
ko.applyBindings(viewModel, document.getElementById(someId));
});
but I always get
Error: ReferenceError: viewModel is not defined
Source File: http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js
I've created a test page where everything is on one page and it works
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Home Page</title>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
<script src="../../Scripts/knockout-2.1.0.debug.js" type="text/javascript"></script>
<script type="text/javascript">
var count = 0;
var viewModel = {
selectedPeople: ko.observableArray()
};
$(document).ready(function () {
ko.applyBindings(viewModel);
});
function AddAnotherCheckbox(){
var id = "checkbox" + count;
var checknox = count + " <input type='checkbox' id='" + id + "' data-bind='attr: { value: \"" + count + "\" }, checked: $root.selectedPeople'><br/>";
$("#container").append(checknox);
count++;
$(document).ready(function() {
ko.applyBindings(viewModel, document.getElementById(id));
});
}
</script>
</head>
<body>
<input type="button" onclick="AddAnotherCheckbox()"/>
<div id="container"></div>
<br/>
<br/>
<br/>
<span data-bind="text: selectedPeople"></span>
</body>
</html>
But I can't make it working using partial view
Could you explain to me what's the problem and how can I solve it?
thanks
Description
This is not about Knockout, it's about JavaScript in general.
Your Testcode works because you have defined the viewModel outside of $(document).ready
This is a other scope.
Compare theese to jsFiddles
This does not work (your scenario)
This works
Sample
This does not work
$(document).ready(function () {
var viewModel = {
someThing : "Test"
};
});
$(document).ready(function () {
alert(viewModel.someThing);
});
This will work
var viewModel;
$(document).ready(function () {
viewModel = {
someThing : "Test"
};
});
$(document).ready(function () {
alert(viewModel.someThing);
});
More Information
Explaining JavaScript Scope And Closures
​

Categories

Resources