I want to have an autocompletition which would look like the one in the image, with blue background and x-s for deletion of the chosen items.
In the example, I wrote 'j' and two users with j in their names are listed in the dropdown. What is the best way to accomplish this?
Here is the jquery plugin that you are looking for
click here to learn more..
I recommend you to use jQuery UI. You have an autocomplete widget and you can customize the CSS as you wish. For selecting multiple items you can use tagsinput plugin.
Here is a sample code for tagsinput:
$('#emails').tagsInput({
width: 'auto', defaultText: 'Add email', isEmail: true
});
You need to use ajax and may be jquery ui autocomplete widget for this:
Since you are using asp.net, you can first create something like a handler in your application.
Sample Handler
<%# WebHandler Language="C#" Class="SimpleHandler" %>
using System;
using System.Web;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Net;
using System.Text;
using System.IO;
public class SimpleHandler : IHttpHandler {
UCA.Common.DataControl.DBUtility dbu = new UCA.Common.DataControl.MsSqlDbUtility();
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
if (context.Request.QueryString["query"] != null)
{
context.Response.Write("You asked for "+ context.Request.QueryString["query"]);
return;
}
public bool IsReusable {
get {
return false;
}
}
}
The in your html page, use this as a base,
<html>
<body>
<form>
<input type="text" id="txtSearch"/>
<input type="button" id="btnSubmit" onclick="getDetails(document.getElementById("txtSearch").value)" value="Submit"/>
</form>
<br>
<div id="txtResult"><b>Person info will be listed here.</b></div>
<script type="text/javascript">
function getDetails(keyword)
{
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
document.getElementById("txtResult").innerHTML=xmlhttp.responseText;
}
xmlhttp.open("GET","simplehandler.ashx?query="+keyword,true);
xmlhttp.send();
}
</script>
</body>
</html>
Related
I am facing a problem passing string to HTML page through javascript.
I have a window form,
A HTML file, where I have my Javascript and HTML code.
In the function in C# page, I have a string that I need to send to the HTML page through javascript. But I can not pass it. Please advise me.
Thanks
My C# method code below
private void Form1_Load(object sender, EventArgs e)
{
Assembly assembly = Assembly.GetExecutingAssembly();
StreamReader reader = new StreamReader(assembly.GetManifestResourceStream("ProjectName.Maps.html"));
webBrowser1.DocumentText = reader.ReadToEnd();
***//pass getDefaultMap() value (str) to the javascript in Maps.html page.***
}
private string getDefaultMap()
{
string str;
str = (#"Exec SP_Map_Display #Opt=1");
return str ;
}
My HTML page is below
<body>
<script>
$(document).ready(function () {
$("#btnSubmit").click(function () {
***// Get the data from C# code str***
}
</script>
<input type="button" name="btnSubmit" value="Submit" />
<div id="dvMap">
</div>
</body>
Assuming this is WinForms since there's a WebBrowser control, to call C# code from the HTML page JavaScript can be accomplished with this minimum example:
Simple HTML page added to the root of the project and Properties was setup to Copy to Output Directory: Copy if newer this will ensure there's a simple page for testing:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>WebForms WebBrowser Control Client</title>
</head>
<body>
<input type="button" onclick="getLocations()" value="Call C#" />
<script type="text/javascript">
function getLocations() {
var locations = window.external.SendLocations();
alert(locations);
}
</script>
</body>
</html>
The JS function getLocations will call C# method SendLocations, the important parts are the Form1 class annotations and setting webBrowser1.ObjectForScripting = this :
using System.Windows.Forms;
using System.Security.Permissions;
using System.IO;
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.ObjectForScripting = this;
var path = Path.GetFullPath("Client.html");
var uri = new Uri(path);
webBrowser1.Navigate(uri);
}
public string SendLocations()
{
return "SF, LA, NY";
}
}
Clicking the HTML button Call C# will show a popup with the return value from C# method
I am trying to use a c# variable to remove an attribute.
I am testing my approach before actually coding application.
I've tried javascript and jQuery but found nothing that would allow to
substitute TextBox ID with value of string in codebehind.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="WebApplication2.index" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="myText" runat="server" required="required"></asp:TextBox>
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication2
{
public partial class index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string straspID = "myText";
bool fieldRequired = false;
if (fieldRequired == false)
{
//FindControl("myText");
FindControl(straspID);
if (straspID != null)
//
myText.Attributes.Remove("required");
// I want to use straspID instead of the ID of the asp page
// which will returned from a table - I'm simulating here
// I get an error if I use straspID for remove attribute
}
}
}
}
My expected result is to remove the attribute for selected ID.
I am currently getting a syntax error.
This
FindControl(straspID);
is not doing what you think it is.
Can you check your index.aspx.designer.cs file and see if there is a protected member variable called 'myText' ?
If there is, you can simply do this: -
if (fieldRequired == false)
{
myText.Attributes.Remove("required");
}
If there is no protected member called myText, add one at class level to 'index': -
namespace WebApplication2
{
public partial class index : System.Web.UI.Page
{
protected Textbox myText;
(etc)
As long as you declare it of the correct type and with the same name and casing, there is no need to resort to FindControl to access a server control.
private void loadform(List providerList)
{
foreach (ProviderInRequest req in providerList)
{
// taget div for plan
Control ctrl = FindControl("div" + req.aspName);
// set visible to true if we found it.
if (ctrl != null)
{
//set div to visible
ctrl.Visible = true;
// set label to proper text
Label lbl = (Label)Page.FindControl("lbl" + req.aspName);
lbl.Text = displayName;
Good day,
Been new to web development (i use ASP.NET) and i had this goal of passing/returning a value to display on HTML element such such as input. I had done searching and trying most of the solutions i found but none work, the output still returns an empty value on the HTML input. why is that? my code i'm working on can be seen below:
javacript:
function confirmExistence(entityValue) {
var entity = "Staff";
var result = "";
if (entityValue === '0') {
entity = "Student";
}
if (confirm(entity + " w/ same name is already registered. is this a different " + entity + "?")) {
result = "Yes";
} else {
result = "No";
}
alert(result);
document.getElementById('<%= fieldFirstNameStudent.ClientID %>').value = result;
}
html:
<asp:button class="by-button" id="btnStudentEnc" runat="server" text="Encode" OnClick="btnStudentEnc_Click" />
<asp:textbox type="text" class="mfield" placeholder="First Name" id="fieldFirstNameStudent" runat="server" />
asp c#:
protected void btnStudentEnc_Click(object sender, EventArgs e)
{ **some sql database condition here to run the clientscript below**
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"studentConfirmExistence", "confirmExistence('0');", true); }
Result is as follows on this image:
UPDATE: IF ABOVE IS TOO COMPLICATED. i created a new web form having simple block of codes that still doesn't work
Aspx:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="LobbyStudents.aspx.cs" Inherits="LobbyStudents" %>
<asp:Content ID="Content0" ContentPlaceHolderID="title" Runat="Server">
LobbyStudents
</asp:Content>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<script>
function confirmExistence(entityValue) {
alert(entityValue);
document.getElementById("<%= fieldFirstNameStudent %>").value = "whatswrong?";
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<asp:textbox placeholder="First Name" id="fieldFirstNameStudent" runat="server"/>
<asp:button runat="server" text="Encode" OnClick="btnStudentEnc_Click"></asp:button>
</asp:Content>
Aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class LobbyStudents : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnStudentEnc_Click(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"studentConfirmExistence", "confirmExistence('0');", true);
}
}
ClientScript works and even does the alert box. Still textbox is still empty and doesn't contain "whatswrong?" value
unlike i try it on this one:
<!DOCTYPE html>
<html>
<body>
Name: <input type="text" id="myText" value="tch">
<p>Click the button to change the value of the text field.</p>
<button onclick="confirmExistence('0')">Try it</button>
<script>
function confirmExistence(entityValue) {
alert(entityValue);
document.getElementById("myText").value = "whatswrong?";
}
</script>
</body>
</html>
where it works.
What's the difference between the two and why it doesn't happen on asp controls
ok, figure out what is the issue for your first example, is not related to the position, but
change your
document.getElementById("<%= fieldFirstNameStudent %>").value = "whatswrong?";
to
document.getElementById("<%= fieldFirstNameStudent.ClientID %>").value = "whatswrong?";
this will generated in html as
document.getElementById("System.Web.UI.WebControls.TextBox").value = "whatswrong?";
which the js not able to find the control name as System.Web.UI.WebControls.TextBox
if assign with .ClientID, it will generate the correct id
document.getElementById("MainContent_fieldFirstNameStudent").value = "whatswrong?";
I am working on a group project, and am trying to figure out ASP.net (hardly anyone in my group knows it, including me). My job is to make some text box and button such that, when the button is clicked, the text in the text box is processed and posted iff it has <= 140 characters.
I tried to write some jQuery that checks the text in the text box, and then sends it to the server for processing. The server is to save it to database, and post it to page, if it is no more than 140 characters long (this will be checked again).
Unfortunately, I run into this error. I tried to contact my team members, but they are super busy with other issues. Here is my code:
Feed.aspx:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Feed.aspx.cs" Inherits="Feed_Feed" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<!-- This is here for test purpose -->
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(
function()
{
$('#TweetButton').click(
function()
{
// get the text from the TweetBox
var status = $('#TweetBox').val();
// if it is 140 characters or less
if (status.length <= 140)
{
var data = JSON.stringify(status);
// send to the server page
$.ajax({
url: '/Feed.aspx.cs',
type: 'POST',
dataType: 'json',
data: data,
success: function(myStatus)
{
$('#MyStatus').html(myStatus);
}
});
}
else
{
alert("Tweet should contain no more than 140 characters");
}
});
});
</script>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
<h1>User Feed</h1>
<p>
<input id="TweetBox" type="text" /><input id="TweetButton" type="button" value="button" />
</p>
<div id="MyStatus"></div>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="LeftContent" Runat="Server">
</asp:Content>
Feed.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Feed_Feed : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
The C# file is practically empty because I don't know how to handle the data being posted to the page (should it be in Page_Load?) I don't know what to do here...
The code is not going to post data to the asp.net server because you are just using regular HTML elements. In order to convert an html element to asp.net element, you need to use attribute runat="server", so your markup would become :
<input id="TweetBox" type="text" runat="server" /><input id="TweetButton" type="button" value="button" runat="server" />
Alternately, to make the job simpler and have more flexibility on the asp.net controls ( like accessing additional properties ), you should strictly use asp.net core controls. So your new markup would look like :
<asp:TextBox id="TweetBox" runat="server"></asp:TextBox>
<asp:Button id="TweetButton" runat="server"></asp:Button>
In order to trigger a click event to post data onto the server ( codebehind ), you need to add the attributes OnClick to your button.
<asp:Button id="TweetButton" runat="server" OnClick="TweetButton_Click"></asp:Button>
In the codebehind (*.aspx.cs), you need to handle the event triggered by the button and check for the length of the text.
public partial class Feed_Feed : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void TweetButton_Click(object sender, EventArgs e)
{
if(TweetBox.Text.Length <= 140)
{
// Save data in the database.
}
}
}
UPDATE :
To work with ajax, you would need asp.net controls, so your markup would be
.ASPX =>
<input id="TweetBox" type="text" />
<input id="TweetButton" type="button" value="button" />
<script>
$().ready(function()
{
$('#TweetButton').click(function(){
// if it is 140 characters or less
if (status.length <= 140)
{
// send to the server page
$.ajax({
url: '/Feed.aspx/SubmitTweet',
type: 'POST',
dataType: 'json',
data: "{'tweet':'" + $('#TweetBox').val() + "'}",
success: function(myStatus)
{
$('#MyStatus').html(myStatus.d);
},
error : function(er)
{
}
});
}
else
{
alert("Tweet should contain no more than 140 characters");
}
});
});
</script>
.ASPX.CS ( code-behind ) =>
[WebMethod]
public static string SubmitTweet(string tweet)
{
// dummy function :
return DataSubmit(tweet) ? "Data Was submitted" : "Error while submitting data";
}
public bool DataSubmit(string data)
{
//call db connection and save the tweet
// if successful , return true else false
}
I know you cant save javascript variables into server side variables (vbscript) directly, but is there a way around this like saving java script variables into html hidden inputs then using javascript to post. Is this possible? If not what else can i do? Below is my code so far get the value of a drop down list - javascript
function selectedDatabase() {
select_temp = form1.elements["selection"];
select_index = select_temp.selectedIndex;
select_text = select_temp.options[select_index].text;
}
Below is the HTML code
<center><select id="selection" onchange="selectedDatabase()">
<option>Movies</option>
<option>Movies 2</option>
<option>New Movies</option>
<option>New Movies 2</option>
</select></center>
</td></tr>
What you're looking for is called ajax. You can do it manually, or better use a JavaScript library such as MooTools, jQuery, or Prototype.
Check out Google University's Ajax tutorial. I would avoid w3schools' tutorials.
Just to cover all the bases, why can't you just have the user submit the form?
Also, you could do this with cookies, though you won't get the cookie values on the server until the next GET or POST from the user.
It is Possible to store javascript variable values into server side variable. All you have to do is to implement "System.Web.UI.ICallbackEventHandler" class.
Below is the code demonstrating how to do it.
In aspx Page:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Client Calback Example</title>
<script type="text/ecmascript">
function LookUpStock()
{
var lb=document.getElementById("tbxPassword");
var product=lb.value;
CallServer(product,"");
}
function ReceiveServerData(rValue){
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="password" id="tbxPassword" />
<input type="Button" onclick="LookUpStock">Submit</button>
</div>
</form>
</body>
**
In Code Behind (CS) Page
**
public partial class _Default : System.Web.UI.Page,System.Web.UI.ICallbackEventHandler
{
protected String returnValue;
protected void Page_Load(object sender, EventArgs e)
{
String cbReference = Page.ClientScript.GetCallbackEventReference
(this,"arg", "ReceiveServerData", "context");
String callbackScript;
callbackScript = "function CallServer(arg, context)" +
"{ " + cbReference + ";}";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
"CallServer", callbackScript, true);
}
public void RaiseCallbackEvent(String eventArgument)
{
if(eventArgument == null)
{
returnValue = "-1";
}
else
{
returnValue = eventArgument;
}
}
public String GetCallbackResult()
{
return returnValue;
}
}
Now you can get the JavaScript variable "product" value into Server side variable "returnValue".