iyal
iyal

Reputation: 1285

change image source on submit

I want to change image source in innerHtml data when the submit button is clicked.

<div id="areaEditor">
    <div class="holder">
        <img src="blob.blob"/>
        <input class="filesss" type="file" value="one.jpg"/>
    </div>

    <div class="holder">
        <img src="blob.blob"/>
        <input class="filesss" type="file" value="two.jpg"/>
    </div>

    <div class="holder">
        <img src="blob.blob"/>
        <input class="filesss" type="file" value="three.jpg"/>
    </div>
</div>


$('#newsButton').click(function(e){
    e.preventDefault();
    alert("klik");

    var source = $(".holder").find(".filesss").val();
    var imageTag = $(".holder").find("img").attr("src",source);
    var htmlData = $("#areaEditor").html();

    alert(htmlData);

})

However, the htmlData I alert there only shows me that the img src for the all three image tags is one.jpg.

How to make it corrects so that the image src is based on each the closest input file there?

Many thanks for the help.

Upvotes: 0

Views: 95

Answers (2)

Rabea
Rabea

Reputation: 2034

The idea is to loop over the elements so it can take a single value each time, in your case; you are telling JQuery to get the source from the class holder which it finds it in the first element, so it does not need to look for anything else.

So you can do something like:

    <div id="areaEditor">
        <div class="holder">
            <img src="blob.blob"/>
            <input class="filesss" type="file" value="one.jpg"/>
        </div>

        <div class="holder">
            <img src="blob.blob"/>
            <input class="filesss" type="file" value="two.jpg"/>
        </div>

        <div class="holder">
            <img src="blob.blob"/>
            <input class="filesss" type="file" value="three.jpg"/>
        </div>
    </div>
  <script>  
    $('#newsButton').click(function(e){
        e.preventDefault();
        alert("klik");

        $(".holder").each(function() {
            var source = $(this).find(".filesss").val();
            $(this).find("img").attr("src",source);
        });

        var htmlData = $("#areaEditor").html();
        alert(htmlData);
    })
</script>

Upvotes: 1

taxicala
taxicala

Reputation: 21769

You have many .holder elements, you should loop them and get the .filesss value for each one and replace the image src as follows:

$('#newsButton').click(function(e){
    e.preventDefault();
    alert("klik");

    $(".holder").each(function() {
        var source = $(this).find(".filesss").val();
        $(this).find("img").attr("src", source);
    });

    var htmlData = $("#areaEditor").html();
})

Upvotes: 1

Related Questions