1

I called a URL using AJAX using the following code below and it returned 2 items in an array in this format ["item1", "item2"]

function getbook()
{        
    $.ajax({
        type: "POST",
        url: "/Home/getBooked",
        data: { "bookNumber": mobile },
        success: function(succ) { // I need to add the items in succ to some text boxes as shown below
            $.each(succ, function (index, element) {
                    $('#tb1').val(element);
                    $('#tb2').val(element);
            });                           
        },
        error: function(err) { 
            alert("An error is thrown"); 
        }
    });
}

But the issue is that only the last item in the succ array is shown in both the textboxes. When I used the alert function to display the contents of succ, it displayed both the items. Clearly i'm missing something. I'll be glad if anyone could help.

2
  • Your loop is adding each element to each textbox and the 2nd iteration is overriding the first. I assume you want $('#tb1').val(succ[0]) and $('#tb2').val(succ[1]) Commented Jan 30, 2016 at 8:30
  • Thanks @StephenMuecke Commented Jan 30, 2016 at 8:41

2 Answers 2

1

The problem is you are setting the value in each iteration. Try like following.

success: function (succ) { 
    $('#tb1').val(succ[0]);
    $('#tb2').val(succ[1]);
}
Sign up to request clarification or add additional context in comments.

Comments

1
if the IDs of textbox is kind of sequence then we can resolve like bellow:

        $.each(succ, function (index, element) {
            $('#tb'+ (index + 1)).val(element);
        });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.