简体   繁体   中英

convert html table data to form using jQuery

I am attempting to retrieve data from a table on another website using YQL and display the data in a form on my website using jQuery. I have been successful retrieving the data and displaying it on my website as-is, however, I am not sure where to start to put the data into my form inputs.

The data being retrieved looks like this:

<table>
    <tbody>
        <tr class="">
            <td class="nobr">
                <a href="/player-26164302" title="View player profile">C Borup</a>
            </td>
            <td class="num IP">
                <p>0.2</p>
            </td>
            <td class="num H:pitching">
                <p>2</p>
            </td>
            [...]
        </tr>
    </tbody>
</table>

I guess I can do 1 of 2 things at this point.
1) Try to convert the p tags in this table to inputs, but just as important I would need to apply the class from the td to the input as well. 2)retrieve the value from the p tag in the table and place it in the existing form based on the td class (is this possible?).

My jQuery to retrieve and display the data look like this:

jQuery("#bbnuke_retrieve_gamechanger_results_btn_id").bind('click', function() {
    var gameID = jQuery("#bbnuke_plugin_gamechanger_import").val();
    var pitchLink = 'http://www.gamechanger.io/game-' + gameID + '/boxscore/pitching/standard';
    var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select tbody FROM html where url ="' + pitchLink + '" and xpath="//table[@id=' + "'tbl_home_pitching'" + ']"') + '&format=xml&callback=?';
    jQuery.getJSON(yql, cbFunc);

    function cbFunc(data) {
        if (data.results[0]) {
            data = data.results[0].replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');
            jQuery("#gamesitedump").html(data);
        }
        else {
            jQuery("#gamesitedump").html("Error");
            throw new Error('Nothing returned from getJSON.');
        }
    }
});

Any help is much appreciated!

You could "convert" the <p> into <input> this way :

$("td > p").each(function() {
    // creates a new <input> element
    $newInput = $("<input type='text'/>");
    // find the parent of the current <p>, and applies its class to the new <input>
    $newInput.addClass($(this).parent().attr("class"));
    // get the value of the current <p>, and set the value of the new <input> to this
    $newInput.val($(this).text());
    // replace the current <p> element with its <input> equivalent
    $(this).replaceWith($newInput);
});

You can find a jsFiddle example here .

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