Mark Ma
Mark Ma

Reputation: 1362

jquery selector doesn't work when dynamically append html

I can dynamically append "select" control to DOM,after appending it to DOM,I wanna change the html content of the last "select"(the latest "select" added dynamically),but it failed...

(I cannot set options value in param_html,becuase I should set them by using ajax request later.)

<script>
    $(function(){
      var param_html = '<select class="params"></select>';
      $("input[value='+']").click(function(){
        $('#parameters').append(param_html);
          $('.params :last').html('<option>aaa</option><option>keyword in profile</option><option>last tweet</option>');
      });

    });
  </script>
  <div id="parameters">
    <input type="button" value="+">
    <select class="params"><option>1</option><option>2</option></select>
  </div>

any suggestion is appreciated.

Upvotes: 3

Views: 8205

Answers (3)

Adam
Adam

Reputation: 21

Well your CSS selector is imporper should be $('.params:last-child') or $('.params:last') i think the space bar is not allowed there.

Also no one forbis You from using the object you've created:

$(function(){
      var param_html = '<select class="params"></select>';
      $("input[value='+']").click(function(){
        $('#parameters').append(param_html);
          $(param_html).html('<option>aaa</option><option>keyword in profile</option><option>last tweet</option>');
      });

    });

If you are going to use AJAX in future then the same idea will work instead of reselecting the object use to one you've created.

Upvotes: 0

The Surrican
The Surrican

Reputation: 29874

your content seems to be added after the dom has been loaded.

try live http://api.jquery.com/live/

Upvotes: 1

Patricia
Patricia

Reputation: 7802

take out the space between params and :last

$('.params:last').html('<option>aaa</option><option>keyword in profile</option><option>last tweet</option>');

Upvotes: 6

Related Questions