Meteor: Most “Meteoric” way to clear form fields

大憨熊 提交于 2019-12-22 10:44:59

问题


I'm working on an example CRUD application with Meteor.js and am not sure how best to empty out the fields of a form. I need it in two places: when the Submit button is clicked, and when the Cancel button is clicked.

I implemented it this way by creating a utility function called clearFormFields() that just uses jQuery to empty their contents, but it doesn't feel as "Meteoric" as it should; I feel it should be scoped better so it doesn't have a global visibility. What am I doing wrong?

function clearFormFields() {
        $("#description").val("");
        $("#priority").val("");    
}

Template.todoNew.events({
    'click #cancel': function(event) {
        event.preventDefault();
        Session.set('editing', false);
        clearFormFields();
    },

    'submit form': function(event) {
        event.preventDefault();
        var theDocument = {
            description: event.target.description.value,
            priority: event.target.priority.value               
        };
        if (Session.get("editing")) {
            Meteor.call("updateTodo", theDocument, Session.get('theDocumentId'))
        }
        else {
            Meteor.call("insertTodo", theDocument);            
        }        
        Session.set('editing', false);        
        clearFormFields();            
        /* Could do this twice but hate the code duplication.
        description: event.target.description.value = "";
        priority: event.target.priority.value = "";
        */
    }
});

回答1:


You could use the native reset method of the DOM form node ?

"submit form":function(event,template){
  event.preventDefault();
  // ...
  template.find("form").reset();
}

http://www.w3schools.com/jsref/met_form_reset.asp




回答2:


The DOM object that originated the event can be accessed and reset from through event.target.reset();

"submit form":function(event){
   event.preventDefault();
   //...
   event.target.reset();
}

http://docs.meteor.com/#/full/eventmaps



来源:https://stackoverflow.com/questions/27419653/meteor-most-meteoric-way-to-clear-form-fields

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!