Call a JavaScript function from VB code
How can I call a Javascript function from my VB.Net code?
I have built a ASP.Net website in VS2005. It is one of those set-ups where you have 2 seperate files for the webpages: i.e. Default.aspx and Default.apsx.vb.
I need to be able to call a JavaScript function from within my VB code, also I need to pass a string variable into the JavaScript function. The JavaScript code is currently sitting at the top of the Default.aspx page whereas the VB code is in the Default.apsx.vb page.
Additional info (if it helps):
What the VB code does is take a user-inputed address and find it in a database and returns certain info about the address. I am trying to improve it to display a Google Map of the address using the Google Maps JavaScript API.
I already have the javascript function ready to go that takes a string address and makes and displays a google map of it, I just need to be able to call it after the user has entered their address.
Simple Javascript solution to get value of element
You can get the value of a form element completely within the Javascript scope and, then you can pass it to a URL as a URL variable which can then be processed with the ASP.NET code. That is one way to do it, probably the simplest, although there are other ways to do it also. Also a hidden form element will be processed by ASP.NET in the same way that a form element of type text is processed.
You can access the value of a form element using getElementById, even if the form element is type HIDDEN, this is actually done quite often in web application development.
Here is a simple example of using getElementById with a form element. It is very important that your form element has an ID attribute, or else the javascript will fail.
<html>
<head>
<script languague="javascript">
function ProcessForm() {
var Address = document.getElementById("address").value;
if (Address != "") {
alert("Address:" + Address);
return true;
} else {
return false;
}
}
</script>
</head>
<body>
<form method="post" onsubmit="return ProcessForm();">
Address: <input type="text" name="address" id="address" value="" />
<input type="submit" value="Submit">
</form>
</body>
</html>
Michael G. Workman
michael.g.workman@gmail.com