简体   繁体   中英

update value of a form field with json values in jQuery

I have a dropdown firm filed with countries like "Belgium", "Barbados" etc with id = " country " and another text input with phone number to be filled with id = " tele ". I need the country calling code to be updated in the tele id input filed based on country dropdown. I have a json file of country calling code mapped to country names in format ( countrycode.json ):

{
  "countries": [
    {
      "code": "+7 840",
      "name": "Abkhazia"
    },
    {
      "code": "+93",
      "name": "Afghanistan"
    },

etc....

My current jQuery code is as follows:

<script>
$('#country').change(function() {
    var countrycode = $(this).val();
    $('#tele').val(countrycode);
});
</script>

which will update the tele id with value from country id.

I need the country calling code to be selected from the json file based on the country chosen. How is it possible?

Thanks in advance.

The tags on your question are "jquery/jason". Using only those tools, you will have to embed the file into your html, probably as an object of key/value pairs.

How can I add a key/value pair to a JavaScript object?

If you don't want to embed it and have your own server, you can make ajax calls to the server to request the info you want. But you'll have to use your favorite server side scripting language (php, python, ruby, etc...) to send the response, then update the response value with jquery.

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