Character encoding issue in Java/JS with the 'é' character in a field - javascript

The database (Postgresql) has a table with a column called
streetaddress1 (varchar(50)) in which the entry is 'Amelié'
The UI (React/JS) :
var streetAddress1 = event.target[1].value;
if (valProductDescription && valModelNumber && valAssemblyNumber && valName) {
url = url + "&streetAddress=" + streetAddress1 + " " + streetAddress2;
<div>
<Modal
isOpen={openCfcOverlay}
style={customStyles}
contentLabel="modal"
<div>
<Input
errorMessage='Please enter a valid Street Address'
error={cfcDeclaration.companyAddress1Error}
title="Street Address"
type="text"
name="Street Address"
value={typeof selectedCompany == 'undefined' ? "" : selectedCompany.streetAddress1}
disabled='edit'
/>
Then in the index.template.html file, I tried both
<!DOCTYPE html>
<html lang="en">
<head>
<title>Home</title>
<meta charset="utf-8">
and
<!DOCTYPE html>
<html lang="en">
<head>
<title>Home</title>
<meta charset="utf-16">
In the back-end (JAVA):
public CompanyRequest(JSONObject jsonObject)
this.streetAddress1 = (String) jsonObject.get("streetAddress1");
this.streetAddress2 = (String) jsonObject.get("streetAddress2");
This 'Street Address' field will appear in a pop-up that allows a pdf download. In here, the name 'Amelié' will appear as
public void generatePdf(String filePath, List<CfcRequest> cfcRequestList, String companyName, String streetAddress) throws IOException {
Document document = new Document(PageSize.A4, 36, 36, 36, 72);
try {
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filePath));
document.open();
if (image != null) {
Image img = Image.getInstance(image, null);
img.setAbsolutePosition(36f, 775f);
img.scaleToFit(150, 40);
document.add(img);
}
String modifiedRegionAddress = "";
String country = "";
boolean zipcodeAdded = false;
String[] address = regionAddress.split(" ");
for (int i = 0; i < address.length; i ++) {
if (!zipcodeAdded) {
try {
Integer.parseInt(address[i]);
zipcodeAdded = true;
} catch(NumberFormatException e) {}
modifiedRegionAddress += address[i] + " ";
} else {
country += address[i] + " ";
}
}
Paragraph header = new Paragraph("PDF Download", headerFont);
header.setAlignment(Element.ALIGN_CENTER);
header.setSpacingAfter(20);
document.add(header);
// Date and additional stuff
DateFormat df = new SimpleDateFormat("MM/dd/yy");
Date dateobj = new Date();
PdfPTable basicInfoTable = new PdfPTable(new float[]{3, 2});
PdfPCell dateTitleCell = new PdfPCell(new Paragraph("Date Issued:", tableHeaderFont));
PdfPCell dateCell = new PdfPCell(new Paragraph(df.format(dateobj), titleFont));
PdfPCell authorizedCell = new PdfPCell(new Paragraph("Authorized Signature:", tableHeaderFont));
PdfPCell companyNameCell = new PdfPCell(new Paragraph(companyName, titleFont));
PdfPCell streetAddressCell = new PdfPCell(new Paragraph(streetAddress, titleFont));
PdfPCell regionAddressCell = new PdfPCell(new Paragraph(modifiedRegionAddress, titleFont));
PdfPCell countryAddressCell = new PdfPCell(new Paragraph(country, titleFont));
PdfPCell emptyCell = new PdfPCell();
emptyCell.setBorder(Rectangle.NO_BORDER);
dateTitleCell.setBorder(Rectangle.NO_BORDER);
dateCell.setBorder(Rectangle.NO_BORDER);
authorizedCell.setBorder(Rectangle.NO_BORDER);
companyNameCell.setBorder(Rectangle.NO_BORDER);
streetAddressCell.setBorder(Rectangle.NO_BORDER);
regionAddressCell.setBorder(Rectangle.NO_BORDER);
countryAddressCell.setBorder(Rectangle.NO_BORDER);
basicInfoTable.addCell(dateTitleCell);
basicInfoTable.addCell(authorizedCell);
basicInfoTable.addCell(dateCell);
basicInfoTable.addCell(emptyCell);
basicInfoTable.addCell(companyNameCell);
basicInfoTable.addCell(emptyCell);
basicInfoTable.addCell(streetAddressCell);
basicInfoTable.addCell(emptyCell);
basicInfoTable.addCell(regionAddressCell);
basicInfoTable.addCell(emptyCell);
basicInfoTable.addCell(countryAddressCell);
basicInfoTable.addCell(emptyCell);
document.add(bodyTop);
document.add(reachTable);
document.add(bodyBottom);
final int FIRST_ROW = 0;
final int LAST_ROW = -1;
//Table must have absolute width set.
if (basicInfoTable.getTotalWidth() == 0)
basicInfoTable.setTotalWidth((document.right() - document.left()) * basicInfoTable.getWidthPercentage() / 100f);
basicInfoTable.writeSelectedRows(FIRST_ROW, LAST_ROW, document.left(), document.bottom() + basicInfoTable.getTotalHeight(), writer.getDirectContent());
document.close();
writer.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Is this a utf-8/utf-16 problem? Why does the "é" character show up incorrectly in the field from the last picture? How do I fix this? and is it a back-end change or a UI change ?

The default encoding of the template databases in PostgreSQL is set to SQL_ASCII.Before retrieving that information did you change it to utf8 ?

Related

Download file from JSP with Javascript

The context: I have a JSP presenting an HTML page. Here I can choose files from a table (populated via MySQL). clicking on a row: the file is loaded from the DB (via MySQL query), then built via stream, then it should be downloaded. I'm able to build a file from a stream, but I can't enable the correct procedure for download it. The software is running on local, so there's no a client/server architecture (I'm aware Javascript is problematicfor this) I read many questions here about using Javascript, href links, jquery, but nothing seems to work.
Can someone provide a "classic example" or proper implementation for this? Sorry if my description is a little vague, I'll provide further details if necessary. Have a look to my jsp (Please ignore the code parts not related). Note: Some errors are due to uncoplete deleting of my efforts
`<%# page import="org.jdom2.Element"%>
<%# page
import="org.yawlfoundation.yawl.resourcing.rsInterface.WorkQueueGatewayClient"%>
<%# page import="org.jdom2.output.XMLOutputter"%>
<%# page import="org.jdom2.output.Format"%>
<%# page import="org.jdom2.input.SAXBuilder"%>
<%# page import="java.io.StringReader"%>
<%# page import="java.io.*"%>
<%# page import="java.sql.Connection"%>
<%# page import="java.sql.DriverManager"%>
<%# page import="java.sql.PreparedStatement"%>
<%# page import="java.sql.ResultSet"%>
<%# page import="java.sql.SQLException"%>
<%# page import="java.sql.Statement"%>
<%# page import="java.util.ArrayList"%>
<%# page import="java.util.List"%>
<%# page import="java.util.Map"%>
<%# page import="org.jdom2.Element"%>
<%# page import="org.yawlfoundation.yawl.elements.data.YParameter"%>
<%# page import="java.sql.*"%>
<%# page import="java.util.Enumeration"%>
<%
String username = "";
String password = "password";
String columns = "columns";
String data1 = "<tr>";
String taskFlag = "void";
String clickedDOC = "";
String link = "";
String jDocTitle = "dummy jDocTitle";
String varName = "username";
String varName2 = "addDocument";
String varName3 = "addRequest";
String varName4 = "evaluateRequest";
String varName5 = "removeDocument";
String varName6 = "removeRequest";
String varName7 = "exit";
String wqURL = "http://localhost:8080/resourceService/workqueuegateway";
String error = "error";
boolean isModified = false;
boolean addDocument = false;
String redirectURL = (String) session.getAttribute("redirectURL");
if (redirectURL == null) {
redirectURL = request.getParameter("source");
session.setAttribute("redirectURL", redirectURL);
}
String submit = request.getParameter("submit");
System.out.println("submit: " + submit);
WorkQueueGatewayClient wqClient = new WorkQueueGatewayClient(wqURL);
String itemXML = (String) session.getAttribute("itemXML");
//if (itemXML == null) {
String itemid = request.getParameter("workitem");
String handle = request.getParameter("handle");
itemXML = wqClient.getWorkItem(itemid, handle);
session.setAttribute("itemXML", itemXML);
session.setAttribute("workitem", itemid);
session.setAttribute("handle", handle);
//}
if ((submit != null) && submit.equals("Add Document")) { // VALUTARE SE IL TASK TERMINA E VA RIAVVIATO (A TERMINE ADD) O SE RIMANE
ATTIVO (E DISPONIBILE DOPO ADD)
System.out.println("AddDocument clicked");
taskFlag = "addDocument";
addDocument = true;
isModified = true;
System.out.println("isModified: " + isModified);
/* session.removeAttribute("itemXML");
session.removeAttribute("workitem");
session.removeAttribute("handle");
session.removeAttribute("redirectURL"); */
redirectURL += "?complete=true";
response.sendRedirect(response.encodeURL(redirectURL));
return;
}
Element wir = new SAXBuilder().build(new StringReader(itemXML)).getRootElement();
Element updatedData = wir.getChild("updateddata");
Element data = (updatedData.getContentSize() > 0) ? updatedData : wir.getChild("data");
Element wirData = data.getChildren().get(0);
System.out.println("itemXML: " + itemXML);
if (!wqClient.successful(itemXML)) {
error = itemXML;
System.out.println("incipit error itemXML: " + itemXML);
} else { // wqClient.successful(itemXML)
if (wir != null) { //NIENTE DA INSERIRE NELL' IF
if (wirData != null) {
Element usernameXML = wirData.getChild(varName);
//Element taskFlagXML = wirData.getChild("taskFlag");
Element addDocumentXML = wirData.getChild("addDocument");
//addDocumentXML.removeContent();
// System.out.println("addDocumentXML: " + addDocumentXML.getText());
/*Element addRequestXML = null;
Element evaluateRequestXML = null;
Element removeDocumentXML = null;
Element removeRequestXML = null;
Element exitXML = null; */
if (usernameXML != null) {
username = usernameXML.getText();
//addDocument.removeContent();
//taskFlagXML.setText(taskFlag);
addDocumentXML.setText("true");
itemid = (String) session.getAttribute("workitem");
handle = (String) session.getAttribute("handle");
String dataString = new XMLOutputter(Format.getCompactFormat()).outputString(wirData);
String result = wqClient.updateWorkItemData(itemid, dataString, handle);
System.out.println("itemXML2: " + itemXML);
if (wqClient.successful(result) && isModified) { // QUI OPZIONE COMPLETAMENTO VALIDO
System.out.println("isModified 3: " + isModified);
/* session.removeAttribute("itemXML");
session.removeAttribute("workitem");
session.removeAttribute("handle");
session.removeAttribute("redirectURL"); */
redirectURL += "?complete=true";
response.sendRedirect(response.encodeURL(redirectURL));
} else { // wqClient.successful(result))
error = result;
System.out.println("not wqClient.successful(result): " + error);
}
} else { //dataitem != null && dataitem2 != null
error = "dataitems null";
System.out.println(error);
System.out.println("itemXML: " + itemXML);
System.out.println("inputs: " + username + " , " + password);
System.out.println("wirdata: " + wirData);
}
} else {//wirData
error = "This workitem does not contain any data for updating.";
System.out.println(error);
}
} else {
System.out.println("inputs null: ");
}
}
System.out.println("SQL start");
String queryAllDocuments = "SELECT title, file FROM appuser, document WHERE appuser.username = '" + username
+ "' AND appuser.role = document.applicantRole";
String queryAllRequests = "SELECT * FROM request WHERE request.applicantUsername = '" + username +"'";
String queryPendingRequests = "SELECT * FROM request WHERE request.applicantUsername = '" + username
+ "' AND request.status = 'pending' ";
String queryAllEvaluatingRequests = "SELECT * FROM request WHERE request.evaluetorUsername = '" + username+"'";
String queryEvaluatingPendingRequests = "SELECT * FROM request WHERE request.evaluetorUsername = '"
+ username + "' AND request.status = 'pending' ";
String queryGetDoc = "SELECT file FROM document WHERE document.title =";
Class.forName("com.mysql.jdbc.Driver");
Connection connection1 = DriverManager
.getConnection("jdbc:mysql://localhost:3306/mydb?autoReconnect=true&useSSL=false",
"root", "root");
Statement statement1 = connection1.createStatement();
ResultSet resultSet1;
resultSet1 = statement1.executeQuery(queryAllDocuments);
System.out.println("resultSet1: "+resultSet1.first());
ResultSet resultSet2;
Statement statement2 = connection1.createStatement();
ResultSetMetaData rsmd;
rsmd = resultSet1.getMetaData();
System.out.println("rsmd: "+rsmd.getColumnCount());
int columnCount = rsmd.getColumnCount();
int index = 1;
int titleIndex = 1; // unica colonna doc
boolean flag = false;
while(flag){
jDocTitle = String.valueOf(request.getAttribute("docTitle")); // click su docTitle
if(jDocTitle.equals(null) ){
System.out.println("jDocTitle: "+jDocTitle);
queryGetDoc+= "'"+jDocTitle+"'";
resultSet2 = statement2.executeQuery(queryGetDoc);
System.out.println("resultSet2: "+resultSet2.first());
if(resultSet2!=null || !resultSet2.first()){
//resultSet2.first();
//costruisci file da query
System.out.println("jDocTitle1: "+jDocTitle);
File file = new File(jDocTitle);
file.createNewFile();
FileOutputStream fop = new FileOutputStream(file);
InputStream is = resultSet2.getBinaryStream(1);
byte[] buffer = new byte[1024];
int len;
for (int i = is.read(); i != -1; i = is.read()) {
fop.write(i);
}
is.close();
fop.close();
}
}else{
jDocTitle = "dummy docTitle";
System.out.println("docTitle null");
}
flag = false;
}
// <html xmlns="http://www.w3.org/1999/xhtml">
%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<script type="text/javascript">
function downloadFunction(){
var doc = document.getElementById("availableDocument").value;
doc = window.location= file;
alert(doc);
var xhttp = new XMLHttpRequest();
if(!doc){
doc = "no doc clicked";
}else
{
document.getElementById(doc).innerHTML = this.responseText;
xhttp.send();
}
flag = true;
}
</script>
<form name="userDataForm" method="post" action="" >
<h1>Welcome User</h1>
<h3> </h3>
<h3> </h3>
<h3>Available Documents</h3>
<table id= "docTable" style="height: 21px; float: left;" width="380">
<tbody>
<tr>
<%
for (int i = 1; i < columnCount; i++) {
System.out.println(rsmd.getColumnName(i));
%><td><b>
<%=rsmd.getColumnName(i)%>
</b></td>
<% }%>
</tr>
<%
int i = 1;
resultSet1.first();
while (!resultSet1.isAfterLast()) {
for (; i != columnCount; i++) {
%>
<tr id="<%resultSet1.getString(i);%>">
<td>
<a id="availableDocument" href="#"; onclick=downloadFunction('<%=resultSet1.getString(i)%>')><%=resultSet1.getString(i)%></a>
</td>
<% }
if ( i % columnCount == 0)out.println("</tr><tr>");%>
<%resultSet1.next();}%>
</tr>
</tbody>
</table>
<p> </p>
<p> </p>
<h3> </h3>
<h3>Submitted Requests</h3>
<table style="height: 21px; float: left;" width="380">
<tbody>
<tr>
<td> </td>
<td style="width: 20px;"> </td>
</tr>
</tbody>
</table>
<p> </p>
<h3> </h3>
<h3> </h3>
<h3>Received Requests</h3>
<table style="height: 21px; float: left;" width="380">
<tbody>
<tr>
<td> </td>
<td style="width: 20px;"> </td>
</tr>
</tbody>
</table>
<input type="submit" name="submit" value="Add Document" /> <input
type="submit" name="submit" value="Add Request" />
</form>
</body>
</html>`

compare the values of two text boxes and validate them in a session in asp.net

I code to generate captcha at page load. Here is the code.
protected void Page_Load(object sender, EventArgs e)
{
Bitmap objBMP = new System.Drawing.Bitmap(60, 20);
Graphics objGraphics = System.Drawing.Graphics.FromImage(objBMP);
objGraphics.Clear(Color.Green);
objGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
Font objFont = new Font("Arial", 10, FontStyle.Italic);
string randomStr = "";
int[] myIntArray = new int[5];
int x;
Random autoRand = new Random();
for (x = 0; x < 5; x++)
{
myIntArray[x] = System.Convert.ToInt32(autoRand.Next(0, 9));
randomStr += (myIntArray[x].ToString());
}
Session.Add("randomStr", randomStr);
objGraphics.RotateTransform(-7F);
objGraphics.DrawString(randomStr, objFont, Brushes.White, 3, 3);
Response.ContentType = "image/Gif";
objBMP.Save(Response.OutputStream, ImageFormat.Gif);
objFont.Dispose();
objGraphics.Dispose();
objBMP.Dispose();
}
Now I want to validate between inputed value and generated captcha. Just like as
if (Page.IsValid && (txtInput.Text.ToString() == Session["randomStr"].ToString()))
Here I have saved query.of user using four text boxes.
public static string SaveEnquiry(string name, string email, string contact, string comments, string Company, string items, string ip,string captcha)
{
string StrReturn = "";
try
{
UserContactUs objUserContactUs = new UserContactUs();
string userCmt = "User Comment:" + comments; ;
int result = objUserContactUs.insertContactUs(name, contact, email, userCmt, GetUser_IP());
if (result > 0)
{
string mesageRec = name + " has enquired for " + ". Contact : " + contact + ", Email: " + email+ ". His Cmt: " + comments ;
//SendSMSToAdmin(mesageRec);
//SendSMSToUser(contact.TrimStart('0'));
StrReturn = "1#Thanks, for your interest.We will get back to you soon";
}
else
{
StrReturn = "0#Your enquiry is not saved. Please try Again!";
}
}
catch (Exception ex)
{
StrReturn = "0#" + ex.Message;
}
return StrReturn;
}
Now I want is if both the fields(i.e captcha image and inputtext box) are not equal then refresh the captcha image by showing a message invalid captcha.
Here is my contact form.
<div class="col-sm-2">
<img height="50" id="EnquiryCaptcha" alt="" style="border:inset;" src="InsertEnquiry.aspx" width="130">
</div>
<div class="col-sm-15">
<input type="text" name="txtInput" id="txtInput" placeholder="Captcha*" style="margin-top:auto; border:groove;">
</div>
<!--end-->
<button class="border-button " data-animation="fadeInUp" data-animation-delay="1000" type="button" id="btnsubmit" onclick="InsertEnquiry('contactForm')" name="submit">Send Message</button>

How to interfere to the ASPxListBox both javascript and codebehind

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

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

problem in calling object.method.method, Javascript

//////////////////////////////////////////////////////////////////////////////
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
// 3 constructor functions of Person, Book, and Library
function Person(fname,lname)
{
this.firstName = fname;
this.lastName = lname;
}
function Book(booktitle,pages,price)
{
this.bookTitle = booktitle;
this.pages = pages;
this.price = price;
this.authors = new Array(arguments.length-3);
for(i=0;i<arguments.length-3;i++)
{
this.authors[i] = arguments[i+3];
}
}
function Library()
{
this.books = new Array(arguments.length);
for(i=0;i<arguments.length;i++)
{
this.books[i] = arguments[i];
}
this.totalPrice = function(){
var totalCost = 0;
for(i=0;i<this.books.length;i++)
{
totalCost += this.books[i].price;
}
return totalCost;
}
this.averagePrice = new Function("return this.totalPrice()/this.books.length");
var flag;
this.getBook = function(name){
for(i=0;i<this.books.length;i++)
{
if(this.books[i].bookTitle == name )
{
this.flag = i;
}
}
}
this.getAuthors = function(){
var toSay = "";
for(j=0;j<this.books[this.flag].authors.length;j++){
var authName =
this.books[this.flag].authors[j].lastName + " " +
this.books[this.flag].authors[j].firstName + "\t";
if(toSay.indexOf(authName)!=-1)
continue;
toSay+=""+authName;
}
return toSay;
}
}
var john = new Person("Smith", "John");
var jack = new Person("Simpson", "Jack");
var bobby = new Person("Franklin", "Bobby");
var albert = new Person("Camus", "Albert");
var java = new Book("Dummy Java", 1000, 29.95, john, jack);
var php = new Book("Dummy PHP", 300, 19.95, john);
var xml = new Book("Dummy XML", 150, 9.95, bobby, albert);
var js = new Book("Dummy JavaScript", 2000, 49.95, albert);
var lib = new Library(java, php, xml, js);
alert(lib.totalPrice()); // output 109.8
alert(lib.averagePrice()); // output 27.45
lib.getBook("Dummy XML");
alert(lib.getAuthors()); // output John Smith, Jack Simpson
</script>
</head>
<body>
</body>
</html>
/////////////////////////////////////////////////////////////////////
Instead of using the below two statements
lib.getBook("Dummy XML");
alert(lib.getAuthors()); // output John Smith, Jack Simpson
it works fine to produce the above output. but i want to produce the abouve output using nested methods.
i want to use a single statement alert(lib.getBook("Dummy XML").getAuthors()); to produce the same output ( // output John Smith, Jack Simpson)
Please help me on how to call a method in a method.
Thanks
It's called method chaining. Have the functions return this.
this.getBook = function(name){
for(i=0;i<this.books.length;i++) {
if(this.books[i].bookTitle == name ) {
this.flag = i;
}
}
return this;
}
then you can call another method on the return of lib.getBook("Dummy XML")....
You'll need to redefine the getBook() function to return a reference to 'lib' in order for your idea to work.

Categories

Resources