user3732216
user3732216

Reputation: 1589

Merging Code with jQuery

Isn't there a better way to write this piece of code? In a way I could create the button add adding it to the filter div class with the additional css and on click functionality?

$('.dataTables_filter').parent().append('<button class="btn btn-primary" id="addnew">Add New</button>');

$('#addnew').css('margin-right', '20px').css('margin-bottom', '5px').css('float', 'right').on('click', function(e) {
    e.preventDefault();
    window.location.replace(window.location.href + '/create');
});

Upvotes: 0

Views: 36

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

Firstly, css() accepts an object, so you can add multiple properties in a single call:

$foo.css({
    'margin-right': '20px',
    'margin-bottom': '5px',
    'float': 'right'
});

However this is still not ideal as it means you have CSS logic in your JS code. The best solution is to set the rules to a CSS class, and add/remove that class as required:

.foo {
    margin-right: 20px,
    margin-bottom: 5px,
    float: right;
}
$foo.addClass('foo');

With regard to your first issue, you can create the button element dynamically and create its' click handler immediately, like this:

var $button = $('<button />', { class: 'btn btn-primary', id: 'addnew', text: 'Add New' }).click(function(e) {
    e.preventDefault();
    window.location.replace(window.location.href + '/create');
}).appendTo($('.dataTables_filter').parent());

Alternatively you could add the click event on load of the document using a delegated event handler, instead of when the button is created:

// on load
$('.dataTables_filter').parent().on('click', '#addnew', function(e) {
    e.preventDefault();
    window.location.replace(window.location.href + '/create');
});

Upvotes: 2

bastos.sergio
bastos.sergio

Reputation: 6764

I guess you can trim down your code to this:

$('.dataTables_filter').parent().append(
    '<button class="btn btn-primary" style="margin-right: 20x; margin-bottom: 5px; float: right;" onclick="window.location.replace(window.location.href + \"/create\"); return false" id="addnew">Add New</button>'
);

Upvotes: 1

Related Questions