5
\$\begingroup\$

I have a bootstrap modal which contains a form that I'm using to add a new record and update existing ones.

I have a button that runs a method (showReferenceModal()) for clearing the field before showing the modal. And another button that runs a method (loadReferencesDetails(referenceId)) for loading the details before showing the modal.

function showReferenceModal() {    
    ...
    $('#referenceId').val("");
    $('#name').val("");
    $('#addr').val("");
    $('#tel').val("");
    $('#updateInfo').html("");
    $('#modal').modal('show');
}

function loadReferencesDetails(referenceId) {    
    ...
    $.ajax({
        ...
        dataType: 'json'
    }).done(function(response) {
        $('#referenceId').val(response.referenceId);
        $('#name').val(response.name);
        $('#addr').val(response.addr);
        $('#tel').val(response.tel);
        var updateInfo = "";        
        ...
        $('#updateInfo').html(updateInfo);
        $('#modal').modal('show');
    });
}

Possible Improvements:

  1. Is there a better way to clear the fields all at once? Because when the form gets bigger, then the method to show the modal will be bigger too. It's okay for now, but I'm thinking about extensibility. I'm new to jQuery so I don't really know if there's a method to do this.

  2. For loading the details on the form. As you can see, the response from my Servlet returns a JSON with the same property name as the ID of the FIELD it belongs to. Maybe there's a shortcut for this too?

  3. By the way, I have multiple modals, which have their own set of these two methods. Any tip so I can just use a single method for different modals instead of creating their own showXXXModal() and loadXXXDetails()?

\$\endgroup\$
3
\$\begingroup\$

Good question,

you can clear all (visible) input elements like this:

$("input:text").is(":visible").val('');

In general, google queries are a gold mine here. Just google 'jQuery clear all text fields' and you will find a link to StackOverflow with several approaches.

You are correct that there are easier ways to get your response in the correct fields, something like this might work for you:

}).done(function(response) {
    Object.keys(response).forEach( function( field ){
      $('#'+field).val(response[field]);
    });
    var updateInfo = "";        
    ...
    $('#updateInfo').html(updateInfo);
    $('#modal').modal('show');
});

As for #3 you should look into libraries to that work for you. A number of folks have done all the heavy lifting for that already.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.