Domanda

file "zip.json": { "zip11111": "City1", "zip99999": "City2" }

the javascript:

jQuery(document).ready(function() {
$("#textbox1zip").change(function() {
    $.getJSON('zip.json', function(data) {

    /* each of the following code blocks don't work when exchanged for each other:

    1 zipcode = "zip" + $("#textbox1zip").val();
    * $('#textbox2city').val( data.zipcode ); -----> call silently dropped

    2 zipcode = 'zip99999';
    * $('#textbox2city').val( data.zipcode ); -----> call silently dropped

    3 zipcode = "zip" + $("#textbox1zip").val();
    * alert( data.zipcode ); -----> returns 'undefined'
    */

    /* but each of these blocks here works:
    4 $('#textbox2city').val( data.zip99999 ); ------> ok

    5 alert( data.zip99999 ); -----> ok

    6 zipcode = 'zip99999';
    * $('#textbox2city').val( zipcode ); ------> ok

    7 zipcode = "zip" + $("#textbox1zip").val();
    * $('#textbox2city').val( zipcode ); ------> ok
    */
    });
});
});

I want the value taken from textbox1zip to return the appropriate value from "zip.json" into textbox2city. And I want to use getJSON. It's probably very simple, but I can't see it...

È stato utile?

Soluzione

Try this:

var zipcode = 'zip99999';   // or 'zip11111'
$('#textbox2city').val( data[zipcode] );

and

var zipcode = "zip" + $("#textbox1zip").val();
$('#textbox2city').val( data[zipcode] );

Now, this alert( data.zipcode ); -----> returns 'undefined'

This happen since the json object you have only two keys zip11111 & zip99999. So, data.zip11111 or data.zip99999 works, whereas data.zipcode doesn't since there's no key with the name zipcode.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top