0

I have multiple input type files. On default they are hidden and only first one is shown. When user selects file with the first input file the funcion below shows the next input type file by id. The problem is that it works only for first 2 change events and than it stops without errors.. How can I make it work for every next input file. Here is the function:

//first we hide all inputs
$('.imagediv').hide();
$('.imagediv:first').show();
var nextupload=$('.imagediv:first').attr('data');
nextupload=(parseInt(nextupload) + 1);

//this is the event
$(function() {
 $("input:file").change(function (){
   var nextf = $(this).attr('data');
   $('#input'+(nextupload)+'').show();
   alert('#input'+(nextupload)+'');
 });    
});

here is how html looks like:

<div class="imagediv" id="input2" data="2">
<input type="file" name="gallery_upload_2" data="gallery_upload_3" id="gallery_upload_2" />
</div>

and so on with the next input.. How to make it work for every next input change? Thanks

I made jsfiddle here: http://jsfiddle.net/Lbu3ksjh/1/

2
  • $("input:file") instead of this use $("#gallery_upload_2") Commented Dec 13, 2014 at 13:03
  • what will this change? I am not missing the event, it triggers well with $("input:file") , but only 2 times :) Commented Dec 13, 2014 at 13:06

2 Answers 2

2

You were missing the +1 part in the change-function:

$('input:file').change(function (){
   var nextupload = $(this).parent('.imagediv').attr('data');
    nextupload = (parseInt(nextupload) + 1);
   $('#input'+(nextupload)+'').show();
   alert('#input'+(nextupload)+'');
 });

I updated your fiddle:

Demo

Sign up to request clarification or add additional context in comments.

1 Comment

empiric, thanks, I succeeded my self with this: $(function() { $('.imagediv').hide(); $('.imagediv:first').show(); $("input:file").change(function (){ var nextf = $(this).attr('data'); $('#input'+(nextf)+'').next().show(); }); }); but stil I will vote and accept your answer, thanks !
2

Here's another solution. It works on a variable number of file inputs and doesn't require a lot of code nor markup.

DEMO

js

$(function() {
    var $fileInputs = $(':file[name*="gallery_"]'), // could be whatever
        next = 0;
  
    $fileInputs.not(':first').hide();

    $fileInputs.change(function (){
        $fileInputs.eq(++next).show();
    }); 
});

html

<input type="file" name="gallery_upload_1" />
<input type="file" name="gallery_upload_2" />
<input type="file" name="gallery_upload_3" />
<input type="text" name="random_text_input" />  
<!-- notice it only reveals file inputs -->
<input type="file" name="gallery_upload_4" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.