jquery inside User Control created dynamically - javascript

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.

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" />

Pass a hidden field value to javascript (href)

I am using javascript to do href. The code as below
<script>
window.onunload = refreshParent;
function refreshParent() {
var SAPno = document.getElementById('HiddenNo');
window.opener.location.href="Inventory.aspx?" + "SAPNo="+ SAPno +;
}
</script>
my hidden field code as below
<asp:HiddenField ID="HiddenNo" runat="server" />
may I know how to use the value in hiddenfield and pass to Inventory.aspx? and anyone know how to retrieve the value?
Thanks!
<script>
window.onunload = refreshParent;
function refreshParent() {
var SAPno = document.getElementById('HiddenNo').value;
window.opener.location.href="Inventory.aspx?" + "SAPNo="+ SAPno
}
</script>
If you want to use JQuery then
$('HiddenNo').val()

Refactoring Javascript code from Aspx file

I am refactoring the web project,where java script and css code is written inside the .aspx file.Now I am removing java script and css code from the aspx files and maintaining that the code in respective css and js files with their reference in aspx files.
It is straight forward for me if java script code is written in one place and inside the funtion.Here in the example code not all java script code is inside the function and some of the script are inside the div block.I am not able to put these script in separate file.Moreover I am new bee in Java script and web development please help me on this.
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
-------code-----------
</script>
<% Html.EnableClientValidation(); %>
<% using (Html.BeginForm())
{%>
<%: Html.ValidationSummary(true) %>
<div class="formColWhole" style="width: 935px;">
<script type="text/javascript">
document.body.style.cursor = 'default';
document.forms[0].action = '<% = ViewData["RegisterPageUrl"].ToString() %>';
function IndicateProcessing() {
if (typeof (Page_ClientValidate) == 'function') {
if (Page_ClientValidate() == false) { return false; }
}
var cancelButton = document.getElementById("<% = buttonCancel.ClientID %>");
if (cancelButton != null) {
cancelButton.disabled = true;
}
document.body.style.cursor = 'wait';
return true;
}
function submitForm() {
IndicateProcessing();
// _gaq.push(['_trackEvent', 'Register', 'Register submit Click', 'Register submit']);
// avoid duplicate submission
var button = $("#buttonSend");
button.attr('disabled', true).html('');
document.forms[0].submit();
}
</script>
</div>
<div class="formColWhole" style="width: 100%;">
--------code----
</div>
<script type="text/javascript">
var selectCountryText = document.getElementById("<% = selectCountry.ClientID %>").value;
var regions = document.getElementById("region");
regions.firstChild.text = selectCountryText;
</script>
</asp:Content>

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

Categories

Resources