0

I run an ajax request and return a json array. There is more in the json array than there is fields on the page. I want to cycle through text fields and find their NAME and match that to the json array and fill in the value.

The names of the fields and the names in the json array are the same.

<script type="text/javascript">
function loadIntake(){
var client = <?php echo $id ?>;

$.post("loadIntake.php", 
    {id: client},
    function(jdata){
        $.each(jdata, function(i, data) {
            $('#' + i).val(data);
        });
            $('input[type=text]').attr("name", function(n, idata){
                //$(idata).val(jdata.idata);
                //alert (idata);
            })
    },
    "json"
);  

}
</script>

However, some of the fields are text fields, some are textfields, some are radio buttons, and checkboxes. As I said the json array has MORE fields than there are fields on the page. So I dont want to deal with unnecessary code runs.

2 Answers 2

2

There are some plugins you might consider using for this. Populating a form with a json object is more complex than you think because fields are not only of type 'input' but could also be 'textarea', 'checkbox', 'radio' or a 'select'.

I've found the following form filler plugins but they're rather old:

http://www.keyframesandcode.com/resources/javascript/jQuery/demos/populate-demo.html

http://plugins.jquery.com/project/Wonderfill

Sign up to request clarification or add additional context in comments.

1 Comment

I've tested Wonderfill - the most recent plugin - and it works fine!
0

How about this:

$.each(jdata, function(i, data) {
    var nameOfField = data.name;
    $('[name='+nameOfField+']').val();
});

I am honestly not sure if that will work, but it won't hurt to try!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.