How to interfere to the ASPxListBox both javascript and codebehind - javascript

When I click the update button, aspxlistbox is filled by codebehind. When I print firm code to AspxTextbox4, the firm code of the firm name is displayed in the second aspxtextbox. In order to do that, I use the lostfocus event of AspxTextbox4.
However, aspxlistbox resets all data. This is an unexpected issue for me. How can I cope with that?
This is my Asp code.
<dx:ASPxTextBox ID="ASPxTextBox4" runat="server" Width="100%"
ClientInstanceName="textbox_firmcode" AutoPostBack="false" EnableClientSideAPI="true">
<ClientSideEvents LostFocus="getFirmName" />
</dx:ASPxTextBox>
<dx:ASPxButton ID="ASPxButton4" runat="server" Text="Add" Width="100%" AutoPostBack="False">
<ClientSideEvents Click="addListClick" />
</dx:ASPxButton>
<dx:ASPxListBox ID="ASPxListBox1" runat="server" Width="100%" ClientInstanceName="ASPxListBox1"> </dx:ASPxListBox>
This is the Javascript code below.
function getFirmName(s, e) {
devpopup.PerformCallback('firmtxt|' + s.GetText());
}
function addListClick(s, e) {
var firmcode = textbox_firmcode.GetText();
var firmname = textbox_firmname.GetText();
var st = 0;
for (var i = 0; i < ASPxListBox1.GetItemCount() ; i++) {
var item = ASPxListBox1.GetItem(i);
if (item.value.split(' ')[0] == firmcode) st = 1;
}
if (st == 0) {
ASPxListBox1.BeginUpdate();
ASPxListBox1.AddItem(firmcode + ' ' + firmname);
ASPxListBox1.EndUpdate();
listcount++;
}
return false;
}
The last one is the codebehind C#
protected void devpopup_WindowCallback(object source, PopupWindowCallbackArgs e)
{
string[] data = e.Parameter.Split('|');
if(data[0].Equals("firmtxt"))
{
ASPxPageControl page = (ASPxPageControl)((ASPxPopupControl)source).FindControl("ASPxPageControl1");
ASPxRoundPanel rpanel = (ASPxRoundPanel)page.FindControl("ASPxRoundPanel2");
ASPxTextBox txtbox = (ASPxTextBox)rpanel.FindControl("ASPxTextBox5");
ASPxRoundPanel otherpanel = (ASPxRoundPanel)page.FindControl("ASPxRoundPanel2");
ASPxListBox firmlistbox = (ASPxListBox)otherpanel.FindControl("ASPxListBox1");
SFADatabase db = new SFADatabase(Server);
string[] frmname = db.getData("SFA_FIRM", new string[] { "FRMNAME" }, "WHERE FRMCODE='" + data[1] + "'");
if (frmname.Length > 0)
{
txtbox.Text = frmname[0];
txtbox.Focus();
//txtbox.Enabled = false;
}
else
{
//txtbox.Enabled = true;
txtbox.Text = "";
txtbox.Focus();
}
}
}
public void putUpdateData(string parameter, object source)
{
// Load the firm name to the listbox with update button
columns = new string[] { "FRMCODE", "FRMNAME" };
data = db.getData(SFADatabase.TABLE_FIRM, columns, "WHERE UGRREF=" + group_id + "");
// firmlistbox.Items.Clear();
firmcodelist.Clear();
firmnamelist.Clear();
for (int i = 0; i < SFADatabase.row_count; i++)
{
ListEditItem item = new ListEditItem(data[i * 2] + " " + data[i * 2 + 1], data[i * 2]);
firmlistbox.Items.Insert(i, item);
firmcodelist.Add(data[i * 2]);
firmnamelist.Add(data[i * 2 + 1]);
}
}
I have attached a gif to be more clear.
enter image description here

Related

Remove certain text from text box on click

I have a TextBoxcontrol in my web form, where in I display Height & Width of certain product.
Now I display this as follows :
As you can see, I append a " to show inches, in the string in the following way :
txtH.Text = arrHW[i].ToString() + "\"";
Now, this causes problem while editing! As the user can never always be sure of correctly editing the field by editing the number only and not the " symbol.
I need someway either through JavaScript or C#, that removes the symbol " while the user clicks on the textbox and removes as the focus is changed.
I tried this method, but it doesn't seem to work!
protected void txtH_TextChanged(object sender, EventArgs e)
{
string height = txtH.Text;
char[] splitArr = { '"' };
string[] editH = height.Split(splitArr);
for (int i = 0; i < editH.Length; i++)
{
if (editH[i].ToString().Equals("\""))
{
editH[i].Remove(i);
}
}
}
This is the designer code for the textboxes :
<asp:PlaceHolder ID="plcHW" runat="server">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-arrows-v"></i> Height</span>
<asp:TextBox ID="txtH" runat="server" Width="60px" CssClass="form-control" OnTextChanged="txtH_TextChanged" />
<span class="input-group-addon"><i class="fa fa-arrows-h"></i> Width</span>
<asp:TextBox ID="txtW" runat="server" Width="60px" CssClass="form-control" />
</div>
</asp:PlaceHolder>
You can clear the text box as soon as the focus is on it then add" after the user adds the value to it! This is one way of doing it!
var prev="";
$('#HEIGHT').focus(function() {
prev=$(this).val();
$(this).val(prev.replace("\"", ""));
}).blur(function() {
if($(this).val()==""){
$(this).val(prev)
}
else{
$(this).val($(this).val()+"\"");
}
});
Without any jquery:
(function($el) {
"use strict";
$el.addEventListener("focus", adjust, true);
$el.addEventListener("blur", adjust, true);
function adjust($e) {
var e = $e.type;
if (e === "focus") $el.value = $el.value.replace(/\"/g, "");
if (e === "blur") $el.value = $el.value + '"';
}
})(document.getElementById("height"));
http://jsfiddle.net/dlizik/5cb7g8te/
You can do it as
$(document).ready(function(){
$("TextBoxId").focus(function(){
var tval = $(this).val();
$(this).val(tval.replace(/\"/g, ""));
});
$("TextBoxId").focusout(function(){
var tval = $(this).val();
$(this).val(tval.replace(/\"/g, "")+ '\"');
});
});
I have tried solving your issue with this Fiddle: http://jsfiddle.net/akd7r31a/1/
$(document).ready(function(){
$('#username').focus(function(){
var txtValue = $(this).val();
var charTest = txtValue.substr(txtValue.length - 1);
if(charTest == '"'){
var showString = txtValue.slice(0, -1);
$(this).val(showString);
}
});
$('#username').focusout(function(){
var txtValue = $(this).val();
var charTest = txtValue.substr(txtValue.length - 1);
if(charTest != '"'){
var newVal = $(this).val() + '"';
$(this).val(newVal);
}
});
});

JavaScript, get dynamically created label's id

The label that is beings created holds a guid that I need later. I need to grab that information after the list of labels are created. Here's my code:
<button onclick="getAllListings()">Get All Listings Information</button>
<br />
<div id="divDataInsert" name="divDataInsert">
#foreach (MVCTest1.Models.Listing foundListings in Model._listings)
{
string pk_listing_id = "listingsid_" + foundListings.PK_Listings_ID;
string addressPK = "address_" + foundListings.PK_Listings_ID;
string address = foundListings.Address.ToString();
string cityPK = "city_" + foundListings.PK_Listings_ID;
string city = foundListings.City.ToString();
string statePK = "state_" + foundListings.PK_Listings_ID;
string state = foundListings.State.ToString();
string zipcodePK = "zipcode_" + foundListings.PK_Listings_ID;
string zipcode = foundListings.ZipCode.ToString();
string fullAddress = address + ", " + city + " " + state;
if (foundListings.PK_Listings_ID != null)
{
<input type="text" id="lblListing_#pk_listing_id" value="#pk_listing_id" />
}
}
</div>
function getAllListings(){
//var listingArray = [document.getElementById("lblListing_")];
for (var i = 0; i < [document.getElementById("lblListing_")].length; i++) {
var listingString = document.getElementById("lblListing_").value;
var guid = listingString.split("_");
alert(guid[1]);
i++;
}
}
My code behind
public ActionResult Index()
{
string sql = "SELECT TOP 10 [PK_Listings_ID], [Address], [City], [State], [ZipCode] FROM dbo.Listings";
ListingCollection ListOfListings = new ListingCollection();
ListOfListings._listings = new List<Listing>();
using (SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["MVCInsertData"].ToString()))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = sql;
using(SqlDataReader reader = cmd.ExecuteReader())
{
if (reader != null)
{
while (reader.Read())
{
Listing listing = new Listing();
listing.PK_Listings_ID = Convert.ToInt32(reader["PK_Listings_ID"]);
listing.Address = reader["Address"].ToString();
listing.City = reader["City"].ToString();
listing.State = reader["State"].ToString();
listing.ZipCode = reader["ZipCode"].ToString();
ListOfListings._listings.Add(listing);
}
}
}
}
conn.Close();
}
return View(ListOfListings);
}
one of the answers involved adding a JS array in the code behind. How do you do that?
*****Update*****
I have changed my input to this:
<input type="text" class="lblListing_" value="#pk_listing_id" />
And I have adjusted my JS to this:
function getAllListings(){
var listingsArray = document.getElementsByClassName("lblListing_");
for (var i = 0; i < listingsArray.length; i++) {
var listingString = listingsArray.value;
var guid = listingString.split("_");
alert(guid[1]);
}
}
Keep in mind, my JS is NOT inside a document.ready(). Should it be?
One way would be to have your code behind emit a JavaScript array of all labels. A different--and this is the approach I would take--would be to use a class name as a "tag". Emit:
<input type="text" class="lblListing_" ...>
Then in your fixed (not dynamic) JavaScript, you can do:
function getAllListings(){
var listings = document.getElementsByClassName("lblListing_");
for (var i = 0; i < listings.length; i++) {
var listingString = listings[i].value;
var guid = listingString.split("_");
alert(guid[1]);
}
}
Update for the follow-on question:
The JavaScript can be placed anywhere but will not run on load. When and how to run the function depends on what you need it to do. (I assume the alert is just to test the logic.)
You can easily achieve that with jQuery
$('someSelector').each(function() {
// do something
});
$("input[id^='lblListing_']").each(function() {
console.log($(this).val().split("_")[1]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="lblListing_g-u-i-d-1" value="value1_g-u-i-d-1" />
<input type="text" id="lblListing_g-u-i-d-2" value="value2_g-u-i-d-2" />

How to use 'onKeyUp' attribute in asp.net?

Message 1: Validation (ASP.Net): Attribute 'onkeyup' is not a valid attribute of element 'TextBox'. E:\ABC\ABCD.aspx 83 66 ABCD
I want dropdown to change the Display list according to the value typed in TextBox.I have written the following query for it
var ddlText, ddlValue, ddl, lblMesg;
function CacheItems() {
ddlText = new Array();
ddlValue = new Array();
ddl = document.getElementById("=STCDropDownList.ClientID");
lblMesg = document.getElementById("=Label1.ClientID");
for (var i = 0; i < ddl.options.length; i++) {
ddlText[ddlText.length] = ddl.options[i].text;
ddlValue[ddlValue.length] = ddl.options[i].value;
}
}
window.onload = CacheItems;
function FilterItems(value) {
ddl.options.length = 0;
for (var i = 0; i < ddlText.length; i++) {
if (ddlText[i].toLowerCase().indexOf(value) != -1) {
AddItem(ddlText[i], ddlValue[i]);
}
}
lblMesg.innerHTML = ddl.options.length + " item(s) found.";
if (ddl.options.length == 0) {
AddItem("No item found.", "");
}
}
function AddItem(text, value) {
var opt = document.createElement("option");
opt.text = text;
opt.value = value;
ddl.options.add(opt);
}
The below following are Textbox and DropDownlist i am using.
<asp:TextBox ID="STCTextBox" runat="server" onkeyup="FilterItems(this.value)"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style3">Service Tax Code</td>
<td class="auto-style3">
<asp:DropDownList ID="STCDropDownList" runat="server" AutoPostBack="True" DataSourceID="STCSqlDataSource" DataTextField="ServiceTaxCode" DataValueField="ServiceTaxCode"></asp:DropDownList>
<asp:Label ID="Label1" runat="server" Text="Entered Comm Code Already Registered" Visible="False"></asp:Label>
Simple jQuery Function
.keyup()
Explore https://api.jquery.com/keyup/
From What i see
Replacing Function FilterItems with this can help
var txtBox=document.getElementById("=STCTextBox.ClientID");
txtBox.onkeyup=function() {
var value=txtBox.value;
ddl.options.length = 0;
for (var i = 0; i < ddlText.length; i++) {
if (ddlText[i].toLowerCase().indexOf(value) != -1) {
AddItem(ddlText[i], ddlValue[i]);
}
}
lblMesg.innerHTML = ddl.options.length + " item(s) found.";
if (ddl.options.length == 0) {
AddItem("No item found.", "");
}
}
Rather use jQuery:
$("#id").keyup(function(){<br/>
// Your Code <br/>
});

No value is present in hidden field after page load

In the below code i have coded in page load.In this i have store regular expressions in hidRegExp.Value. Now i have to store this value in the hidden field.Now in javascript i have to validate the user input in textbox.But when i enter a value it shows blank alert.But i want to display the regular expression in alert.Pls help me to do this.
code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (FieldTypeInfo == FieldType.TextBox)
{
TblSearch.Visible = false;
TblDate.Visible = false;
tblDropd.Visible = false;
TblChk.Visible = false;
lblText.Text = FieldLabel;
//txtreq.Enabled = this.IsMandatory;
string strRegularExp = string.Empty;
if (ListOfRegularExpression != null)
{
for (int iRow = 0; iRow < ListOfRegularExpression.Count; iRow++)
{
strRegularExp += ListOfRegularExpression[iRow].ToString() + "~~";
hidRegExp.Value = strRegularExp;
if (iRow == ListOfRegularExpression.Count - 1)
{
strRegularExp = strRegularExp.TrimEnd("~~".ToCharArray());
txtField.Attributes.Add("onblur", "javascript:ValidateRegExp('" + txtField.ToString() + "');");
}
}
}
hidRegExp.Value = strRegularExp;
lbl.Text = "The value of the HiddenField control is " + hidRegExp.Value + ".";
}}
code:
<script type="text/javascript">
function ValidateRegExp(txtInput) {
var hiddenValue = document.getElementById("<%=hidRegExp.ClientID%>").value;
alert("hiddenValue" + hiddenValue+".");
var mySplitResult = new Array();
mySplitResult = hiddenValue.split("~~");
for (i = 0; i < mySplitResult.length; i++) {
//document.write("<br /> Array[" + i + " ]= " + mySplitResult[i]);
var re = new RegExp(mySplitResult[i]);
if (txtInput.match(re)) {
alert("Successful match");
} else {
alert("No match");
}
}
}
</script>
<asp:HiddenField ID="hidRegExp" runat="server" EnableViewState= "true" >
</asp:HiddenField >
<asp:Label ID="lbl" runat="server"></asp:Label>
Initially ListOfRegularExpression will be null so control will not enter into if (ListOfRegularExpression != null) and HiddenField.Value wont be set.
I have had the problem before. Honestly, I don't remember how I resolved it, but I tried a few things. Here they are:
For displaying the hidden field, add ClientIdMode as static on your hidden field like
<asp:HiddenField ID="hidRegExp" runat="server" EnableViewState="true" ClientIDMode="Static"></asp:HiddenField>
and in the JavaScript, use:
document.getElementById("hidRegExp");
If this does not work, try your approach with these below:
1) Try moving your hidden field before the script.
2) Try making it a label and use that in the JavaScript.
Hope this helps.

How to access gridview cell value with javascript

I have a javascript function that I am trying to validate the inputs of a gridview. My problem is that I cannot get the value of the cell. Here is what I have:
function fcnCheck() {
var grid = document.getElementById("<%= GridViewProducts.ClientID %>");
var cellPivot;
if (grid.rows.length > 0) {
for (i = 1; i < grid.rows.length-1; i++) {
cellPivot = grid.rows[i].cells[0];
cellStatus = grid.rows[i].cells[1];
if (cellPivot == "Yes" and cellStatus == "") {
alert("You must select an answer for all columns if Pivot is yes")
return false;
}
}
}
}
This line does not work: cellPivot = grid.rows[i].cells[0];
Most likely you want (edit)
var theDropdown = grid.rows[i].cells[0].elements[0];
var selIndex = theDropdown.selectedIndex;
cellPivot = theDropdown.options[selIndex].value;
Another possibly easier or more reliable way to do this would be to tag the cells controls you want in some way and select them directly?
http://aspdotnetcodebook.blogspot.com/2010/01/how-to-get-cell-value-of-gridview-using.html#comment-form
Code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var list = "";
$("#btnGet").click(function() {
$("#<%=GridView1.ClientID %> tr").each(function() {
//Skip first(header) row
if (!this.rowIndex) return;
var age = $(this).find("td:last").html();
list += age + "</br>";
});
$("#listAge").html(list)
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
<input type="button" id="btnGet" value="Get Cell Value" />
<div id="listAge">
</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;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Create Object of person class
Person personObject = new Person();
//Assign Person list to GridView
GridView1.DataSource = personObject.GetPersonList();
//Call Bindmethod of GridView
GridView1.DataBind();
}
}
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public List<Person> GetPersonList()
{
//Retrun List of Person
List<Person> list = new List<Person>()
{
new Person{ID=1,Name="Person1",Age=32},
new Person{ID=2,Name="Person2",Age=45},
new Person{ID=3,Name="Person3",Age=43},
new Person{ID=4,Name="Person4",Age=21},
new Person{ID=5,Name="Person5",Age=76},
new Person{ID=6,Name="Person6",Age=54},
};
return list;
}
}
<script language="javascript" type="text/javascript">
function Calculate()
<br/>
{
<br/>
var grid = document.getElementById("<%=GridID.ClientID%>");
<br/>
var sum = 0; <br/>
for (var i = 1; i < grid.rows.length; i++)<br/>
{ <br/>
var Cell = grid.rows[i].getElementsByTagName("input");
<br/>if (!Cell[4].value) {sum += 0; } else { sum += parseFloat(Cell[4].value);} }
<br/>
document.getElementById("<%=TextBox1.ClientID%>").value = sum;
}
<br/>
</script>
------------------------------------------------------------------------
<asp:TemplateField HeaderText="Current payment" >
<ItemTemplate>
<asp:TextBox ID="cridnvalue" runat="server" Width="70px" BorderStyle="None" onkeyup="CalculateTax();" ></asp:TextBox>
</ItemTemplate>
<ItemStyle Width="120px" />
</asp:TemplateField>
//your gridview id in my case my gridview is named dgd and the id comes from
// ClientID
var myGrid = document.getElementById("<%= dgd.ClientID %>");
var oRows = myGrid.rows;
var k;
for (k = 1; k < oRows.length; k++)
{
var currentRow = myGrid.rows[k];
//now you can see the 1st,2nd and 3trd column value
alert(currentRow.cells[1].innerHTML);
alert(currentRow.cells[2].innerHTML);
alert(currentRow.cells[3].innerHTML);
}
function rowWisegetcellvalueingridview() {
///concat string
var str1 = "";
var n = document.getElementById('hdnColumn').value;
///concat string
var grid = document.getElementById('GridView1');
var Inputs = grid.getElementsByTagName('input');
var Inputsa = grid.getElementsByTagName('a');
var Inputsspan = grid.getElementsByTagName('span');
var Input = Inputs.length;
var j = 0;
var p = 0;
var r = 0;
for (t = 0; t < grid.rows.length - 1; t++) {
var HdnID1 = Inputs[j].value;
var HdnID2 = Inputs[j + 1].value;
var HdnID3 = Inputs[j + 2].value;
var HdnID4 = Inputs[j + 3].value;
var HdnID5 = Inputsa[p].innerHTML;
var HdnID6 = Inputsa[p + 1].innerHTML;
var HdnID7 = Inputsspan[r].innerHTML;
var varConcat = "(" + HdnID1 + "," + HdnID2 + "," + HdnID3 + "," + HdnID4 + "," + HdnID5 + "," + HdnID6 + "," + HdnID7 + "),\n";
n = n.concat(varConcat);
j = j + 4;
p = p + 2;
r = r + 1;
}
return false;
}

Categories

Resources