views:

67

answers:

1

I have the user entering a post-number in a form-field, and then I want to display the town with that post-number.

I have the server-side function set up, it takes a variable from the URL and returns a plain string.

As I see it, I need to get the variable from the form-field afterthe user has written it and the focus has left the form-field, use that number in a XMLHttpRequest call to the server and display the resulted string.

But the problem is, that I've never written any JavaScript, more complex than a Hello World. So I would like some help with writing the JavaScript for that page, any help would be appreciated.

-- -0.5

+1  A: 

Since you are new to JavaScript I won't recommend using any js framework for this.

To get the value from an input box you can use

document.getElementById ( "txt1" ).value;

where txt1 is the id of the input element.

Then you can append the element value to the querystring and call the server side function. And if the response text is a plain string put that inside a div or span

document.getElementById ( "divTown" ).innerText = "response string"; // for IE

document.getElementById ( "divTown" ).textContent = "response string"; // for FF

You can get a basic understanding of ajax and javascript read these

AJAX Introduction

JavaScript Tutorial

rahul
w3schools.com? You must be joking :)
kangax
I think for a beginner it is a nice site.
rahul
**There's nothing nice about w3schools.com**. I don't see a reason for beginners to start with bad practices. I mean, seriously... look at this wonderful "form validation" script - http://www.w3schools.com/js/js_form_validation.asp. Instead of providing clear and simple solution (which is trivial), w3schools decides to introduce completely unnecessary `with` together with an ancient, non-standard form elements access (`formEl.foo` instead of `formEl.elements.foo`). As if that wasn't enough, an example is based on invalid and poor HTML (inputs have no labels, doctype is missing, no title).
kangax