jj2
jj2

Reputation: 956

Update next span with specific class using jquery

As shown below, I'm trying to update the html of a span when a value is selected from a bootstrap dropdown menu. I am trying to update whatever the next span is after the dropdown menu with class "requestStatus".

I thought something like $(this).closest('.requestStatus').html('updated status'); should do the trick but no such luck.

Here's the relevant markup:

<div>
  <div class="btn-group">
    <button type="button" class="btn btn-primary btn-sm dropdown-toggle" data-toggle="dropdown">Action <span class="caret"></span></button>
      <ul class="pull-right dropdown-menu btnUpdateRequestStatus" role="menu">
        <li><a href="...">In progress</a></li>
        <li><a href="...">Complete</a></li>
        <li><a href="...">Cancel</a></li>
      </ul>
    </div>
    some text <span class="requestStatus">status goes here...</span>
  </div>
</div>

Here's the jquery:

$(document).on("click", ".btnUpdateRequestStatus", function(e){
  e.preventDefault();

  $.ajax({
    async: false,
    type: 'GET',
    cache: false,
    url: $(e.target).attr('href'),
    success: function(response){ 
      $(e.target).closest('.requestStatus').html('updated status');
    },
    error: function(){
      ...
    }
  });
}); 

I know there's a lot of questions similar to this, but I have seemingly tried all of the suggestions but nothing seems to work (continually just get "undefined").

Upvotes: 0

Views: 59

Answers (2)

j08691
j08691

Reputation: 207891

Change:

$(e.target).closest('.requestStatus').html('updated status');

to:

$(e.target).closest('div.btn-group').parent().find('span.requestStatus').html('updated status');

jsFiddle example

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

Because those are not ancestor descendant elements

$(e.target).closest('.btn-group').nextAll('.requestStatus').html('updated status');

$(document).on("click", ".btnUpdateRequestStatus", function(e) {
  e.preventDefault();

  $(e.target).closest('.btn-group').nextAll('.requestStatus').html('updated status');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
  <div class="btn-group">
    <button type="button" class="btn btn-primary btn-sm dropdown-toggle" data-toggle="dropdown">Action <span class="caret"></span>
    </button>
    <ul class="pull-right dropdown-menu btnUpdateRequestStatus" role="menu">
      <li><a href="...">In progress</a></li>
      <li><a href="...">Complete</a></li>
      <li><a href="...">Cancel</a></li>
    </ul>
  </div>
  some text <span class="requestStatus">status goes here...</span>
</div>

Upvotes: 1

Related Questions