JavaScript / jQuery selector value function I have the following function which opens a modal and puts some value into a div. It works but the function looks ugly, I hope for improvements (maybe more dynamic).

submitDelete: function() {

    // projects
    $('button[name="removeProj"]').on('click', function(e){
        var $form      = $(this).closest('form'); // closest parent form
        var $id        = $(this).data('id');
        var $title     = $(this).data('title');
        var $createdAt = $(this).data('created-at');
        var $updatedAt = $(this).data('updated-at');
        e.preventDefault();
        if($id != '') {
            $("#prodId").empty().append($id);
        } else {
            $("#prodId").empty().append('-');
        }
        if($title != '') {
            $("#prodTitle").empty().append($title);
        } else {
            $("#prodTitle").empty().append('-');
        }
        if($createdAt != '') {
            $("#prodCreatedAt").empty().append($createdAt);
        } else {
            $("#prodCreatedAt").empty().append('-');
        }
        if($updatedAt != '') {
            $("#prodUpdatedAt").empty().append($updatedAt);
        } else {
            $("#prodUpdatedAt").empty().append('-');
        }
        $('#confirm').modal({ backdrop: 'static', keyboard: false })
        $('#delete').click(function() {
            $form.trigger('submit'); // submit the form
        });
    });
In JavaScript you can do this:

var example = someValue || 'fallbackValue';


if someValue does not have a value, example=='fallbackValue', otherwise it'll be whatever value someValue has; You can integrate this in your code.

// You can now replace this:
if($id != '') {
    $("#prodId").empty().append($id);
} else {
    $("#prodId").empty().append('-');
}
// With this:
$("#prodId").empty().append( $(this).data('id') || '-') 
// Or just set it directly:
$("#prodId").val( $(this).data('id') || '-') 


Resulting in:

submitDelete: function() {

    // projects
    $('button[name="removeProj"]').on('click', function(e){
        e.preventDefault();
        var $form      = $(this).closest('form'); // closest parent form

        $("#prodId").val(        $(this).data('id') || '-'); 
        $("#prodTitle").val(     $(this).data('title') || '-');
        $("#prodCreatedAt").val( $(this).data('created-at') || '-');
        $("#prodUpdatedAt").val( $(this).data('updated-at') || '-'); 

        $('#confirm').modal({ backdrop: 'static', keyboard: false })
        $('#delete').click(function() {
            $form.trigger('submit'); // submit the form
        });
    });
}


*Instead of .val() you can use .text() or .html() to set the values of other types of elements like divs.