Reputation: 46
I tried this code but it still submit the form even the input has not been validated yet.
Here is the code for my form:
<a style="cursor: pointer;" id="upload_image">Upload Image</a></li>
<?php
$attributes = array('id' => 'upload_form');
echo form_open_multipart('c=web_page&m=upload_img', $attributes);
?>
<input type='file' style="display:none;" name="photosubmit" id="photosubmit"/>
<?php echo form_cose(); ?>
Here is the code for my jQuery:
$("#upload_image").click(function(){
$("#photosubmit").click();
if( $('photosubmit').val() != "") //
$("#upload_form").submit();
});
so here is my question:
How will I ensure that before I submit this form, my input has already a value..?
Upvotes: 1
Views: 251
Reputation: 796
If you want to get the element by id you should do this:
if( $('#photosubmit').val() != "")
instead of:
if( $('photosubmit').val() != "")
Updated answer:
With help of the jQuery API documentation, I found a fully working solution:
$("#the_form").submit(function(event) {
if ( $( "input:first" ).val() !== "" ) {
alert("The file input is valid.");
return;
}
alert("The file input is not valid.")
event.preventDefault();
});
https://jsfiddle.net/christianheinrichs/nbuzoxLv/2/
Upvotes: 3
Reputation: 46
After one day of research, I tried this one and it works. It will only submit the form once you have made any changes to the file input type form(e.g you want to upload new file).
$("#upload_image").click(function () {
$("#photosubmit").click().change(function(){
$("#upload_form").submit();
});
});
I hope it will help someone in the future.
Upvotes: 0
Reputation: 1914
You are missing an # in your code, it has to be:
$("#upload_image").click(function(){
$("#photosubmit").click();
if( $('#photosubmit').val() != "")
$("#upload_form").submit();
});
Also, is the #upload_image click event, the right event to check if your input[type="file"] is filled?
Upvotes: 0
Reputation: 291
Check what is returned:
$("#photosubmit").val()
If returns null
that is different from empty string.
Try this:
if ($("#photosubmit").val()) {
$("#upload_form").submit();
}
Upvotes: 0
Reputation: 57095
Try
$("#upload_image").click(function (e) {
e.preventDefault();
if ($("#photosubmit").val() != "")
^ //added # here
$("#upload_form").submit();
});
References
Upvotes: 0