user2879070
user2879070

Reputation: 15

getting input values with jQuery

I'm trying to get the values out of the input boxes after clicking the Remove button and before removing the row using jQuery. Right now I'm just trying to get the first box, but haven't had any luck with my selection attempts.

Here is the latest attempt at retrieving the input value having an .editing class. By the way, this is not all of the code. The removeIng function is firing like it's supposed to, I'm just not getting back what I need.

$('.remove_ing').click(removeIng);

function removeIng(){ //removes the row
    alert($(this).parentsUntil('tr').find('.editing').val());
    $(this).parent().parent().remove();
}

Here is the HTML, I have several rows like this (added dynamically)

<tr>
  <td><input type='text' name='ingredient' value='' class='editing' /></td>
  <td><input type="text" class='editing_amt' name="amount" size="8" value="100"/></td>
  <td><select name='meas' class='editing_meas'></select></td>
  <td><input type="button" name="remove_ing" class="remove_ing" value="Remove"/></td>

</tr>

Thanks for the help

Upvotes: 0

Views: 92

Answers (2)

Sam Ccp
Sam Ccp

Reputation: 1162

If your html is static ( it's not dynamic ) you should give the button an id and preferably the tr too. If that's not the case, then an event delegation is the way to go. @Tushar gave you an idea about event delegation.

Anyway, here's a little snippet that might help you.

var btn = $(".remove_ing");
btn.click( removeIng );
function removeIng(){
    // get the row
    var tr = $(this).parents("tr").first();
    //get the text boxes
    var txt = tr.find("input[type='text']");
    //loop through the texts
    txt.each(function(){
        alert( $(this).val() );
    });
}

In both cases ( dynamic or static html ) this function will get all your inputs text. Hope it helps.

Upvotes: 0

Use .on()

As elements are added dynamically you can not bind events directly to them .So you have to use Event Delegation.

$(document).on('click','.remove_ing',removeIng);

function removeIng(){ //removes the row
    alert($(this).parentsUntil('tr').find('.editing').val());
    $(this).parent().parent().remove();
}

Syntax

$( elements ).on( events, selector, data, handler );

Use .closest()

Instead

$(this).parent().parent().remove();

use

$(this).closest('tr').remove();

Upvotes: 2

Related Questions