Trouble finding the last input value of a table with jQuery, my function only returns jibberish. How do you get the last row input value?

Jim Czerniak

Sorry for the basic question. I just started learning Javascript about 5 days ago. I have an HTML form/table like this:

<body>
    <form onsubmit="playland()">
    <table id="dynamictable"> <!-- Added an id to the table element to easily select it and keep track of the rows -->
        <tr>
            <td>Name</td>
            <td>Location</td>
            <td>From</td>
            <td>To</td>
        </tr>

        <tr class="tr_clone">
            <td>
                <input type="text" autofocus placeholder="who" name="add" class="tr_clone_add" >
            </td>
            <td>
                <input type="text" autofocus placeholder="location" name="location" >
            </td>
            <td>
                <input type="text" placeholder="Start Date" name="datepicker_start" class="datepicker">
            </td>
            <td>
                <input type="text" placeholder="End Date" name="datepicker_end" class="datepicker">
            </td>
        </tr>
    </table>

    <button  action="submit">Click me</button>
    </form>
</body>

There is a function that updates the rows once input is entered into the last row. This is that function:

$(document).on('input', 'input.tr_clone_add', function() {


    if(document.getElementById("dynamictable").tBodies[0].rows.length ==    
            (this.parentNode.parentNode.rowIndex + 1)) {                        
                var $tr    = $(this).closest('.tr_clone');
                var $clone = $tr.clone();
                $clone.find(':text').val('');
                $tr.after($clone);
        }                                                                       
    });

Then here is the function I am trying to make. I wan't to get the last table input value and store it in a variable. It just returns a bunch of jibberish at the moment though and I can't figure out why for the life of me.

function playland(){
    alert($("#dynamictable tr:last").prev().find("td").html());
}
Don't Panic

You were already very close. Working JSFiddle.

Assuming the nested $(document).on('input', ... handlers is just a typo, here's how you'd get the value of the last input in the second-to-last last table row (as the last row is now the new empty clone):

alert($("#dynamictable tr:last").prev().find("input:last").val());

Using td as your selector, you are choosing table cells, but it is really the input you're after. And using .html() will give you the actual literal HTML contents of the table cell(s), where you really want the input value - which you get with .val().

Edit - some suggestions:

Your code mixes jQuery with vanilla Javascript. Technically there's nothing wrong with that, but it is harder to read and work with. If you have jQuery available, you may as well use it.

This plain JS:

document.getElementById("dynamictable").rows.length

can be written in jQuery as:

$('#dynamictable tr').length

The jQuery selector matches all rows, and .length will tell us how many matches we got.

This plain JS:

this.parentNode.parentNode.rowIndex

is a bit tricker, but this jQuery works:

$(this).closest('tr').index()

$(this) in this context refers to the input element that received input. closest('tr') finds the closest parent row, which will be the row the input is in. And index(), in this format, will tell us the (zero-based) position of that element amongst its siblings.

Just for fun, you could also write that whole test as:

if ($(this).closest('tr').is($("#dynamictable tr:last"))) {

That simply checks if the row with the input is actually equal to the last row in the table. This is maybe a bit more readable and understandable than the other version.

Next, It is considered bad practice to include Javascript inline with your HTML, like the onClick() handler. A better approach is to keep them separated, and add the event handler in your JS, eg something like:

$('form').on('submit', playland);

Also note that as you are handling the form submission with JS, you (probably?) don't want the standard HTML form submission to happen. To stop that, you need to use the event parameter that is automatically passed to any event handler, and stop it - you do that with:

function playland(event){
    event.preventDefault();
    // ... rest of your code

Here's an updated JSFiddle with all those changes incorporated.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to get the entire input value dynamically (not the last character only)?

Get the input value of the last input field using JQuery

Break statement not storing data, returns only last value input

How to convert value from HTML table to JSON array in javascript excluding if any of the input in last row is empty and get numbers as integer in json

How can I use lead() function which returns the value of two rows forward such that the second last and last row value do not return null?

AngularJS and JQuery $.each() function only returns the last loop value

How to convert value from HTML table to JSON array in javascript excluding if any of the input in last row is empty

Beautiful Soup only returns last value of table

$_POST only contains the last input textbox value

Function only returns last value to list

Using for loop in a function, only returns last value

How to clone jQuery input before delete last value?

(ReactJS) How do you get the input value of an input of type date?

How to get last value of the input with some dynamic class?

How to get last value of an array input text in JS?

How to get last row value of mysql table in laravel?

Why my select only get the last value?

jQuery .html only get last value of JSON

Function returns only the first value of the input variable

How do you deny an input, re ask it, and ONLY retain that value

How to get a value from the last inserted row?

How to get the last row number with a positive value

How to get the rank of the last row with specified value?

How add new <input> when the last input has a value?

How do you replace a specific value of an input field using jQuery?

how do you change the value in the input using jquery?

How to get last recent value only

finding the first and last entry with a certain value in a row

How do you I React to get the button value into the input?

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive