In the following SSCCE,there are two .inner-table
elements. I have used JQuery each()
to iterate through them. Then inside each .inner-table
, I iterate through each <tr>
to find out and alert the value of the <input>.color-name
element, by using val()
function.
The problem is that in the first iteration, the alert showing value of <input>.color-name
shows correct value I entered into the text field, but in the second iteration (ie for the second inner-table
), the alert seems to show an empty string no matter what I write into the text field.
The question is why? What am I doing wrong?
$(document).on("click", "#button", function(event) { //event.preventDefault(); alert('Button clicked.'); //check var colorName; var dataJSON = {}; $(".inner-table").each(function() { var dataUnit = []; dataJSON.dataUnit = dataUnit; var iterationCount = 1; $(this).find("tbody tr").each(function() { alert("Iteration " + iterationCount); //check //alert($(this).html());//check if ($(this).find("td .color-name").length) { colorName = $(this).find("td .color-name").val(); alert(colorName); //check } iterationCount++; }); var color = { "colorName": colorName }; dataJSON.dataUnit.push(color); }); console.log("dataJSON > " + JSON.stringify(dataJSON)); //check });
.outer-table tr { margin: 30px; } .inner-table { border: 2px solid yellow; background-color: wheat; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="button"> Click </button> <table class="outer-table"> <tbody> <tr> <td colspan="3"> <table class="inner-table"> <tbody> <tr> <td> <p class="input-label">Name of Color</p> <input class="input-field color-name" type="text" /> </td> </tr> </tbody> </table> </td> </tr> <!-- ------------------------------------------------- --> <!-- ------------------------------------------------- --> <!-- ------------------------------------------------- --> <tr> <td colspan="3"> <table class="inner-table"> <tbody> <tr> <td> <p class="input-label">Name of Color</p> <input class="input-field colorName" type="text" /> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table>
You should read more on the each
API here: http://api.jquery.com/jQuery.each/ . You should change your callback function to accept parameters including the iteration variable, rather than declaring your own. I think that is start of your solution. In the jsfiddle, the iterator variable never seems to advance in the alerts popped up.
you are using a wrong class name in the second td. you are using "colorName" it should be "color-name"
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.