Anamnian
Anamnian

Reputation: 427

How to get textbox value via button click Ajax

I have 2 input's:

<td><input id='someName_1' type='textbox' value='1' /><td>
<td><input id='someID_1' class="button1" type='button' value='Submit' /></td>

I have below ajax code:

$("body").on('click', '.button1', function () {
    var params = { id: this.id, value: (?) };
    $.ajax({
        type: 'POST',
        url: '@Url.Action(SomeUrl- pointless)',
        dataType: 'json',
        cache: false,
        contentType: 'application/json; charset=utf­8',
        data: JSON.stringify(params),
        success: function (data, status) {
            doingsomething
        },
        error: function (er, info) {

        },
        complete: function (xhr, status) {

        },
    });
});

Question is: how i can get value in variable 'params', field 'value' from textbox with someID_1, if all my id's are created dynamically via response from server? Input's are too created dinamically.

There is code which generated my input's:

var s = [];
$.each(data.items, function (i, item) {
                var t = "<td><input id='someName_" + item.id + "' type='textbox' value='1' /></td>" +
                "<td><input id='someID_" + item.id + "' class='button1' type='button' value='Submit' /></td></tr>";
                s.push(t);                   
            });
$('body').html(s.join(""));

Upvotes: 0

Views: 1908

Answers (2)

Dekel
Dekel

Reputation: 62566

Since your DOM is a bit problematic you will have to traverse to the previous td element and take the input from there.

Here is an example:

$("body").on('click', '.button1', function () {
    input = $(this).parent('td').prev('td').children('input[type=textbox]')
    var params = { id: $(this).attr('id'), value: input.val() };
    $.ajax({
        type: 'POST',
        url: '@Url.Action(SomeUrl- pointless)',
        dataType: 'json',
        cache: false,
        contentType: 'application/json; charset=utf­8',
        data: JSON.stringify(params),
        success: function (data, status) {
            doingsomething
        },
        error: function (er, info) {

        },
        complete: function (xhr, status) {

        },
    });
});

Upvotes: 1

Fabien
Fabien

Reputation: 4972

I am not sure that I see an issue here, but maybe I misunderstood the question?

Basically, you can pick up any DOM element that has any ID, by using jquery with:

$("#MY_RANDOM_ID")

so you can access its value (user input or automatically generated input) with:

$("#MY_RANDOM_ID").val()

Upvotes: 0

Related Questions