post data from table row like json format

后端 未结 3 825
囚心锁ツ
囚心锁ツ 2021-01-03 15:24

this is related to my last question( NOTE: I already got some good answers there). I\'m doing a program that will filter. I didn\'t include this question because i thought t

3条回答
  •  太阳男子
    2021-01-03 16:00

    Building on my answer to your previous question, see http://jsfiddle.net/evbUa/1/

    Once you have your data in a javascript object (dataArray in my example), you can write the JSON yourself, per my example, but you will find it much easier to use a library such as JSON-js (see this also).

    // object to hold your data
    function dataRow(value1,value2,value3) {
        this.name = value1;
        this.comparison = value2;
        this.value = value3;
    }
    
    $('#out').click(function(){   
    
        // create array to hold your data
        var dataArray = new Array();
    
        // iterate through rows of table
        for(var i = 1; i <= $("table tr").length; i++){
    
            // check if first field is used
            if($("table tr:nth-child(" + i + ") select[class='field']").val().length > 0) {
    
                // create object and push to array
                dataArray.push(    
                    new dataRow(
                        $("table tr:nth-child(" + i + ") select[class='field']").val(),
                        $("table tr:nth-child(" + i + ") select[class='comp']").val(),
                        $("table tr:nth-child(" + i + ") input").val())
                );
            }
    
        }
    
        // consider using a JSON library to do this for you
        for(var i = 0; i < dataArray.length; i++){
            var output = "";
            output = output + '{"name":"data' + (i + 1) + '.' + dataArray[i].name + '",';
            output = output + '"comparison":"data' + (i + 1) + '.' + dataArray[i].comparison + '",';
            output = output + '"value":"data' + (i + 1) + '.' + dataArray[i].value + '"}';
            alert(output);
        }
    })
    

提交回复
热议问题