简体   繁体   中英

How to display a string, based on number in a form with JavaScript

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 after the user has written it and the focus has left the form-field, use that number in an 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.

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 query string 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM