1

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..?

McPhelpsius
  • 253
  • 1
  • 4
  • 16
Zhul
  • 46
  • 1
  • 8

5 Answers5

3

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/

Christian Heinrichs
  • 786
  • 1
  • 9
  • 28
0

Try

$("#upload_image").click(function (e) {
    e.preventDefault();
    if ($("#photosubmit").val() != "") 
           ^ //added # here
    $("#upload_form").submit();
});

References

event.preventDefault

Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
  • still not working man, aside from .val() function, is there any other method that i can use to ensure that my input file has been set? – Zhul Oct 01 '13 at 16:55
  • i think the file input has already a value before it is clicked. – Zhul Oct 01 '13 at 18:36
0

Check what is returned:

$("#photosubmit").val()

If returns null that is different from empty string.

Try this:

if ($("#photosubmit").val()) {
    $("#upload_form").submit();
}
maketest
  • 281
  • 1
  • 8
0

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?

veelen
  • 1,916
  • 19
  • 26
0

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.

Zhul
  • 46
  • 1
  • 8