How do I access values created by serializeArray in JQuery?

前端 未结 8 620
眼角桃花
眼角桃花 2021-02-02 09:33

I have this HTML:

And I create an object array from it lik

相关标签:
8条回答
  • 2021-02-02 10:00

    Similar to what Nick posted, but a little cleaner

    var dataArray = $("#myform").serializeArray(),
        dataObj = {};
    
    $(dataArray).each(function(i, field){
      dataObj[field.name] = field.value;
    });
    

    Then access the same way

    alert(dataObj['title']);
    
    0 讨论(0)
  • 2021-02-02 10:01

    Adding this anyway to help others in future. Good way to quickly inspect all values.

    var formdata = $( "#myform" ).serializeArray();
    var formdata = JSON.stringify(formdata);
    alert (formdata);
    
    0 讨论(0)
  • 2021-02-02 10:03
    alert(dataArray[0].name);
    alert(dataArray[0].value);
    

    So:

    for (i=0; i<dataArray.length; i += 1) {
        if (dataArray[i].name === "title") {
            // do something here...
        }
    }
    
    0 讨论(0)
  • 2021-02-02 10:16

    append/echo/print dataArray[0].name to a div will give you 'title'

    0 讨论(0)
  • 2021-02-02 10:18

    Alerting serializeArray of inputs in myDiv (note: the :input selector will include select and textarea tags as well!):

    //alert(fData.length) // how many inputs got picked up 
    var fData=$("#myDiv :input").serializeArray();
    var msg=""; 
    for(var i=0;i<fData.length;i++){
        var raKy=Object.keys(fData[i]); 
        msg+="\n"+raKy[0]+":"+eval("fData[i]."+raKy[0])+" "+raKy[1]+":"+eval("fData[i]."+raKy[1]); 
    }
    alert(msg);
    
    0 讨论(0)
  • 2021-02-02 10:22

    You can either loop through, as @Tom has...or if you're accessing more than one, be a bit more efficient and loop once, creating an object like this:

    var dataArray = $("#myform").serializeArray(),
        len = dataArray.length,
        dataObj = {};
    
    for (i=0; i<len; i++) {
      dataObj[dataArray[i].name] = dataArray[i].value;
    }
    

    Then you can access it like you want, for example:

    alert(dataObj['title']); //or alert(dataObj.title);
    

    You can test it out here.

    0 讨论(0)
提交回复
热议问题