william
william

Reputation: 606

check filename before posting using jquery/ php

I need jquery to check if my posted filename (up_image) is empty or not.

if it's empty i need a div tag to be shown and come with some kind of alert message.

if not, just do the

$("#submit").submit();
    <form action="/profile/" method="post" enctype="multipart/form-data" id="submit">
    <p>
        <label for="up_image">image:</label>
        <input type="file" name="up_image" id="up_image" />     
    </p>
    <a href="javascript:;" id="post_submit" class="submit_btn">Upload</a>
</form>

Upvotes: 1

Views: 545

Answers (2)

bobince
bobince

Reputation: 536469

1: use a standard submit button to submit your form rather than a javascript-dependent link, for accessibility reasons, and to prevent brokenness if someone tries to right-click-open-in-new-window or other similar action on the link. If you want it to look like a link, you can still use a button, just apply some CSS to make it no longer look like a button.

2: use the form.onsubmit event to do validation rather than relying on a submit button click (forms can also be submitted by pressing enter, which may not always generate a button click)

<form id="uploadform" method="post" action="/profile/" enctype="multipart/form-data">
    <p>
        <label for="up_image">image:</label>
        <input id="up_image" type="file" name="up_image" />
    </p>
    <p>
        <input type="submit" value="Upload" />
    </p>
</form>
<script type="text/javascript">
    $('#uploadform').submit(function(e) {
        if ($('#up_image').val()=='') {
            alert('Please choose a file to upload.');
            e.preventDefault();
        }
    });
</script>

Upvotes: 0

Josh Stodola
Josh Stodola

Reputation: 82483

$(function() {
  $("#post_submit").click(function() {
    var fil = $("#up_image");
    if($.trim(fil.val()).length == 0) {
      alert("Choose a file!");
      fil.focus();
      return false;
    }

    $("#submit").submit();
  });
});

Upvotes: 2

Related Questions