开发者

jQuery append value to html input depending on other input

Ok, the title is a bit confusing, but here's my predicament. I've made a web app to track UPS packages internally at work. Currently, you input the tracking number and then select the city it was shipped from. All tracking numbers fro开发者_StackOverflow中文版m an account start with the same X amount of numbers. So if someone entered "1Z8473..." into one input, "Houston, TX" would automatically be entered into the next input. Is this a difficult thing to pull off? Where would I begin?


You could monitor one input for a change, then depending on it's contents matching a specified value, updating the second one.

Trivial example:

<label for="code">Code:</label> <input type="text" id="code" />

<label for="area">Area:</label> <input type="text" id="area" />

<script type='text/javascript'>
    $(document).ready(function(){
        // Listen for change on our code input
        $('#code').keyup(function(){
            var entered = $(this).val();  // text entered in 'code'

            // Look up the start of the code (first 6 digits?)
            if(entered.substring(0,6) == '1Z8473')
            {
                // Set the value of our "area" input
                $('#area').val('Houston, TX');
            }
        });
    });
</script>

The above example uses a simple if block to do the matching. As others have posted here, you can send this value to a server side script that does the geolocation for your required areas. So replacing the if above with something like:

// Look up the area depending on the code entered
$.getJSON(
    '/geocoder_on_your_site.php?area='+entered, 
    function(data) {
        $('#area').val(data.location);
});

and on your server, in geocoder_on_your_site.php:

$input = $_REQUEST['entered'];
// Assume input is sanitised & checked first..
...
// Look up the area base on location
$data['location'] = look_up_location($input);

echo json_encode($data);


You'll need a geolocation API such as this one

Then you'll need to query it using AJAX calls, and put part of the result (the city in this case) into the input box.

Here's an example of something similar, install Firebug and watch the requests it sends.

Source code is here


Check for keyup events and send the input via ajax to a server-side tool which looks the number up and sends the city back. This is added simply by adding it to the value of the input.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜