开发者

jQuery Tabs - jquery script only works for 1st tab - bad initialize?

I have jQuery Tabs in w开发者_如何学Pythonhich each tab and corresponding content are populated by a PHP foreach loop.

For each tab the user can upload a picture. I have this setup in a way so that as soon as the user chooses a file, a jquery script makes the upload begin automatically -- and the browse button is hidden and replaced by "Uploading your picture".

Here is the code (CI markup):

<ul class="tab_header">
    <?php foreach ($p as $row):
        echo '<li>
            <a href="#tabs-'. $row->p_id . '">' . $row->p_name . '</a>
               </li>'; 
        endforeach; ?>
</ul>
<?php foreach ($p as $row): ?>
    <div id="tabs-<?php echo $row->p_id; ?>">

        <?php echo form_open_multipart('/p/p_upload_picture/' . $row->p_id, 'id="upload_form"');
        echo form_upload('userfile', '', 'id="file_select"');
        echo form_hidden('upload','upload');
        echo form_close(); ?>
         <div id="loading" style="display:none;">
            Uploading your picture...
         </div>     
</div>

<?php endforeach; ?>

<script>
$(function(){
    $("#file_select").change(function(){
        $("#upload_form").submit();
        $("#upload_form_div").hide();
        $("#loading").show();
    });
});
</script>   

This works perfectly but only on the first tab.

In all other tabs, the jquery script doesn't run -- as soon as I choose a file, the file name is shown in the browse button field instead, and no upload happens (form isn't submitted).

I wonder if this has to do with the script not being initialized for the other tabs.

How can I fix this?

Thanks for helping, much appreciated.


Your field has an id. Which should be unique per element.

jQuery only returns the first element it encounters with the given id, that's why your code isn't working. I would suggest adding a class instead of an id to your field.

$('.class-of-field')..change(function() {
    ..
});

The above should do the job.

This would be the equivalent code without jQuery:

var el = document.getElementById('file_select');

Which only returns one element, have a look at the documentation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜