Copy dynamic field value to another field - javascript

I am running a database app (sql backend). One particular form calls a value from another table using the follwing:
<td class=NewSalesOpCompany id="contactPostCode"><#externalfield SQL="Select POSTALCODE from wce_sales s join wce_linkto l on s.UNIQUEID = l.luniqueid left join wce_contact c on l.LEntityID = c.UNIQUEID where (s.UNIQUEID = '<#field field=uniqueid noedit static>')" ></td>
The above code populates the field with post-code data in text format which works fine. I then want to copy the data in that field to another field. I have tried the folwing but failed to get it to work.
<script language=javascript>
function copyPostCode() {
var parentPOSTALCODE=document.getElementById('contactPostCode');
var oppPOSTCODE=document.forms[0]._POSTCODE;
if (oppPOSTCODE != parentPOSTALCODE)
{ oppPOSTCODE.value = parentPOSTALCODE.value;}
}
</script>
When executing the function I get "parentPOSTALCODE.value is undefined" error via firefox. I'm a bit of a newbie at this so any help would be appreciated.

Try this:
<script language=javascript>
function copyPostCode() {
var parentPOSTALCODE=document.getElementById('contactPostCode');
var oppPOSTCODE=document.forms[0]._postcode;
if (oppPOSTCODE != parentPOSTALCODE)
{
oppPOSTCODE.value = parentPOSTALCODE.innerText;
}
}
</script>
Here is the example FIDDLE

Related

Compare variable values in scriplet and javascript

I have a jsp file with a scriptlet tag, I am getting the values of .properties file in it .I have a java script tag in which I am storing the value from the dropdown in a variable. On selecting some value in the dropdown I want to compare it with the property in the scriptlet and if it is equal a value from properties file must populate in my textbox. I have tried the following code but it is not working
My scriplet tag
<%
Properties prop = new Properties();
String propFileName = "server. properties";
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
if (inputStream != null) {
prop.load(inputStream);
} else {
throw new FileNotFoundException("property file '" + propFileName + "'not found in the classpath");
}
String appName = prop.getProperty("Demo_name");
String link = prop.getProperty("Demo_Links");
String database = prop.getProperty("DemoApps_DataBase");
%>
JavaScript
<script type="text/javascript">
function OnSelectionChange(serverName) {
var selectedOption = serverName.options[serverName.selectedIndex];
var txtbox=document.getElementById('serverLink');
var appName=<%=appName%>;
var links=<%=link%>
alert(appName.value);
if(selectedOption.value==appName.value){
txtbox.value=links.value;
}
}
</script>
Try this code. Is Your selected value is case sensitive?
<script type="text/javascript">
function OnSelectionChange(serverName) {
var selectedOption = serverName.options[serverName.selectedIndex].value;
var txtbox=document.getElementById('serverLink');
var demoName='<%=demoServer%>';
var testName='<%=testingServer%>';
var PNGName='<%=pngServer%>';
var DCPName='<%=dcpServer%>';
var demoLink='<%=demoLink%>';
var testLink='<%=testingLink%>';
var pngLink='<%=pngLink%>';
var dcpLink='<%=dcpLink%>';
if(selectedOption==appName){
txtbox.value=links;
}
if(selectedOption==PNGName){
txtbox.value=pngLink;
}
if(selectedOption==DCPName){
txtbox.value=dcpLink;
}
if(selectedOption==demoName){
txtbox.value=demoLink;
}
}
</script>
Using scriplets populate the values in a hidden field from your scriplet like :
<input id=hiddenPops type="hidden" name="Language" value="English">prop1=value2;prop2=value3</input>
In your javascript get the value of the above field using getElementById(hiddenPops )
Split the value string into array or as desired and you can work with it to match the keys and fetch the corresponding values.
Note: Its a solution but your approach is not great. Try to use modern JS frameworks which could allow you to talk to the server directly or simply use Ajax

highlight search word using jquery in MVC

I have MVC controller that returns a list containing a search string.
public ActionResult GetList(string searchString)
{
ViewData["searchString"] = searchString;
if (String.IsNullOrEmpty(searchString))
{
var persons = db.Persons.ToList();
return View(persons);
}
else{
var persons = db.Persons.Where(p=> p.Title.Contains(searchString)).ToList();
return View(persons);
}
}
In the view the list is displayed in a table. I want to highlight the searchString (or at most the td that contains the searchString). The following is my jquery where I attempted to achieve this. I have tried putting this bit of code in a separate .js script or in the view itself and I have also tried to change the code in several ways but it wouldn't work. It appears like the searchString remains null even if the content of my ViewData has changed.
$(document).ready(function () {
var textToHighligt = #ViewData["searchString"];
$("#simpleSearchButton").click(function () {
$("td:contains(textToHighligt)").css("background-color", "yellow");
});
});
I think this:
var textToHighligt = #ViewData["searchString"];
$("td:contains(textToHighligt)").css("background-color", "yellow");
should be concatenated:
var textToHighligt = '#ViewData["searchString"]'; //<---put in quotes
$("td:contains("+textToHighligt+")").css("background-color", "yellow");
I think you can do otherwise if it is not happening in the javascript file , create a hidden field and populate the value from the ViewBag
#Html.Hidden("hiddensearchString", (string)ViewBag.searchString)
For the ViewData
#Html.Hidden("FirstName", ViewData["searchString"])
and then the javascript read the value like this
var searchString = $("#hiddensearchString").val();
In you code you can also try this using of the single quote.
var textToHighligt = '#ViewData["searchString"]';

easiest way to read data from excel spreadsheet with javascript?

I have a list of airport codes, names, and locations in an Excel Spreadsheet like the below:
+-------+----------------------------------------+-------------------+
| Code | Airport Name | Location |
+-------+----------------------------------------+-------------------+
| AUA | Queen Beatrix International Airport | Oranjestad, Aruba|
+-------+----------------------------------------+-------------------+
My Javascript is passed a 3 character string that should be an airline code. When that happens I need to find the code on the spreadsheet and return the Airport Name and Location.
Im thinking something like:
var code = "AUA";
console.log(getAirportInfo(code));
function getAirportInfo(code) {
// get information from spreadsheet
//format info (no help needed there)
return airportInfo;
}
Where the log would write out:
Oranjestad, Aruba (AUA): Queen Beatrix International Airport
What is the easiest method to get the data I need from the spreadsheet?
Extra Info:
The spreadsheet has over 17,000 entries
The function alluded to above may be called up to 8 times in row
I don't have to use an Excel Spreadsheet thats just what I have now
I will never need to edit the spreadsheet with my code
I did search around the web but everything I could find was much more complicated than what Im trying to do so it made it hard to understand what Im looking for.
Thank you for any help pointing me in the right direction.
I ended up using a tool at shancarter.com/data_converter to convert my flie to a JSON file and linked that to my page. Now I just loop through that JSON object to get what I need. This seemed like the simplest way for my particular needs.
I've used a plain text file(csv, or tsv both of which can be exported directly from Excel)
Loaded that into a string var via xmlhttprequest. Usually the browsers cache will stop having to download the file on each page load.
Then have a Regex parse out the values as needed.
All without using any third party....I can dig the code out if you wish.
Example:
you will need to have the data.txt file in the same web folder as this page, or update the paths...
<html>
<head>
<script>
var fileName = "data.txt";
var data = "";
req = new XMLHttpRequest();
req.open("GET", fileName, false);
req.addEventListener("readystatechange", function (e) {
data = req.responseText ;
});
req.send();
function getInfoByCode(c){
if( data == "" ){
return 'DataNotReady' ;
} else {
var rx = new RegExp( "^(" + c + ")\\s+\\|\\s+(.+)\\s+\\|\\s+\\s+(.+)\\|", 'm' ) ;
var values = data.match(rx,'m');
return { airport:values[2] , city:values[3] };
}
}
function clickButton(){
var e = document.getElementById("code");
var ret = getInfoByCode(e.value);
var res = document.getElementById("res");
res.innerText = "Airport:" + ret.airport + " in " + ret.city;
}
</script>
</head>
<body>
<input id="code" value="AUA">
<button onclick="clickButton();">Find</button>
<div id="res">
</div>
</body>
</html>

Javascript for onblur event

Building a registration form using webmatrix,asp.net & Javascript,sql server CE. I'm writing an onblur event for the Username textbox.When focus leaves the textbox, it checks if there is an exisiting username in database and displays a label if yes.The foll. code is not working as js code is ignored if inside the "#{}" block. It works fine outside the "#{}" block but then i cant give a condition there.Please help me out.
<html>
<head>
<script>
function RegUsernameLeave()
{
#{
regusername=Request.Form["regusername"];
if(!regusername.IsEmpty())
{
var db = Database.Open("myshop");
int usercount = db.QueryValue("select count(*) from webusers where username=#0",regusername);
db.Close();
if(usercount!=0){
document.getElementById("msg").innerHTML="Username already exists";}
}
}
}
</script>
</head>
<body>
<label>Username:</label>
<p><input type="text" id="regusername" onblur="RegUsernameLeave()"/>
<label id="msg"></label></p>
</body>
</html>
I'm taking a complete stab in the dark here.. but maybe something along these lines?
Basically - I'm assuming that anything #{} is printed out into the JS - so if we can executed the server side code and output it equal to your JS variable userCount then you can use that JS Variable to do your checking and output the error message (if necessary)
#functions{
public int GetUserCount() {
string regusername = Request.Form["regusername"].ToString();
if(!regusername.IsEmpty())
{
var db = Database.Open("myshop");
int usercount = db.QueryValue("select count(*) from webusers where username='#0'",regusername);
db.Close();
return usercount;
}
return 0;
}
}
function RegUsernameLeave()
{
var userCount = #GetUserCount();
if (userCount > 0)
document.getElementById("msg").innerHTML="Username already exists";
}

the function is not working

Alright, so I'm making a form validation everything is good in this JS, but now I'm facing a problem in the output, I am trying to display all the chosen data. So I used the action attribute and called the following function:
function funcs()
{
var favor = document.reg.favor[selectedIndex].value; //Select input
var fname = document.reg.fname.value; // text input
var lname = document.reg.lname.value; // text input
var email = document.reg.email.value; // text input
var pass = document.password.value; //text input
for(i=0;i<document.reg.rad.length;i++)
{
if(document.reg.rad[i].checked == true)
{
var rad = document.reg.rad[i].value; // Radio input
}
}
if(document.reg.bike.checked == true)
{
var bike = document.reg.bike.value; //CheckBox input
}
if(document.reg.car.checked == true)
{
var car = document.reg.car.value; //CheckBox input
}
document.write('<head><link type="text/css" rel="stylesheet" href="registrationtable.css"/></head><body>');
document.write("<div class = 'team'>");
document.write('<table>');
document.write("<tr><td> שם פרטי: </td><td>" + fname + "</td></tr> <tr><td> שם משפחה: " + lname + "</td></tr> <tr><td> אימייל: " + email + "</td></tr> <tr><td> סיסמא: " +pass +"</td></tr>");
document.write("<tr><td> השחקן האהוב עליך הוא " + favor +"</td></tr>");
document.write("</table>");
document.write("</div></body>");
}
Here's the form header:
<form name ="reg" action ="Javascript:funcs()" onsubmit ="return checkValidation()">
I'd like to clear that all the other javascript code is working perfectly, it must be something with this function.
When I'm pressing the send button, it won't do anything. Anyone knows whats the problem?
Thanks in advanced.
You can't shouldn't have a javascript function in your action attribute, it needs to be a URI. You can just call the funcs onsubmit if validation succeeded.
As Aquinas has shown that calling a javascript function in the action attribute is in fact possible, it is advised that you not put js code in the action attribute.
As I suspected. One problem is this line:
var favor = document.reg.favor[selectedIndex].value;
It should be
var favor = document.reg.favor[document.reg.favor.selectedIndex].value;
And your second problem is this:
var pass = document.password.value;
Should be:
var pass = document.reg.password.value;
See updated fiddle: http://jsfiddle.net/x7SBy/1/
Finally, you should use Firefox and download Firebug. It is invaluable for debugging JS problems like this.
Edit: There are other problems with your JS that I won't get into in detail, but in general you don't want to use document.reg.password, because of issues like this. You should really use document.getElementById. FYI.
It looks like you are trying to validate a form, then if valid call the funcs function to alter HTML on the page.
Maybe something like this:
<form name="reg" action="" onsubmit="checkValidation()">
Then a checkValidation function to pause form submission and if valid, call the funcs function:
function checkValidation(e) {
e.preventDefault();
if (checkValidation()) {
funcs();
}
}
But if this is the case, your funcs function should not be writing <head> tags and such. Maybe you could just add HTML to the body instead of trying to lay a new HTML document into the DOM with javascript.
Alternate solution:
function checkValidation() {
... do your validation
return true; // or false if invalid
}
Then use a real HTML page/resource in your action tag of the form.

Categories