Reputation: 5303
I have an input field which is in the type "file".
<input type="text" name="fake_section" class="fake_section"><button class="fake_section">Choose Photo</button>
<input type="file" style="display:none;" name="file" id="file" value="Choose Photo" accept="image/png,image/jpeg" />
<input type="submit" name="submit" value="Submit" />
And i use the following css
input[type="file"] {
width:50%;
height:25px;
border-radius:2px;
display:inline-block;
border:thin solid #ddd;
}
i got my output like following
But actually i want the output like,
Another problem is that i only want to choose the "jpeg and png" image files, but this input field accept all the file type. And i try this in both the browsers Firefox and Chrome
Upvotes: 0
Views: 5053
Reputation: 46629
To answer the second question, you can choose which files appear in the open box by using the accept
attribute on the input
.
See the official W3C reference.
Note, however, that the page suggests you can choose png and jpeg files by using accept="image/png,image/jpeg"
, and that will not work in all browsers. Only in Chrome actually. So it's better to put accept="image/*"
(for all image files) which does work in the majority of browsers.
Fiddle here.
You also had troubles with the submit button, but that was caused by the fact that <input type="button">
is not the same as <button>
. One doesn't submit, the other does.
Here is a quick list for reference.
<input type="submit">
submits
<input type="button">
doesn't submit
<button type="submit">
submits
<button type="button">
doesn't submit
<button>
submits
Upvotes: 1
Reputation: 9782
<input type="text" name="fake_section" class="fake_section">
<input type="button" class="fake_section" value="Choose Photo"/>
<input type="file" style="display:none;" name="file" id="file" value="Choose Photo" accept="image/png,image/jpeg" />
<input type="submit" name="submit" value="Submit" />
JS
$('.fake_section').click(function(e){
e.preventDefault();
$('#file').trigger('click');
});
$('#file').change(function(e){
var filename = $(this).val();
var ext = filename.split('.').pop().toLowerCase();
if( $.inArray( ext, ['gif','jpg','jpeg'] ) == -1 ){
alert('not valid!');
}
else{
$('input[name="fake_section"]').val(filename);
}
});
Try like this
http://jsfiddle.net/jogesh_pi/5WcFj/2/
Upvotes: 2
Reputation: 15387
Try this to validate the file
var ext = $('#file').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['gif','png','jpg','jpeg']) == -1) {
alert('invalid extension!');
}
Upvotes: 1