views:

23

answers:

2

i need to select change some data and change image in own form each from will have own preview image. each image will get attr name "imagePreview" from selected the option. if nothing in attr or imagePreview="0" will do nothing

here some of my working scrip but when I change option all image preview in DIV tag will change not just in the form... please help me to make it work >.<

script

<script type="text/javascript">
$(document).ready(function() {
$('.choose').change(function(event) {
  var update = $(this).prev();
  //------
  var src = $("option:selected").attr("imagePreview");
  $(".imagePreview").html(src ? "<img src='" + src + "'>" : "");
  //-----
  $.post('select-change-ajax2.php', $(this).closest('form').serialize(), function(data) {
    update.html(data);
  });
});
});
</script>

html form

<form>
<div class="imagePreview">
   displays image here
</div>
( etc data this data not change )
 <div class="update">Default Data</div>
    <select name='selected' class="choose">
        <option value="1" imagePreview='/images/1.jpg'>1</option>
        <option value="2" imagePreview='0'>2</option>
       </select>
       <input type='hidden' name='do' value='go' />
</form>

<hr />

<form>
<div class="imagePreview">
   displays image here
</div>
( etc data this data not change )
 <div class="update">Default Data</div>
    <select name='selected' class="choose">
        <option value="3" imagePreview='/images/1.jpg'>3</option>
        <option value="4" imagePreview='0'>4</option>
       </select>
       <input type='hidden' name='do' value='go' />
</form>
A: 

You can find the elements that matter (.imagePreview and the <option>) relatively, like this:

$(function() {
  $('.choose').change(function(event) {
    var form = $(this).closest("form"),
        update = form.find(".update"),
        src = $(this).find("option:selected").attr("imagePreview");
    form.find(".imagePreview").html(src ? "<img src='" + src + "'>" : "");
    $.post('select-change-ajax2.php', form.serialize(), function(data) {
      update.html(data);
    });
  });
});

The key is changing $("option:selected") and $(".imagePreview") to be relative to the changes element, rather than selecting the first/all they find, respectively.

Before it was finding the first selected <option> in any <form> and all .imagePreview elements, not by using tree traversal we're finding the elements you want relative to the <select> (the this) that changed.

Nick Craver
Thank you again Nick it's working well u forgot some "var" and ";" ... so , i just put the new code from you again in the next answer :D
Choo
@Choo - You can declare multiple varibles at once with a comma, i'll change the indentation to make this more apparent.
Nick Craver
Thx again Nick :D
Choo
@Choo - welcome :)
Nick Craver
A: 

Working well ^^

Choo