简体   繁体   中英

How to get the value of <select> inside <td> only if <select> tag presents?

I have an HTML page with its associated js file. the purpose is to convert data inserted into the table into a JSON file. User can edit table cells, and click the button so Javascript file parses the data and send it as an Ajax request to a PHP file on the server. The PHP file then stores the data as a file on the server and sends the link back. For the tags, I need to use val() instead of text() to get the selected value. However, val() returns an empty string. How to make it return value correctly?

 var $TABLE = $('#table'); var $BTN = $('#export-btn'); var $EXPORT = $('#export'); $('.table-add').click(function () { var $clone = $TABLE.find('tr.hide').clone(true).removeClass('hide table-line'); $TABLE.find('table').append($clone); }); $('.table-remove').click(function () { $(this).parents('tr').detach(); }); $('.table-up').click(function () { var $row = $(this).parents('tr'); if ($row.index() === 1) return; // Don't go above the header $row.prev().before($row.get(0)); }); $('.table-down').click(function () { var $row = $(this).parents('tr'); $row.next().after($row.get(0)); }); // A few jQuery helpers for exporting only jQuery.fn.pop = [].pop; jQuery.fn.shift = [].shift; $BTN.click(function () { //alert("ok"); var $rows = $TABLE.find('tr:not(:hidden)'); var headers = []; var data = []; // Get the headers (add special header logic here) $($rows.shift()).find('th:not(:empty)').each(function () { headers.push($(this).text().toLowerCase()); }); // Turn all existing rows into a loopable array $rows.each(function () { var $td = $(this).find('td'); var h = {}; // Use the headers from earlier to name our hash keys headers.forEach(function (header, i) { h[header] = $td.eq(i).val(); alert($td.eq(i).val()); }); data.push(h); }); // Output the result normaldata = JSON.stringify(data); $.ajax({ type: "POST", url: "filemaker.php", data: {"data":normaldata}, success: function(output) { var a = document.createElement('a'); a.href = 'data.gmp' a.download = "data.gmp"; a.click(); //alert("reached here"); } }); }); 
 .table-editable { position: relative; } .table-editable .glyphicon { font-size: 20px; } .table-remove { color: #700; cursor: pointer; } .table-remove:hover { color: #f00; } .table-up, .table-down { color: #007; cursor: pointer; } .table-up:hover, .table-down:hover { color: #00f; } .table-add { color: #070; cursor: pointer; position: absolute; top: 8px; right: 0; } .table-add:hover { color: #0b0; } 
 <!DOCTYPE html> <html lang="en" > <head> <meta charset="UTF-8"> <title>HTML5 Editable Table</title> <link rel='stylesheet' href='http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css'> <link rel='stylesheet' href='http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css'> <link rel="stylesheet" href="css/style.css"> </head> <body> <a href='text.html' >aa</a> <div class="container"> <h1>HTML5 Editable Table</h1> <p>Through the powers of <strong>contenteditable</strong> and some simple jQuery you can easily create a custom editable table. No need for a robust JavaScript library anymore these days.</p> <ul> <li>An editable table that exports a hash array. Dynamically compiles rows from headers</li> <li>Simple / powerful features such as add row, remove row, move row up/down.</li> </ul> <div id="table" class="table-editable"> <span class="table-add glyphicon glyphicon-plus"></span> <table class="table"> <tr> <th>Type</th> <th>Doctor</th> <th>Specialization</th> <th>City</th> <th>Area</th> <th>Rank</th> <th></th> <th></th> </tr> <tr> <td contenteditable="true"> <select> <option value='pharmacist'>Pharmacist</option> <option value='doctor'>Doctor</option> </select> </td> <td contenteditable="true">stir-fry</td> <td contenteditable="true">stir-fry</td> <td contenteditable="true">stir-fry</td> <td contenteditable="true">stir-fry</td> <td contenteditable="true"> <select> <option value='A+'>A+</option> <option value='A'>A</option> <option value='B'>B</option> <option value='C'>C</option> </select> </td> <td> <span class="table-remove glyphicon glyphicon-remove"></span> </td> </tr> <!-- This is our clonable table line --> <tr class="hide"> <td contenteditable="true"> <select> <option value='pharmacist'>Pharmacist</option> <option value='doctor'>Doctor</option> </select> </td> <td contenteditable="true">stir-fry</td> <td contenteditable="true">stir-fry</td> <td contenteditable="true">stir-fry</td> <td contenteditable="true">stir-fry</td> <td contenteditable="true"> <select> <option value='A+'>A+</option> <option value='A'>A</option> <option value='B'>B</option> <option value='C'>C</option> </select> </td> <td> <span class="table-remove glyphicon glyphicon-remove"></span> </td> </tr> </table> </div> <button id="export-btn" class="btn btn-primary">Export Data</button> <p id="export"></p> </div> <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script> <script src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js'></script> <script src='https://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js'></script> <script src='http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore.js'></script> <script src="js/index.js"></script> </body> </html> 

Given the following jQuery methods:

The .val() method is primarily used to get the values of form elements such as input , select and textarea .

The result of the .text() method is a string containing the combined text of all matched elements.

For each table cell, it seems that you want to return the val() of the child <select> , if one exists, and the text() of the <td> otherwise.

Using JavaScript's logical OR operator , we can choose text() or val() depending on which one exists:

Logical OR (||)
expr1 || expr2
Returns expr1 if it can be converted to true; otherwise, returns expr2.

Like this:

$select.val() || $td.text()

Here's an example:

 var $TABLE = $('#table'); var $BTN = $('#export-btn'); var $EXPORT = $('#export'); $('.table-add').click(function() { var $clone = $TABLE.find('tr.hide').clone(true).removeClass('hide table-line'); $TABLE.find('table').append($clone); }); $('.table-remove').click(function() { $(this).parents('tr').detach(); }); $('.table-up').click(function() { var $row = $(this).parents('tr'); if ($row.index() === 1) return; // Don't go above the header $row.prev().before($row.get(0)); }); $('.table-down').click(function() { var $row = $(this).parents('tr'); $row.next().after($row.get(0)); }); // A few jQuery helpers for exporting only jQuery.fn.pop = [].pop; jQuery.fn.shift = [].shift; $BTN.click(function() { //alert("ok"); var $rows = $TABLE.find('tr:not(:hidden)'); var headers = []; var data = []; // Get the headers (add special header logic here) $($rows.shift()).find('th:not(:empty)').each(function() { headers.push($(this).text().toLowerCase()); }); // Turn all existing rows into a loopable array $rows.each(function() { var $tds = $(this).find('td'); var h = {}; // Use the headers from earlier to name our hash keys headers.forEach(function(header, i) { var $td = $tds.eq(i); var $select = $td.find('select'); h[header] = $select.val() || $td.text(); console.log(h[header]); }); }); }); 
 .table-editable { position: relative; } .table-editable .glyphicon { font-size: 20px; } .table-remove { color: #700; cursor: pointer; } .table-remove:hover { color: #f00; } .table-up, .table-down { color: #007; cursor: pointer; } .table-up:hover, .table-down:hover { color: #00f; } .table-add { color: #070; cursor: pointer; position: absolute; top: 8px; right: 0; } .table-add:hover { color: #0b0; } 
 <link rel='stylesheet' href='http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css'> <link rel='stylesheet' href='http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css'> <div id="table" class="table-editable"> <span class="table-add glyphicon glyphicon-plus"></span> <table class="table"> <tr> <th>Type</th> <th>Doctor</th> <th>Specialization</th> <th>City</th> <th>Area</th> <th>Rank</th> <th></th> <th></th> </tr> <tr> <td contenteditable="true"> <select> <option value='pharmacist'>Pharmacist</option> <option value='doctor'>Doctor</option> </select> </td> <td contenteditable="true">stir-fry</td> <td contenteditable="true">stir-fry</td> <td contenteditable="true">stir-fry</td> <td contenteditable="true">stir-fry</td> <td contenteditable="true"> <select> <option value='A+'>A+</option> <option value='A'>A</option> <option value='B'>B</option> <option value='C'>C</option> </select> </td> <td> <span class="table-remove glyphicon glyphicon-remove"></span> </td> </tr> <!-- This is our clonable table line --> <tr class="hide"> <td contenteditable="true"> <select> <option value='pharmacist'>Pharmacist</option> <option value='doctor'>Doctor</option> </select> </td> <td contenteditable="true">stir-fry</td> <td contenteditable="true">stir-fry</td> <td contenteditable="true">stir-fry</td> <td contenteditable="true">stir-fry</td> <td contenteditable="true"> <select> <option value='A+'>A+</option> <option value='A'>A</option> <option value='B'>B</option> <option value='C'>C</option> </select> </td> <td> <span class="table-remove glyphicon glyphicon-remove"></span> </td> </tr> </table> </div> <button id="export-btn" class="btn btn-primary">Export Data</button> <p id="export"></p> <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script> <script src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js'></script> <script src='https://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js'></script> <script src='http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore.js'></script> 

first return of your algoritm ($td.eq(i)) is

<td contenteditable="true"> 
    <select> 
        <option value="pharmacist">Pharmacist</option>
        <option value="doctor">Doctor</option>
    </select>
</td>

and <td contenteditable="true"> is not have attribute value so that reson you have null value

and second value is

<td contenteditable="true">stir-fry</td>

its same havn't attribut value so return null too

just use .text() its clear. because .text() will get only text in tag

i hope i can help and understand what i say lol...

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