Change the value of input textbox with eyeball - javascript

I have 2 properties created, one with a masked value and the other with a raw value for my web page. Currently when I submit the form I have the masked value to display with the eyeball slash. When I click on the eyeball I want the raw value to be displayed and masked again when clicked. None of the research online explains this, they only focus on passwords which I do not need.
index.cshtml.cs
// Properties
public ResidencyCheckResult CheckResult { get; set; }
public string OutputSSN { get => CheckResult.SSNumber; set => CheckResult.SSNumber = value; }
public string OutputSSNMasked { get; set; }
// Constructors(Parameters)
public IndexModel(Assess50Context context)
{
_context = context;
CheckResult = new ResidencyCheckResult();
}
// Methods(Parameters)
public async Task<IActionResult> OnPostSubmit()
{
using HttpClient client = new HttpClient();
ResidencyCheckClient checkClient = new ResidencyCheckClient();
await checkClient.OpenAsync();
ResidencyCheckCriteria checkCriteria = new ResidencyCheckCriteria()
{
};
ResidencyCheckResult checkResult = await checkClient.ValidateFloridaResidencyAsync(checkCriteria);
OutputSSN = checkResult.SSNumber;
OutputSSNMasked = OutputSSN;
OutputSSN = $"{SubstringCheck(OutputSSN, 3)}-{SubstringCheck(OutputSSN, 3, 2)}-{SubstringCheck(OutputSSN, 5, 4)}";
OutputSSNMasked = $"{SubstringCheck(OutputSSNMasked, 3)}-{SubstringCheck(OutputSSNMasked, 3, 2)}-{SubstringCheck(OutputSSNMasked.Replace(OutputSSNMasked, "XXXX"), 5, 4)}";
await checkClient.CloseAsync();
return Page();
}
// methods to prevent causing argument out of range exceptions on substring calls
public string SubstringCheck(string s, int length)
{
int len = s.Length;
if (len > length)
{
len = length;
}
return s.Substring(0, len);
}
public string SubstringCheck(string s, int b, int length)
{
int len = s.Length;
if (len <= b)
{
return s;
}
len -= b; // b < len
if (len > length)
{
len = length;
}
return s.Substring(b, len);
}
index.cshtml
<form class="mt-0" method="post">
<button class="btn btn-outline-dark col-1 offset-5" type="submit" id="SubmitBtn" name="SubmitBtn" value="Submit" disabled asp-page-handler="Submit">Submit</button>
<input class="form-control" title="Social security number" readonly asp-for="OutputSSNMasked">
<i class="fa fa-eye-slash" id="ToggleOutputSSN" style="cursor: pointer;"></i>
</form>
#section Scripts {
<script>
const toggleOutputSSN = document.querySelector('#ToggleOutputSSN');
const outputSSNMasked = document.querySelector('#OutputSSN');
toggleOutputSSN.addEventListener('click', function (e) {
const type = outputSSNMasked.getAttribute('type') === 'text' ? 'password' : 'text';
outputSSNMasked.setAttribute('type', type);
this.classList.toggle('fa-eye');
});
});
</script>

Try something like this.
const toggleOutputSSN = document.querySelector('#ToggleOutputSSN');
const outputSSNMasked = document.querySelector('#OutputSSNMasked');
toggleOutputSSN.addEventListener('click', function(e) {
const parts = outputSSNMasked.dataset.ssn.split('-');
if(!outputSSNMasked.value.endsWith('XXXX')) {
parts[2] = 'XXXX';
}
outputSSNMasked.value = parts.join('-');
const iTag = this.querySelector('i');
iTag.classList.toggle('fa-eye');
});
.masked-input {
margin: 20px;
width: 200px !important;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" />
<div class="input-group masked-input">
<input type="text"
id="OutputSSNMasked"
class="form-control"
title="Social security number"
aria-label="Social security number"
data-ssn="115-67-0707"
value="115-67-0707">
<span id="ToggleOutputSSN" class="input-group-text" style="cursor: pointer;">
<i class="far fa-eye-slash"></i>
</span>
</div>

Related

MVC: Razor: Bind SelectList's SelectedValue to textbox

I have a model and a View with a select and a few text boxes. I am trying to bind the textbox values to the selected list item the following way:
Model:
public class Items
{
public string ID { get; set; }
public string Name { get; set; }
public SelectList ItemList { get; set; }
public List<SelectListData> MiscList { get; set; }
}
public class SelectListData{
public string ID { get; set; }
public string Name { get; set; }
public string Address{get; set;}
public string City{get; set;}
public string State{get; set;}
}
Controller:
Controller:
public async public async Task<IActionResult> Index()
{
Items viewModel = new Items();
List<SelectListData> tempLIst = new List<SelectListData>();
tempLIst.Add(new SelectListData() { ID = "1", Name = "ID-1", Address="123 AVE", City = "New City", State = "CA"});
tempLIst.Add(new SelectListData() { ID = "2", Name = "ID-2", Address="234 AVE", City = "New City", State = "CA"});
tempLIst.Add(new SelectListData() { ID = "3", Name = "ID-3", Address="345 AVE", City = "New City", State = "CA"});
tempLIst.Add(new SelectListData() { ID = "4", Name = "ID-4", Address="456 AVE", City = "New City", State = "CA"});
viewModel.ItemList = new SelectList(tempLIst, "ID", "Name", 2);
viewModel.SelectListData = tempLIst;
return View(viewModel);
}
View:
#Model Items
<div class="form-group">
<label class="col-lg-2 control-label">Account</label>
<div class="col-lg-10">
<div class="input-group col-lg-10">
<span class="input-group-addon">
<i class="fa fa-globe" aria-hidden="true"></i>
</span>
<select asp-for="ID" asp-items="#Model.ItemList" class="form-control" onchange="OnSelectedIndexChanged_01(this)"></select>
</div>
#{
if(Model.ID != null) {
var selectedAddress = Model.MiscList.SingleOrDefault(c => c.ID == Model.ID).Address;
}
}
<div>
<input id="selAddress" value="#selectedAddress" /> =====? how do I set the value to selectedAddress here?
</div>
</div>
</div>
<script>
function OnSelectedIndexChanged_01(value, jsdata) {
var selectedID = value.options[value.selectedIndex].value;
var selectedText = value.options[value.selectedIndex].text;
var myArray = [];
var jsdata = #Json.Serialize(#Model.MiscList.ToList()); ===? this is being assigned correctly
//myArray = JSON.parse(jsdata); ===> this line throws "Unexpected token o in JSON at position 1"; commenting this worked out
//myArray = jsdata;
console.log("[" + selectedID + "] [" + jsdata + "] [" + myArray + "]"); ===> this line is printing [[object, object], [object, object], [object, object]]
//console.log("[" + selectedID + "] [" + jsdata + "]");
for (var i = 0; i < myArray.length; i++) {
if (myArray[i].ID == selectedID) {
var Address = document.getElementById("selAddress");
Address.value = "";
Address.value = myArray[i].Address.toString();
break;
}
}
}
</script>
I am trying to bind the selectedValue of the dropdown to a selected Address. Any help is appreciated.
Edit:
As ScareCrow indicated, I am able to bind the initial values.
ANother question: my javascript doesn't seem to populate the address text based on the OnChange event of the dropdownlist. I am not sure if I am passing the model's arraylist properly. Any pointers is helpful.
Thanks
NH
Please try the following code Snippet in view: made changes in your code
#model Items;
#{var selectedAddress=string.Empty;}
<div class="form-group">
<label class="col-lg-2 control-label">Account</label>
<div class="col-lg-10">
<div class="input-group col-lg-10">
<span class="input-group-addon">
<i class="fa fa-globe" aria-hidden="true"></i>
</span>
<select asp-for="ID" asp-items="#Model.ItemList" class="form-control"></select>
</div>
#{
if(Model.ItemList != null) {
selectedAddress = Model.MiscList.SingleOrDefault(c => c.ID == Model.ItemList.SelectedValue.ToString()).Address;
}
}
<div>
<input id="selAddress" value="#selectedAddress" />
</div>
</div>
</div>
I believe the selected items you set in
if(Model.ItemList != null) {
selectedAddress = Model.MiscList.SingleOrDefault(c => c.ID == Model.ItemList.SelectedValue.ToString()).Address;
}
rather than Model.ID in your code.
Dropdown change event can be achieved by the following Javascript code snippet:
$(document).ready(function () {
$('#ID').change(function () {
var selectedValue = $(this).val();
var misclist = #Json.Serialize(#Model.MiscList.ToList());
for(i=0;i<misclist.length;i++){
if(misclist[i].id == selectedValue) {
$('#selAddress').val(misclist[i].address);
break;
}
}
});
});
There were 2 issues with my question. #ScareCrow provided a solution to my first issue and helped me in figuring out the solution to my second issue. Here's an updated javascript function(with the key values being lower-case):
function OnSelectedIndexChanged_01(value, jsdata) {
var selectedID = value.options[value.selectedIndex].value;
var selectedText = value.options[value.selectedIndex].text;
var myArray = [];
var jsdata = #Json.Serialize(#Model.MiscList.ToList());
//myArray = JSON.parse(jsdata); ===> this line throws "Unexpected token o in JSON at position 1"; commenting this worked out; jsdata is already a javascript object
myArray = jsdata;
for (var i = 0; i < myArray.length; i++) {
if (myArray[i].id == selectedID) {
var Address = document.getElementById("selAddress");
Address.value = "";
Address.value = myArray[i].address.toString();
break;
}
}
}

Passing checkbox value to array in Angular

I'm working on a solution where each of the inputs, generated depending on the passenger number, gets additional checkboxes. I want to pass the value of each checkbox and bind it to the input next to it. The plan is to eventually end up with an array in which I have the value of the input field + each checkbox value. I am not sure how to move forward with this. For now, I have:
COMPONENT.HTML:
<li *ngFor="let passenger of createRange(showStorage.passengersNumber); let i=index"><input type="text" [(ngModel)]="passengersData[i]" placeholder="Name and surname">
<input type="checkbox" (click)="addChild($event)">Child
<input type="checkbox" (click)="addLuggage($event)">Luggage
</li>
COMPONENT.TS
constructor() {
this.passengersData = [];
}
public passengersData: any[];
public luggageCounter: number = 0;
public childrenCounter: number = 0;
createRange(number){
var items: number[] = [];
for(var i = 1; i <= number; i++){
items.push(i);
}
return items;
}
addLuggage(event) {
console.log("Added luggage");
this.luggageCounter++
}
addChild(event) {
this.childrenCounter++
console.log(event);
}
Thanks for any help!
STACKBLITZ: https://stackblitz.com/edit/flight-date-picker-with-service-done-qfmn6p
Use an array with a name property and boolean properties for child and luggage and regenerate the array only when the number of passengers is updated retaining the previous passengers.
Here is a working StackBlitz https://stackblitz.com/edit/angular-ivy-s7dtu4?file=src%2Fapp%2Fapp.component.ts
Number of passengers <input type="text" [ngModel]="passengers.length" (ngModelChange)="updateNumOfPassengers($event)">
<li *ngFor="let passenger of passengers; let i=index">
<input type="text" [name]="'name_' + 1" [(ngModel)]="passenger.name" placeholder="Name and surname">
<input type="checkbox" [checked]="passenger.child" (change)="passenger.child = !passenger.child">Child
<input type="checkbox" [checked]="passenger.luggage" (change)="passenger.luggage = ! passenger.luggage">Luggage
</li>
passengers = [];
updateNumOfPassengers(input: string) {
const numOfPassengers = parseInt(input);
if (!isNaN(numOfPassengers) && numOfPassengers >= 0) {
const passengersToAdd = numOfPassengers - this.passengers.length;
if (passengersToAdd > 0) {
this.passengers = [...this.passengers, ...Array.from({ length: passengersToAdd }, _ => ({ name: '', child: false, luggage: false }))];
} else if (passengersToAdd < 0) {
this.passengers = this.passengers.filter((_, index) => index < numOfPassengers);
}
}
}

How can I call c# method from Jquery Ajax in WebForm?

I am new to the coding and i am trying to call my c# method through jquery ajax because my form action is not allowing my OnClick() event to run, I cannot remove form action because, my form comes from proprietary software and gives form action automatically every time, i tried to change it to default again but that doesn't work. So now I am trying to run my C# code through Jquery Ajax. If you have better way to solve it please suggest.
Your help is appreciated, Thank You in advance
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="HTMLtoPDF.aspx.cs"
Inherits="HTMLtoPDF.HTMLtoPDF" %>
<!DOCTYPE html>
<!--[if IE 9]><html class="lt-ie10" lang="en" > <![endif]-->
<html class="no-js" lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=9" />
<title>Incomplete Grade Application</title>
</head>
<body>
<form action="xyz.aspx" id="form1" runat="server" method="post" name="form1">
/// Web Form ///
<div class="row">
<div class="col-sm-12">
<label class="control-label" style="margin-top:0px;margin-left:20px">Please use your mouse/finger sign below:</label>
<div id="esignature"></div>
<input type="hidden" id="bitmap" name="bitmap" value="" />
</div>
</div>
<div class="row">
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
<button type="button" class="btn btn-danger btn-xs" id="clear">Clear Signature</button>
</div>
<div class="col-lg-2 col-lg-offset-6 col-md-2 col-md-offset-6 col-sm-2 col-sm-offset-6 col-xs-2 col-xs-offset-6">
<div class="pull-right">
<input type="submit" class="btn btn-danger" id="reject-button" name="button" value="Reject" />
</div>
</div>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
<input type="button" ID="submit" class="btn btn-success" value="Approve" />
<button id="hiddenButton" runat="server" onserverclick="btnClick_Click" style="display:none;" ></button>
</div>
</div>
<hr style="background-color:#750D17;height:1px" />
<div class="row">
<div class="col-lg-12">
<input type="text1" class="form-control" id="reject-reason" name="reject-reason">
<p class="help-block">Reject Reasons (if rejected)</p>
</div>
</div>
</div>
</div>
<br />
<br />
</form>
<script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script>
<script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script>
<script src="https://code.jquery.com/jquery-migrate-1.3.0.js"></script>
<script src="https://workflow.stratford.edu/Content/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<!--[if lt IE 9]>
<script src='https://workflow.stratford.edu/Content/jSignature/flashcanvas.js' type='text/javascript'></script>
<![endif]-->
<script src='https://workflow.stratford.edu/Content/jSignature/jSignature.min.js'></script>
<script type="text/javascript">
var isEmpty = function (element) {
if ($("#" + element).val() == "" || $("#" + element).val() == null) {
return true;
} else {
return false;
}
};
var arrayCheck = function (array) {
for (var i = 0; i < array.length; i++) {
if (array[i] == false) {
return false;
}
};
return true;
};
function arrayAssign(array, num) {
for (var i = 0; i < num; i++) {
array[i] = false;
};
return array;
};
function validationCheck(array, number, element) {
if (isEmpty(element)) {
$("#" + element).parent(".form-group").addClass("has-error");
array[number] = false;
} else {
$("#" + element).parent(".form-group").removeClass("has-error");
array[number] = true;
}
};
var pass1 = [];
$(document).ready(function () {
if ($.browser.msie) {
if (parseInt($.browser.version) < "9.0") {
alert("Sorry! This form does not support your current IE version, please use Firefox/Google Chrome to submit.");
}
}
var preSig = $('#stu-sig-bit').val();
$('#stu-sig').attr('src', preSig);
var fakeVari = $("#typea").val();
$("#esignature").jSignature({
"background-color": "transparent",
"decor-color": "transparent",
"color": "#1489FF",
});
$("#clear").click(function () {
$("#esignature").jSignature("reset");
});
$("input[type=text]").attr("readonly", true);
$("textarea1").attr("readonly", true);
//$("input[type=radio]").attr("disabled", "disabled");
$("#reject-reason").attr("readonly", false);
$("#submit").click(function () {
$("#bitmap").val($("#esignature").jSignature("getData"));
arrayAssign(pass1, 2);
pass1[2] = false;
validationCheck(pass1, 0, "remaining_work");
validationCheck(pass1, 1, "deadline_date");
pass1[2] = true;
if (!arrayCheck(pass1)) {
return false;
}
else if ($("#esignature").jSignature("getData", "native").length == 0) {
alert("Please sign at bottom of the form.");
return false;
} else {
$("#iso_sig").val($("#bitmap").val());
$("#iso_decision").val("no");
var date = new Date();
var month = date.getMonth() + 1;
var day = date.getDate();
var temp = (month < 10 ? "0" : "") + month + "/" + (day < 10 ? "0" : "") + day + "/" + date.getFullYear();
$("#iso_date").val(temp);
var answer = confirm('Are you sure you want to approve the case?');
if (answer == true) {
document.getElementById('<%= hiddenButton.ClientID %>').click();
} else {
return false;
}
}
});
$("#reject-button").click(function () {
$("#bitmap").val($("#esignature").jSignature("getData"));
if (isEmpty("reject-reason")) {
alert("Please write down the reason why you reject the request.");
return false;
} else if ($("#esignature").jSignature("getData", "native").length == 0) {
alert("Please sign at bottom of the form.");
return false;
} else {
$("#iso_sig").val($("#bitmap").val());
$("#iso_decision").val("no");
var date = new Date();
var month = date.getMonth() + 1;
var day = date.getDate();
var temp = (month < 10 ? "0" : "") + month + "/" + (day < 10 ? "0" : "") + day + "/" + date.getFullYear();
$("#iso_date").val(temp);
var answer = confirm('Are you sure you want to reject the case?');
if (answer == true) {
} else {
return false;
}
}
});
});
</script>
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnClick_Click(object sender, EventArgs e)
{
DownloadAsPDF();
}
public void DownloadAsPDF()
{
try
{
string strHtml = string.Empty;
string pdfFileName = Request.PhysicalApplicationPath + "\\files\\" + "CASEID6.pdf";
//string testPath = Server.MapPath("~/files/test.pdf");
string template = File.ReadAllText(Server.MapPath("~/Incomplete-Pdf-temp.html"));
CreatePDFFromHTMLFile(template, pdfFileName);
Response.Redirect("SendEmail.aspx");
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
public void CreatePDFFromHTMLFile(string HtmlStream, string FileName)
{
try
{
object TargetFile = FileName;
string ModifiedFileName = string.Empty;
string FinalFileName = string.Empty;
GeneratePDF.HtmlToPdfBuilder builder = new GeneratePDF.HtmlToPdfBuilder(iTextSharp.text.PageSize.A4);
GeneratePDF.HtmlPdfPage first = builder.AddPage();
first.AppendHtml(HtmlStream);
byte[] file = builder.RenderPdf();
File.WriteAllBytes(TargetFile.ToString(), file);
iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(TargetFile.ToString());
ModifiedFileName = TargetFile.ToString();
ModifiedFileName = ModifiedFileName.Insert(ModifiedFileName.Length - 4, "1");
iTextSharp.text.pdf.PdfEncryptor.Encrypt(reader, new FileStream(ModifiedFileName, FileMode.Append), iTextSharp.text.pdf.PdfWriter.STRENGTH128BITS, "", "", iTextSharp.text.pdf.PdfWriter.AllowPrinting);
reader.Close();
if (File.Exists(TargetFile.ToString()))
File.Delete(TargetFile.ToString());
FinalFileName = ModifiedFileName.Remove(ModifiedFileName.Length - 5, 1);
File.Copy(ModifiedFileName, FinalFileName);
if (File.Exists(ModifiedFileName))
File.Delete(ModifiedFileName);
}
catch (Exception ex)
{
throw ex;
}
}
}
}
You would implement a web-service, or you would utilize a handler file. This generic handler is often used, since it doesn't require a form. Once you utilize the template you'll have a file that should appear as follows:
public class SampleHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
}
public bool IsReusable
{
get { return false; }
}
}
From your primary application, or form, you would execute your ajax as follows:
<script type="text/javascript">
$.ajax({
url: '<% Page.ResolveUrl("/SampleHandler.ashx") %>',
method: 'post',
...,
success : function (response) {
// Handle .ashx response.
}
});
</script>
That is one of the simplest approaches. As it will allow you to separate your logic, compared to the declaration of a method in your code behind decorated in a [WebMethod] attribute.

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>

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

Categories

Resources