Form Data output is disappearing

时间:2015-07-08 15:39:34

标签: javascript jquery forms post form-submit

I'm having a problem with this form. I want it to return the values it got into the <p> tag below when submit is clicked, however, these values stay for a fraction of a second before disappearing. I was wondering how I could get the text to remain under the <p> tag.

<form method="POST">
        <div><span class="padded20">Select Announcement Title:</span> <input type="text" id="title" value="default title"></div>
     <div><span class="padded20">Select Announcement Here:</span> <input type="file" id="file"></div>
      <div><span class="padded20">Select Announcement Date:</span> <input type="date" id="date" value="2000-01-01"></div>
      <div class="padded220"><input type="submit" value="Submit Announcement"> </div>
    </form>


    <script>
     $(function() {
     $("form").submit(function() {
        if ($("#title") != null && $("#file") != null && $("#date") != null) {
             $("#displayAnnouncement p").html($("#date").val() + ' ' + $("#title").val() + ' ' + $("#file").val()); 
        return; 
        }
     });
     });

    </script>
    <div id="displayAnnouncement"><p></p></div>

3 个答案:

答案 0 :(得分:0)

When you submit the form, you submit it to the same page.
That way, the page is reloaded. Subsequently, your form appears reset, and so does your result.

You can avoid this either using preventdefault or by not submitting the form. In the latter case you would not use the form's submit event, but for example the button's clickevent.

答案 1 :(得分:0)

when you submit a form, it automatically refreshes the page, so that's why it's there for a split second then disappears. If you are actually using php to do something with this data, you need to set a php variable to go inside the p tag. if you're not using php, then get rid of your $("form").submit(function() {

and do this instead...

  $(function() {
        if ($("#title") != null && $("#file") != null && $("#date") != null) {
             $("#displayAnnouncement p").html($("#date").val() + ' ' + $("#title").val() + ' ' + $("#file").val()); 
        return; 
        }
     });

答案 2 :(得分:0)

You need to get the values of the ID's you're using in the if statement. Also, input type file value is "" when no file is chosen. I adjusted your code to use button instead of submit type and run the function on click event listener.

http://jsfiddle.net/2a0jjb8t/

if ($("#title").val() != null && $("#file").val() != "" && $("#date").val() != null) {
         $("#displayAnnouncement p").html($("#date").val() + ' ' + $("#title").val() + ' ' + $("#file").val()); 
    return;
}