How to pass textbox client ID to JavaScript function - javascript

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>

Related

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

add click event to auto complete

this is my AutoComplete code :
<link href="JostejuFile/css/jquery.autocomplete.css" rel="stylesheet" type="text/css" />
<script src="JostejuFile/scripts/jquery-1.4.1.min.js"></script>
<script src="JostejuFile/scripts/jquery.autocomplete.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#<%=txtSearch.ClientID%>").autocomplete("Handler/Search_CS.ashx", {
width: 200,
formatItem: function (data, i, n, value) {
return "<img style = 'width:50px;height:50px' src='PRupload/" +
value.split("-")[1] + "'/>" + value.split("-")[0];
},
formatResult: function (data, value) {
return value.split("-")[0];
}
});
});
</script>
<asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
I want to fire an event on the click or selection of an item from the autocomplete list.Can anyone please help me out with this?
You can always add code for select event in autocomplete:
i.e.
$( ".selector" ).autocomplete({
select: function( event, ui ) {}
});
Reference:
http://api.jqueryui.com/autocomplete/#event-select

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.

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