简体   繁体   中英

Jquery JSON response to populate many fields in form

I am trying to take a json response and populate a form with it. I can populate all the text fields just fine, I however, can not get select fields to show the value of the json.

my example is on jsfiddle Here

$('#sub').click(function(){

var returnValues = {'name':'Bob','age':'21','favoriteFood':'Spaghetti'};
$.each(returnValues, function(e,i){
    alert(e+i);
    $('#'+e).val(i);
  });
});

<input type='text' id='name'>
<input type='text' id='age'>
    <select name='favoriteFood'>
        <option value=''>
            <option value='Turkey'>Turkey</option>
            <option value='Fish'>Fish</option>
            <option value='Spaghetti'>Spaghetti</option>
        </select>

The json response has values like {"toName":"CustomerX"} my actual code:

        <div class='label'><label for='toName'>To Name</label></div>
            <div class='input' style='width:15%'><select id='toName'>
                                    <option value=''></option>
 <?php
    foreach ($customers as $k => $v)
    {
            if(strlen($v) > 0)
            {
                    echo "<option value='" . $k . ":" . $v . "'>" . $v . "</option>";
            }
    }
 ?>
    </select></div>

You need to set the id= on the dropdown, not just the name. jQuery won't find it by name in the loop you setup. If you need the 'name' for some other purpose, you can set both the same.

<select id='favoriteFood' name='favoriteFood'>

jsfiddle => http://jsfiddle.net/apf9ds5m/2/

do you want the selected text? Then this will do it:

$('#sub').click(function(){
    var returnValues = {'name':'Bob','age':'21','favoriteFood':'Spaghetti'};
    $.each(returnValues, function(e,i){
        //alert(e+i);
        if ('favoriteFood' === e) {
            $('select#'+e).val(i).attr("selected", "selected");
        } else {
            $('#'+e).val(i);
        }
    });
});

please add the id in the select:

<select id='favoriteFood' name='favoriteFood'>

The solution was to add:

 if (e == "toName"){
 $('#toName option:contains('+i+')').prop('selected', true);
 }

i would have to do this for all select fields in my form.

Is something kind like that you looking?

$('#sub').click(function() {
    var returnValues = {'name':'Bob','age':'21','favoriteFood':'Spaghetti'};
    $.each(returnValues, function(e,i){
        alert(e+i);
        $('#'+e).val(i);
        if (e == 'favoriteFood') {
            $('select option[value="'+i+'"]').attr('selected', true);
        }
    });
});

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