0

Experts,

I am having a hard time getting jquery to modify some HTML values that is dynamically injected via an ajax response.

https://jsfiddle.net/ksa0yg9y/

I have some html on page:

<button id="test">test</button>
<div class="main"></div>

Script (simulating the html response by setting the html as static value):

$(document).on('click', '#test', function(){
    $.ajax({
  type: 'get',
  url: '/echo/html/',
  success:
  function(data) {
        $('.main').html('<input id="txt" type="text" name="title" value="">');
      }
  });
    $('#txt').val('test');
});

Expected result would be for the

But as you can see from the jsfiddle, the input value remains blank.

Any help is appreciated.

Rick
  • 555
  • 1
  • 12
  • 30
  • Both below answers are correct, but NullDev explains why and gives a demo. Here is [your jsFiddle updated](https://jsfiddle.net/ksa0yg9y/2/) – cssyphus Jan 20 '18 at 02:50

2 Answers2

1

The call which Ajax performs is asynchron. You need to "wait" until the data is actually there.
Try to use a callback:

$(document).on('click', '#test', function(){
    $.ajax({
        type: 'get',
        url: '/echo/html/',
        success: function(data) {
            $('.main').html('<input id="txt" type="text" name="title" value="">');
            callback();
        }
    });
    function callback() {
        $('#txt').val('test');
        //...
    }
});

Live Demo

NullDev
  • 6,739
  • 4
  • 30
  • 54
  • when using static data for html this works fine... when actually waiting on the ajax response (non simulated) it is not... i think you may be right that its not detecting the html response and attempting to change the value. – Rick Jan 20 '18 at 02:58
1

Is this what you're trying to do?

document.getElementById("test").addEventListener("click", function (e) {
    $.ajax({
        type: 'get',
        url: '/echo/html/',
        success: function(data) {
            $('.main').html('<input id="txt" type="text" name="title" value="">');
            $('#txt').val('test');
        }
    });
});
JeanPaul98
  • 492
  • 6
  • 18