0

I am trying to have my console print the contents of an input field with a type of file. However, it's not doing this. It's actually behaving as though a form is being submitted, although there is no action attached to the form at this time. Can anyone explain why I'm unable to get the value of the desired field?

js

$("#submit").on("click", function(){
    var image = $("#dept_image").val();
    console.log(image);
})

html

<form enctype="multipart/form-data" method="post" id="departments" class="view">
    <fieldset>
        <label for="dept_name">Department Name:</label>
        <input type="text" name="dept_name" id="dept_name" />
    </fieldset>
    <fieldset>
        <label for="dept_image">Image:</label>
        <input type="file" name="dept_image" id="dept_image" />
    </fieldset>
    <button name="submit" id="submit">Submit</button>
</form>

1 Answers1

0

Prevent the default action by capturing the event and acting on it -

$("#submit").on("click", function(event){
    event.preventDefault(); // prevents the default action of the submit
    var image = $("#dept_image").val();
    console.log(image);
})

Nothing will be console logged from the submitting page because you are 'leaving' it to load a 'new' page (even though it is itself). Now you can ad AJAX to the function to do whatever submission action you would care to.

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119