Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery: Update only the next span with a specific class

Tags:

jquery

html:

<p class="fields">
  <select id="parts">
    <option value="10">Ring</option>
    <option value="50">Necklace</option>
    <option value="3">Pendant</option>
  </select>
  <label for="price">Price</label>
  <span class="price"></span>
</p>


function load_part_price_select(id, value) {
$('#' + id ).live('change',function() {
    $.ajax({
      url: '/parts/' + value + '/price',
      type: 'get',
              context: this,
      dataType: 'script',
      success: function(responseData) {
        $(this).next("span.price").html(responseData);
      }
    }); 
});
};

I've tried this way but no success.

The "onchange" is working fine I just need some help to display the value inside the span tag as a content.

Any help?

like image 739
Kleber S. Avatar asked Aug 10 '11 01:08

Kleber S.


2 Answers

@samccone was on the right track, but it's not working for you because the span.price is not the next element after the select#parts element (which I assume is the element you are sending to the load_part_price_select function).

It is one of the siblings though, so try this:

$(this).siblings("span.price:first").html(responseData);

Or try nextAll:

$(this).nextAll("span.price:first").html(responseData);

I'm going to assume that 'siblings' is more efficient because it doesn't care if the matched element is before or after 'this' element. But if you don't want to match previous spans, use 'nextAll'.

Then set the ajax context as per samccone's comment:

function load_part_price_select(id, value) {
$('#' + id ).live('change',function() {
    $.ajax({
      url: '/parts/' + value + '/price',
      type: 'get',
      context: this,
      dataType: 'script',
      success: function(responseData) {
        $(this).nextAll("span.price:first").html(responseData);
      }
    }); 
});
};
like image 147
irama Avatar answered Oct 29 '22 12:10

irama


$(this).next("span.price").html(responseData);

should work just fine

like image 1
samccone Avatar answered Oct 29 '22 14:10

samccone