Reynier
Reynier

Reputation: 2478

Changing the right element

I have this HTML code:

<div class="custom-input-file product-left">
    <input type="file" class="input-file" name="mediabundle_mediatype[file]" id="picture_1">
    <div class="archivo">Seleccionar ...</div>
    <img style="display:none" alt="your image" src="#" id="picPreview1">
</div>

<div class="custom-input-file product-left">
    <input type="file" class="input-file" name="mediabundle_mediatype[file]" id="picture_2">
    <div class="archivo">Seleccionar ...</div>
    <img style="display:none" alt="your image" src="#" id="picPreview2">
</div>

<div class="custom-input-file product-left">
    <input type="file" class="input-file" name="mediabundle_mediatype[file]" id="picture_3">
    <div class="archivo">Seleccionar ...</div>
    <img style="display:none" alt="your image" src="#" id="picPreview3">
</div>

<div class="custom-input-file product-left">
    <input type="file" class="input-file" name="mediabundle_mediatype[file]" id="picture_4">
    <div class="archivo">Seleccionar ...</div>
    <img style="display:none" alt="your image" src="#" id="picPreview4">
</div>

<div class="custom-input-file product-left">
    <input type="file" class="input-file" name="mediabundle_mediatype[file]" id="picture_5">
    <div class="archivo">Seleccionar ...</div>
    <img style="display:none" alt="your image" src="#" id="picPreview5">
</div>

And I need to run the same jQuery code for each but of course changing the ID of the elements. This is the code I made:

$("#picture_1, #picture_2, #picture_3, #picture_4, #picture_5").change(function() {
    readURL(this);
    $(this).parent().find(".archivo").html("Cambiar imagen");
}).css('border-width', function() {
    if (navigator.appName == "Microsoft Internet Explorer")
        return 0;
});

$(".document-file input:file").change(function() {
    $(this).parent().find(".file").html($(this).val());
}).css('border-width', function() {
    if (navigator.appName == "Microsoft Internet Explorer")
        return 0;
});

But don't know how to iterate trough elements and change the one I'm changing, any help?

Upvotes: -1

Views: 59

Answers (1)

Darm
Darm

Reputation: 5659

Just replace

$("#picture_1, #picture_2, #picture_3, #picture_4, #picture_5")...

by

$(".input-file").change(function() {
    readURL(this);
    $(this).parent().find(".archivo").html("Cambiar imagen");
    $(this).parent().find(".file").html($(this).val());
}).css('border-width', function() {
    if (navigator.appName == "Microsoft Internet Explorer")
        return 0;
});

It now uses class selector (http://api.jquery.com/class-selector/).

Upvotes: 1

Related Questions