简体   繁体   中英

How to get value from object?

I have this code which works.

$(document).ready(function(){
  $('form').live('submit', function(){

     // have to do it like this to simulate my problem
     var aform = $(this);

     var dat = { "TITLE" : "55h5", "OWNER" : "fff" };
     $('#template').tmpl(dat).prependTo('#content');

    return false;

  });
});

But what I would like is to take the values from aform and insert them directly into

$('#template').tmpl(  HERE   ).prependTo('#content');

The data from the form have do accessed through aform to simulate my problem. Can this be done?

Here is the problem illustrated

http://jsfiddle.net/HYLYq/

You could use .serializeArray() , and then loop over it to create the right data structure:

var data = {},
    values = $(this).serializeArray();

for(var i = values.length; i--;) {
    data[values[i].name] = values[i].value;
}

You could do the same with plain JavaScript (is probably faster):

var elements = $(this)[0].elements,
    data = {};

for(var i = elements.length; i--;) {
    data[values[i].name] = values[i].value;
}

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