Adding a simple confirm/cancel dialog in jQuery 1.4.2 - javascript

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).

Related

How to pass textbox client ID to JavaScript function

I have a JS function to make textbox operation. When I sent textbox client ID, I am receiving this syntax error:
JavaScript runtime error: Syntax error, unrecognized expression: #<%=txtEposta.ClientID%>
How can I fix this error? I am very new to JavaScript. Whatever I tried I cannot find a solution. Please help.
function SearchText(clientID) {
console.log("#" + clientID);
var availableTags = ["gmail.com", "hotmail.com", "mynet.com", "yahoo.com", "outlook.com", "windowslive.com"];
$("#"+clientID).autocomplete({
source: availableTags,
matchCase: false,
focus: function (event, ui) {
var oldValue = $("#" + clientID).val();
var value = oldValue + ui.item.value;
event.preventDefault();
$("#" + clientID).val(value);
},
select: function (event, ui) {
var oldValue = $("#" + clientID).val();
var value = oldValue + ui.item.value;
$("#" + clientID).val(oldValue);
event.preventDefault();
},
minLength: 0
});
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="TextBoxControl.WebUserControl1" %>
<link href="/Script/jquery-ui.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="jquery-1.8.3.js"></script>
<script type="text/javascript" src="jquery-ui-1.8.24.js"></script>>
<script type="text/javascript" src="../common.js"></script>>
<div>
<asp:Textbox runat="server" ID="txtEposta" MaxLength="100" Width="250px" onKeyPress="javascript:SearchText('<%=txtEposta.ClientID%>');"
ControlType="AlpfaNumericAndSymbols" AllowSpaces="False" Visible="true"></asp:Textbox>
</div>
You could simply replace the txtEposta.ClientID with this.
<asp:Textbox runat="server" ID="txtEposta" onKeyPress="javascript:SearchText(this);"
<script>
function SearchText(element) {
alert(element.id);
}
</script>
If you really want to use ClientID you will have to add it programatically
<asp:TextBox runat="server" ID="txtEposta"></asp:TextBox>
<script>
function SearchText(element) {
alert(element);
}
</script>
and then in Page_Load
txtEposta.Attributes.Add("onKeyPress", string.Format("javascript:SearchText('{0}');", txtEposta.ClientID));
Set the property ClientIDMode in you Textbox to Static. Thes will make the ClientID be the same as the id on server side. Don't forget to change the onKeyPress argument.
<asp:Textbox runat="server" ID="txtEposta" ClientIDMode="Statis" MaxLength="100" Width="250px" onKeyPress="javascript:SearchText('txtEposta');"
ControlType="AlpfaNumericAndSymbols" AllowSpaces="False" Visible="true"></asp:Textbox>

i wanted to use this javascript function with asp update panel, Details are bellow

Here is the script that I am using for opening a new tab and it's working without using an update panel:
<script type="text/javascript">
function openInNewTab() {
window.document.forms[0].target = '_blank';
setTimeout(function () { window.document.forms[0].target = ''; }, 0);
}
This is my .aspx page: and i want to use it with update panel please help
<asp:ScriptManager ID="ScriptManager1" runat="server"
</asp:ScriptManager>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:Button ID="btnAssign" runat="server" Text="Assign" OnClientClick="SetTarget();" OnClick="btnAssign_Click"/>
</ContentTemplate>
</asp:UpdatePanel >
i want to use it with update panel please help me if there any solution
You code would run fine, if you would have noticed that your Javascript code has a syntax error. You are missing a closing } to define your function. Without it you are receving an unexpected end of input error.
In addition you will not open a new tab until you actually submit your form.
This code will work:
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<script>
function SetTarget() {
document.forms[0].target = "_blank";
console.log("Foo");
document.forms[0].submit();
}
</script>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:Button ID="btnAssign" runat="server" Text="Assign" OnClientClick="SetTarget();" />
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
You can use the below script. It will work for you.
<script language="javascript">
function SetTarget() {
document.forms[0].target = "_blank";
window.open(this.href);
alert("hello");
return false;
}
</script>
do let me know in case you required any more help.
Now i got solution by using a script and onclient click event
<script language="javascript">
function PopupHistory(url) {
var width = 550;
var height = 300;
var left = (screen.width - width) / 2;
var top = (screen.height - height) / 2;
var params = 'width=' + width + ', height=' + height;
params += ', top=' + top + ', left=' + left;
params += ', directories=no';
params += ', location=no';
params += ', menubar=no';
params += ', resizable=no';
params += ', scrollbars=no';
params += ', status=no';
params += ', toolbar=no';
newwin = window.open(url, 'windowname5', params);
if (window.focus) { newwin.focus() }
return false
}
</script>
on button event
<asp:Button ID="btnUnAssign" runat="server" Text="UnAssign" OnClientClick="return PopupHistory('/PatientAssignment/PatientUnAssign.aspx')" OnClick="btnUnAssign_Click" />

How to compare two text box values using jquery?

I have two text boxes named txtbalance and txtdays. If I enter greater value in txtdays than txtbalance I want show error message. I have a javascript method but it not working.
<script type="text/javascript" language="javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">
</script>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("#txtdays").on('input', function () {
var txtbalance = $('#txtbalance').val();
var txtdays = $('#txtdays').val();
if (txtbalance === "" || txtdays === "") return false;
if (parseInt(txtbalance) < parseInt(txtdays)) {
alert("u cant apply");
}
});
});
</script>
And my sourse code
<% Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="drop._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<style type="text/css">
.style1
{
width: 100%;
}
</style>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<head>
<script type="text/javascript" language="javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("#txtdays").on('input', function () {
var txtbalance = $('#txtbalance').val();
var txtdays = $('#txtdays').val();
if (txtbalance === "" || txtdays === "") return false;
if (parseInt(txtbalance) < parseInt(txtdays)) {
alert("u cant apply");
}
});
});
</script>
</head>
<table class="style1">
<tr>
<asp:TextBox ID="txtbalance" runat="server"></asp:TextBox>
</tr>
<tr>
<asp:TextBox ID="txtdays" runat="server"></asp:TextBox>
</tr>
</asp:Content>
please help me reach a solution...
if the balances are numbers, you most likely need to use parseInt. LIke this:
if (parseInt($('#txtbalance').val()) < parseInt($('#txtdays').val())) {
alert("u cant apply")
}
$(document).ready(function () {
var n = $("#txtbalance").val();
var m = $("#txtdays").val();
if(parseInt(n) > parseInt(m)) {
alert("Alert!");
}
});
Add event handler to change event of text boxes and compare values.
<script language="javascript" type="text/javascript">
var bal='';
var days='';
$(document).ready(function () {
$( "#txtbalance" ).change(function() {
bal=$(this).val();
return compare(bal,days);
});
$( "#txtdays" ).change(function() {
bal=$(this).val();
return compare(bal,days);
});
});
function(bal,days)
{
if(bal!='' && days!='' && parseInt(bal)<parseInt(days))
{
alert("u cant apply");
return false;
}
return true;
}
</script>
I would use key up method :
$("#txtdays").on('keyup', function () {
// your code here
}
http://jsfiddle.net/y7hgwyvy/ - jquery 1.7
$(document).ready(function () {
$("#txtdays").on('input', function () {
var txtbalance = $('#txtbalance').val();
var txtdays = $('#txtdays').val();
if (txtbalance === "" || txtdays === "") return false;
if ( parseInt(txtbalance) < parseInt(txtdays) ) {
alert("u cant apply");
}
});
});
you can also think about some delay when user typing value in txtdays input.
EDIT
solution for jquery 1.4 http://jsfiddle.net/y7hgwyvy/1/

jquery inside User Control created dynamically

I've created an User Control where I have a button. And when this button is clicked a jquery function is executed. The jquery function is inside the User Control page.
Now i'm trying to add this User Control dynamically in my page, inside an UpdatePanel.
The problem is that my button is not working.
After i google it, i found out that maybe the problem is in using jquery inside ajax UpdatePanel. After every asynchronous postback the jquery script is lost. So the idea is to rebind my jquery function in every asyn postback. But in the all answers that i found, they kinda suppose that the script manager is in User control and it's not in my case.
Here my jquery fucntion
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#<%= idButtonLeft %>").bind("click", function () {
var options = $("#<%= idListDestinataire %> option:selected");
for (var i = 0; i < options.length; i++) {
var opt = $(options[i]).clone();
$(options[i]).remove();
$("#<%= idListSource %>").append(opt);
}
});
$("#<%= idButtonRight %>").bind("click", function () {
var options = $("#<%= idListSource %> option:selected");
for (var i = 0; i < options.length; i++) {
var opt = $(options[i]).clone();
$(options[i]).remove();
$("#<%= idListDestinataire %>").append(opt);
}
});
});
</script>
the code to add my User control dynamically
Dim CListBox As UserControl = LoadControl("DragDropList.ascx")
CListBox.ID = "CListBox" + i.ToString()
CType(CListBox, DragDropList).idListSource = "ListLeft" + i.ToString()
CType(CListBox, DragDropList).idListDestinataire = "ListRight" + i.ToString()
CType(CListBox, DragDropList).idButtonLeft = "idButtonLeft" + i.ToString()
CType(CListBox, DragDropList).idButtonRight = "idButtonRight" + i.ToString()
UpdatePanel1.ContentTemplateContainer.Controls.Add(CListBox)
Panel1.Controls.Add(CListBox)
in my page i have this
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:Panel ID="Panel1" runat="server">
</asp:Panel>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ImageButton1" />
</Triggers>
</asp:UpdatePanel>
<asp:ImageButton ID="ImageButton1" ImageAlign="Right" EnableViewState="false" ImageUrl=".\image\ajouter.png" runat="server" AlternateText="Ajouter" OnClick="AjouterC"/>
So please any ideas to help.
Thank you
When i changed the trigger on PostBackTrigger, it's working but i want it in asynchrone postback. and still don't know why it's not working!
Use This
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args) {
if (args.get_error() == undefined) {
$(function () {
//Your script
});
}
}
</script>
This will work on post back that your update panel is giving to you.

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