I have use autocompleteextender for textbox autocomplete. I have written addition js for suggestion & value selection. Problem is after type ing some letter if I move my cursor from top to bottom then it doesn't select value where cursor is pointed. It selects value above cursor position. This problem only when cursor moves from top to bottom. Works fine when move bottom to top.
In following snapshot you can see where my cursor position & it highlighting value above.
<asp:TextBox ID="clientCode" runat="server" CssClass="field-pitch" ClientIDMode="Static"></asp:TextBox>
<asp:AutoCompleteExtender ServiceMethod="SearchClientCode"
ServicePath="~/auto.aspx" MinimumPrefixLength="1" CompletionInterval="100"
EnableCaching="false" CompletionSetCount="10" TargetControlID="clientCode"
ID="clientCodeExtender" runat="server" FirstRowSelected="false"
CompletionListCssClass="completionList" CompletionListItemCssClass="listItem"
CompletionListHighlightedItemCssClass="itemHighlighted"
OnClientPopulated="onClientPopulated" OnClientItemSelected="itemSelected"
BehaviorID="AutoCompleteEx"></asp:AutoCompleteExtender>
<script type="text/javascript">
function itemSelected(ev) {
var index = $find("AutoCompleteEx")._selectIndex;
if (index != -1) {
$find("AutoCompleteEx").get_element().value = $find("AutoCompleteEx").get_completionList().childNodes[index]._value;
}
else {
$find("AutoCompleteEx").get_element().value = '';
}
}
function onClientPopulated(sender, e) {
var List = $find("AutoCompleteEx").get_completionList();
for (i = 0; i < List.childNodes.length; i++) {
var _value = JSON.parse(List.childNodes[i]._value);
var abbr = _value[0];
var fullform = _value[1];
List.childNodes[i]._value = abbr;
List.childNodes[i].innerHTML = "<span>" + abbr + "(" + fullform + ")</span>"
}
}
</script>
code behind
[System.Web.Script.Services.ScriptMethod(), System.Web.Services.WebMethod()]
public static List<string> SearchClientCode(string prefixText, int count)
{
MySqlConnection conn = new MySqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings("conio").ConnectionString;
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "SELECT clientID, clientName FROM clientsDetails where (clientID like #SearchText)";
cmd.Parameters.AddWithValue("#SearchText", prefixText + Convert.ToString("%"));
cmd.Connection = conn;
conn.Open();
List<string> customers = new List<string>();
MySqlDataReader sdr = cmd.ExecuteReader;
JavaScriptSerializer serializer = new JavaScriptSerializer();
while (sdr.Read) {
object[] item = new object[] {
sdr("clientID").ToString(),
sdr("clientName").ToString()
};
customers.Add(serializer.Serialize(item));
}
conn.Close();
return customers;
}
You should use the given parameters of the OnClientItemSelected method:
function itemSelected(source, eventArgs) {
$find("AutoCompleteEx").get_element().value = eventArgs.get_value();
}
Related
I want to highlight a particular word and do a hover from gridview. My problem is if the word is repeated in the page the word is highlighted but other same words are disappearing form the text. Image for before and after highlight is attached. I have attached image of missing words before and after highlighting. Please help.
Page1.aspx
protected void GridView3_SelectedIndexChanged(object sender, EventArgs e)
{
Session["Pa"] = GridView3.SelectedRow.Cells[4].Text;
Session["paId"] = GridView3.SelectedRow.Cells[1].Text;
string sValue = ((HiddenField)GridView3.SelectedRow.FindControl("HiddenField1")).Value;
Session["panode"] = sValue;
Session["patt"] = GridView3.SelectedRow.Cells[5].Text.ToString().Trim('\n');
Response.Redirect("selectipc.aspx");
}
page2.aspx
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function () {
var searchWord = $("#hfWord").val();
var iframeHtml = $("#hfHTML").val();
var index = iframeHtml.indexOf(searchWord);
if (index >= 0) {
iframeHtml = iframeHtml.substring(0, index) + "<span id='lblHighlight' style='background-color: yellow;'>"
+ iframeHtml.substring(index, index + searchWord.length) + "</span>" + iframeHtml.substring(index + searchWord.length);
}
$('#frmDisplay').contents().find('body').html(iframeHtml);
if ($('#frmDisplay').contents().find('#lblHighlight').length > 0) {
$('#frmDisplay').contents().find('#lblHighlight')[0].scrollIntoView()
}
});
</script>
protected void Page_Load(object sender, EventArgs e)
{
//Session.Add("Logintype", Session["new"].ToString());
if (!this.IsPostBack)
{
if (Session["paId"] != null)
{
hfWord.Value = Session["pa"].ToString();
getPa();
//Session.Contents.Remove(Session["Pa"].ToString());
}
}
}
public void getPa()
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connString"].ConnectionString);
string panode = Session["panode"].ToString();
string pstext = Session["pa"].ToString();
string patext = Session["patt"].ToString();
string vc = (Convert.ToInt32(HttpContext.Current.Session["VCN"])).ToString();
SqlCommand cmd = new SqlCommand("select bn.vcFilePath from tblBookNodes bn inner join tbl_Pannotation pa on bn.iModuleId=pa.iNodeId where bn.iModuleId='" + panode + "' ", conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
bytesp = (byte[])dr["vcFilePath"];
conn.Close();
}
getpa();
}
public void getpa()
{
string panId = Session["paId"].ToString();
string pstext = Session["pa"].ToString();
string patext = Session["patt"].ToString();
string fileName = panId.Replace(" ", "_") + ".htm";
//string returnpath = "File/htmlFile/";
string strPath = Server.MapPath("~/htmlFile/");
//if (Directory.Exists(strPath))
//{
// Directory.Delete(strPath, true);
//}
if (!Directory.Exists(strPath))
{
Directory.CreateDirectory(strPath);
}
//string pth = strPath;
string path = strPath + fileName;
var doc = new HtmlDocument();
string html = Encoding.UTF8.GetString(bytesp);
doc.LoadHtml(html);
StringWriter sw = new StringWriter();
var hw = new HtmlTextWriter(sw);
StreamWriter sWriter = new StreamWriter(path);
sWriter.Write(sw.ToString());
doc.Save(sWriter);
sWriter.Close();
//string fileContents = html;
string searchText = HttpUtility.HtmlEncode(pstext);
string newBookmarktag = "<style>font.tip {border - bottom: 1px dashed;text - decoration: none}font.tip:hover {cursor: help;position: sticky}font.tip span {display: none}font.tip:hover span {background-color:F0E6BC;text-align:center;color:Black;font-weight:bold;border: #c0c0c0 1px dotted;padding: 5px 20px 5px 5px;display: block;z - index: 1000;left: 0px;margin: 10px;position: absolute;top: 10px;text - decoration: none}</style><font style=background-color:yellow class=tip><a name=" + pstext + ">" + "<span>" + patext + "</span></a></font>";
// pstext = newBookmarktag;
html = html.Replace(searchText, newBookmarktag);
//hfHTML.Value = html;
System.IO.File.WriteAllText(path, html);
hfHTML.Value = File.ReadAllText(path);
//HiddenField1.Value = html;
Page page = (Page)HttpContext.Current.Handler;
MultiView control = ((IETM.select)(page)).MultiView1;
View View1 = (View)control.FindControl("View1");
HtmlControl ctrl = (HtmlControl)View1.FindControl("frmDisplay");
frmDisplay.Attributes.Add("src", HttpContext.Current.Request.Url + "/.." + "\\htmlFile\\" + fileName);
MultiView1.SetActiveView(View1);
}
indexOf return only first value position
better use split in this case
$(function () {
var searchWord = $("#hfWord").val();
var iframeHtml = $("#hfHTML").val();
iframeHtml = iframeHtml.split(searchWord).join("<span style='background-color: yellow;' class='lbl-highlight'>"+searchWord+"</span>");
$('#frmDisplay').contents().find('body').html(iframeHtml);
if ($('#frmDisplay').contents().find('.lbl-highlight').length > 0) {
$('#frmDisplay').contents().find('.lbl-highlight')[0].scrollIntoView()
}
});
1- I have a form in a jsp page created dynamically on select option with JavaScript. The form has three empty select boxes.
2- I have a servlet to redirect the jsp page view
3- I have a database table containing data to fill the three select boxes
question : is it possible to fill the three select boxes one after one on select event, with only one servlet, and asynchronously.
the servlet code :
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Connection conn = MyUtils.getStoredConnection(request);
String cursusc = request.getParameter("cursusc");
/*PrintWriter pr =response.getWriter();
response.setContentType("text/xml");*/
if(cursusc=="look") {
String errorString = null;
List<Cursus> list = null;
try {
list = DButils.listetab(conn);
System.out.println("code: ");
} catch (SQLException e) {
e.printStackTrace();
errorString = e.getMessage();
}
request.setAttribute("errorString", errorString);
request.setAttribute("etab", list);
response.getWriter().append(" "+list);
}
RequestDispatcher dispatcher =
this.getServletContext().getRequestDispatcher("/WEB-
INF/views/client/cursus_info.jsp");
dispatcher.forward(request, response);
}
the jsp first select code :
<select name="etab" id="etab" onchange="lmdf()">
<c:forEach items="${ETAB}" var="etablissement" >
<option>${etablissement.etablissement}</option>
</c:forEach>
</select></td>
and the first sql request
public static List listetab(Connection conn) throws SQLException {
String sql = "SELECT a.ETABLISSEMENT\r\n" +
"FROM CURSUS a";
PreparedStatement pstm = conn.prepareStatement(sql);
ResultSet rs = pstm.executeQuery();
List<Cursus> list = new ArrayList<Cursus>();
while (rs.next()) {
String etab = rs.getString("ETABLISSEMENT");
Cursus cursus = new Cursus();
cursus.setEtablissement(etab);
list.add(cursus);
}
return list;
}
the js dynamique select create
function cursuschoice(){
var selectBox = document.getElementById("choice");
var val= selectBox.value;
var origin1 = document.getElementById("td2");
var origin2 = document.getElementById("td3");
var origin3 = document.getElementById("td4");
var origin4 = document.getElementById("td5");
var origin11 = document.getElementById("rtd2");
var origin22 = document.getElementById("rtd3");
var origin33 = document.getElementById("rtd4");
var origin44 = document.getElementById("rtd5");
var myNode1 = document.getElementById("td2");
while (myNode1.firstChild) {
myNode1.removeChild(myNode1.firstChild);
}
var myNode2 = document.getElementById("td3");
while (myNode2.firstChild) {
myNode2.removeChild(myNode2.firstChild);
}
var myNode3 = document.getElementById("td4");
while (myNode3.firstChild) {
myNode3.removeChild(myNode3.firstChild);
}
var myNode4 = document.getElementById("td5");
while (myNode4.firstChild) {
myNode4.removeChild(myNode4.firstChild);
}
var myNode11 = document.getElementById("rtd2");
while (myNode11.firstChild) {
myNode11.removeChild(myNode11.firstChild);
}
var myNode22 = document.getElementById("rtd3");
while (myNode22.firstChild) {
myNode22.removeChild(myNode22.firstChild);
}
var myNode33 = document.getElementById("rtd4");
while (myNode33.firstChild) {
myNode33.removeChild(myNode33.firstChild);
}
var myNode44 = document.getElementById("rtd5");
while (myNode44.firstChild) {
myNode44.removeChild(myNode44.firstChild);
}
var s1 = document.createElement("span");
s1.setAttribute('id',"firsttd");
var s2 = document.createElement("span");
s2.setAttribute('id',"secondtd");
var s3 = document.createElement("span");
s3.setAttribute('id',"thirdtd");
var s4 = document.createElement("span");
s4.setAttribute('id',"fourthtd");
var s11 = document.createElement("select");
s11.setAttribute('name',"firstrtd");
var s33 = document.createElement("input");
s33.setAttribute('name',"thirdrtd");
var s44 = document.createElement("input");
s44.setAttribute('name',"fourthrtd");
if (val=="L"){
var t1= document.createTextNode("first");
var t2= document.createTextNode("second");
var t3= document.createTextNode("third");
var t4= document.createTextNode("fourth");
var s111 = document.createElement("select");
s111.setAttribute('name',"first1rtd");
origin11.appendChild(s111);
var s22 = document.createElement("input");
s22.setAttribute('name',"secondrtd");
}
else {
var t1= document.createTextNode("first +");
var t2= document.createTextNode("second +");
var t3= document.createTextNode("third +");
var t4= document.createTextNode("fourth +");
var s22 = document.createElement("select");
s22.setAttribute('name',"secondrtd");
}
s1.appendChild(t1);
s2.appendChild(t2);
s3.appendChild(t3);
s4.appendChild(t4);
origin1.appendChild(s1);
origin2.appendChild(s2);
origin3.appendChild(s3);
origin4.appendChild(s4);
origin11.appendChild(s11);
origin22.appendChild(s22);
origin33.appendChild(s33);
origin44.appendChild(s44);
}
this is my programmatically button, there is the error null pointer exception in logcat.
This is my way to loop the button.But the disable button for the button cannot function.When i click on "save" button the programmatically button will disable. is it my way to disable button is incorrect?
String CountQuery = "SELECT * FROM Category";
db = new DBController(getActivity());
SQLiteDatabase db2 = db.getReadableDatabase();
Cursor cursor1 = db2.rawQuery(CountQuery, null);
{
int num = cursor1.getCount();
Button[] valueB = new Button[num];
for (int i = 1; i < num; i++) {
String SelectQuery = "SELECT * FROM Category where CategoryID='" + i + "'";
db = new DBController(getActivity());
SQLiteDatabase db1 = db.getReadableDatabase();
Cursor cursor = db1.rawQuery(SelectQuery, null);
if (cursor.moveToNext()) {
String categoryName = cursor.getString(1);
String coordinateX = cursor.getString(2);
String coordinateY = cursor.getString(3);
valueB[i] = new Button(getActivity());
valueB[i].setText("" + categoryName);
valueB[i].setId(i);
valueB[i].setOnTouchListener(this);
params = new RelativeLayout.LayoutParams(300, 100);
params.leftMargin = Integer.parseInt(coordinateX);
params.topMargin = Integer.parseInt(coordinateY);
final int finalI = i;
valueB[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "asdasd" + finalI, Toast.LENGTH_SHORT).show();
viewPager = (ViewPager) getActivity().findViewById(R.id.pager);
viewPager.setCurrentItem(finalI);
}
});
mRrootLayout.addView(valueB[i],params);
}
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (i[0] = 1; i[0] < num; i[0]++) {
valueB[i[0]].setOnTouchListener(null);
}
}
});
}
}
You can disable the onclick listener by using valueB[i].setOnClickListener(null);
you can disable the button by using setClickable method.
valueB[i].setClickable(false);
or you can user setEnabled method also like
valueB[i].setEnabled(false);
I'm trying to have a hide and show button
Whenever i click on the button, it works but also refreshes the page at the same time. I'm not sure what is causing the refresh. This is on aspx:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#buttontest").click(function () {
$("#hello").toggle();
});
});</script>
<button id="buttontest">test</button>
<div id="hello">hello</div>
Not sure if its the aspx.cs is causing the refreshing:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection myConnect = new SqlConnection(_connStr);
acct = new Account();
acct = (Account)Session["Account"];
if (!IsPostBack)
{
LoadCart();
DataBind();
string strCommandText = "SELECT * From Customer where Cust_Id = #Cust_Id";
SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
cmd.Parameters.AddWithValue("#Cust_Id", 1);
//open connection and retrieve data by calling ExecuteReader
myConnect.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Lbl_FName.Text = dr["First_Name"].ToString();
Lbl_LName.Text = dr["Last_Name"].ToString();
Lbl_CNo.Text = dr["Contact_No"].ToString();
string addr1 = dr["Address"].ToString();
string addr2 = dr["Address2"].ToString();
address = new List<string>();
address.Add(dr["Address"].ToString() + " " + "Singapore " + dr["Postal_Code"].ToString());
address.Add(dr["Address2"].ToString() + " " + "Singapore " + dr["Postal_Code"].ToString());
//Ddl_Address.Text = dr["Address"].ToString() + " " + "Singapore " + dr["Postal_Code"].ToString();
//Ddl_Address.Text = dr["Address2"].ToString() + " " + "Singapore " + dr["Postal_Code"].ToString();
ddl_Addr.DataSource = address;
ddl_Addr.DataBind();
}
dr.Dispose();
dr.Close();
myConnect.Close();
//page load box retrieve
SqlConnection myConnect2 = new SqlConnection(_connStr);
string strCommandText2 = "SELECT * From Card_Details where Card_Id = #Card_Id";
myConnect2.Open();
SqlCommand cmd2 = new SqlCommand(strCommandText2, myConnect2);
cmd2.Parameters.AddWithValue("#Card_Id", 1);
////open connection and retrieve data by calling ExecuteReader
SqlDataReader dr2 = cmd2.ExecuteReader();
if (dr2.Read())
{
CNo1 = dr2["Card_Number"].ToString();
CNo2 = dr2["Card_Number2"].ToString();
Session["CardNo1"] = CNo1;
Session["CardNo2"] = CNo2;
CNo = new List<string>();
CNo.Add(CNo1);
CNo.Add(CNo2);
ddl_CNo.DataSource = CNo;
ddl_CNo.DataBind();
//display when first run
Lbl_CardName.Text = dr2["Name_On_Card"].ToString();
Lbl_CardType.Text = dr2["Card_Type"].ToString();
Lbl_EDate.Text = dr2["Expired_Date"].ToString();
dr2.Dispose();
dr2.Close();
myConnect2.Close();
}
}
}
protected void ddl_CNo_SelectedIndexChanged(object sender, EventArgs e)
{
string cardNum1 = Session["CardNo1"].ToString();
string cardNum2 = Session["CardNo2"].ToString();
if (ddl_CNo.SelectedIndex == 0)
{
SqlConnection myConnect2 = new SqlConnection(_connStr);
string strCommandText2 = "SELECT Name_On_Card, Card_Type, Expired_Date From Card_Details where Card_Number = #Card_Number";
myConnect2.Open();
SqlCommand cmd2 = new SqlCommand(strCommandText2, myConnect2);
cmd2.Parameters.AddWithValue("#Card_Number", cardNum1);
SqlDataReader dr2 = cmd2.ExecuteReader();
if (dr2.Read())
{
Lbl_CardName.Text = dr2["Name_On_Card"].ToString();
Lbl_CardType.Text = dr2["Card_Type"].ToString();
Lbl_EDate.Text = dr2["Expired_Date"].ToString();
}
dr2.Dispose();
dr2.Close();
// DataBind();
myConnect2.Close();
}
else if (ddl_CNo.SelectedIndex == 1)
{
SqlConnection myConnect3 = new SqlConnection(_connStr);
string strCommandText3 = "SELECT Name_On_Card2, Card_Type2, Expired_Date2 From Card_Details where Card_Number2 = #Card_Number2";
myConnect3.Open();
SqlCommand cmd3 = new SqlCommand(strCommandText3, myConnect3);
cmd3.Parameters.AddWithValue("#Card_Number2", cardNum2);
SqlDataReader dr3 = cmd3.ExecuteReader();
if (dr3.Read())
{
Lbl_CardName.Text = dr3["Name_On_Card2"].ToString();
Lbl_CardType.Text = dr3["Card_Type2"].ToString();
Lbl_EDate.Text = dr3["Expired_Date2"].ToString();
}
dr3.Dispose();
dr3.Close();
// DataBind();
myConnect3.Close();
}
}
protected void LoadCart()
{
gv_CartView.DataSource = ShoppingCart.Instance.Items;
gv_CartView.DataBind();
decimal total = 0.0m;
foreach (ShoppingCartItem item in ShoppingCart.Instance.Items)
{
total = total + item.TotalPrice;
}
decimal a = 2.0m;
decimal totalP = a + total;
Lbl_Subtotal.Text = total.ToString("C");
Lbl_TotalPrice.Text = totalP.ToString("C");
}
I'm still unfamiliar with all these, any help would be appreciated
EDIT: I've edited the button and javascript, it still caused a refresh
this looks like you might have button type as submit other wise this is not possible to happen
please make sure you added button as button not as submit button
Also please try to avoid
$("button").click(function () {
used specific button id
$("#btn_toggle").click(function () {
And you can also do.. in case if your button type is submit but you need to do return false.
$("#btn_toggle").click(function () {
$("#hello").toggle();
return false;
});
but make sure this will stop submit your from at server.
Replace server button with html button. i.e.
Replace
<asp:Button />
With
<input type="button" />
OR
do this:
$("button").click(function () {
$("#hello").toggle();
return false;
});
Try this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("button").click(function () {
$("#hello").toggle();
});
});</script>
<button>hello</button>
<div id="hello">hello</div>
I am working in ASP.NET project. And my task is to append the Checkbox text to the TextBox. Checkboxes's text are bound from Database values in CheckBoxList.
protected void prbtn_Click(object sender, EventArgs e)
{
string ConnectionString = "Data Source=.;Initial Catalog=nci;Integrated Security=true";
SqlConnection myConn = new SqlConnection(ConnectionString);
List<string> minire = new List<string>();
string sql = "SELECT distinct PRIMARY_MINI_REGION FROM customers";
myConn.Open();
SqlCommand cmd = new SqlCommand(sql, myConn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
minire.Add(dt.Rows[0][0].ToString());
group12.DataSource = dt;
group12.DataTextField = "PRIMARY_MINI_REGION";
group12.DataValueField = "PRIMARY_MINI_REGION";
group12.DataBind();
string[] grpary = prgrp.Text.Split(';');
foreach (var items in grpary)
{
if (items != "")
{
li.Add(items.ToString());
if (li.Contains(items.ToString()))
{
group12.Items.FindByText(items.ToString()).Selected = true;
//group12.Items.FindByText(items.ToString()).Enabled = false;
}
}
}
}
Can any of you please help me how to do it in jquery.Currently i appended text using stringbuilder using C# as like
protected void group_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (ListItem l in group12.Items)
{
if (l.Selected)
{
li.Add(l.Text);
}
}
foreach (var i in li)
{
si.Append(i.ToString() + ";");
}
//if (prgrp.Text == "")
// prgrp.Text = si.ToString();
//else
prgrp.Text = si.ToString();
}
once i select checkbox means it have to append text.and once i unchecked it means,content have to be deleted from textbox
I guess this snippet helps you out:
$(function() {
$('input[type="checkbox"]').change(function() {
// Reset output:
$("#output").html('');
// Repeat for all checked checkboxes:
$('input[type="checkbox"]:checked').each(function(){
// Get values:
var existingText = $("#output").html();
var textToAppend = $(this).val();
// Append seperator (';') if neccessary:
if(existingText != '')
{
existingText = existingText + ";";
}
// Print out append value:
$("#output").html(existingText + textToAppend);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Select:</h2>
<input type="checkbox" value="Jan"/>Jan
<input type="checkbox" value="Feb"/>Feb
<input type="checkbox" value="Mar"/>Mar
<input type="checkbox" value="Apr"/>Apr
<h2>Output:</h2>
<div id="output"></div>
$(document).ready(
$('.checkBoxCommunClass').on('click', function () {
var id = $(this).get(0).id;
if ($('input[id=' + id + ']:checked').length > 0)
$('#resultTextInput').val() = $('#resultTextInput').val() + $(this).val();
}));