Anamnian Anamnian - 3 months ago 7
Javascript Question

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(""));

Answer

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) {

        },
    });
});
Comments