$(function () { $('.button-checkbox').each(function () { // Settings var $widget = $(this), $button = $widget.find('button'), $checkbox = $widget.find('input:checkbox'), color = $button.data('color'), settings = { on: { icon: 'glyphicon glyphicon-check' }, off: { icon: 'glyphicon glyphicon-unchecked' } }; // Event Handlers $button.on('click', function () { $checkbox.prop('checked', !$checkbox.is(':checked')); $checkbox.triggerHandler('change'); updateDisplay(); }); $checkbox.on('change', function () { updateDisplay(); controlPrice(); }); function controlPrice(){ var isChecked = $checkbox.is(':checked'); if (isChecked) { $('#erp').val($('#erpVal').val()); var precio = parseFloat($('#TotalPriceValueBox').text().replace("€", "")) + parseFloat($('#erpVal').val()); precio = precio.toFixed(2); $('#TotalPriceValueBox').text(precio+'€'); } else { $('#erp').val(''); var precio = parseFloat($('#TotalPriceValueBox').text().replace("€", "")) - parseFloat($('#erpVal').val()); precio = precio.toFixed(2); $('#TotalPriceValueBox').text(precio+'€'); } } // Actions function updateDisplay() { var isChecked = $checkbox.is(':checked'); // Set the button's state $button.data('state', (isChecked) ? "on" : "off"); var string = $('#textERP').text(); if(isChecked){ var string = string.replace("Contratar por", "Quitar franquicia de"); } else { var string = string.replace("Quitar franquicia de", "Contratar por"); } console.log(string); $('#textERP').text(string); $button.find('.state-icon') .removeClass('glyphicon-unchecked glyphicon-check') .addClass('state-icon ' + settings[$button.data('state')].icon); // Update the button's color if (isChecked) { $button .removeClass('btn-default') .addClass('btn-' + color + ' active'); } else { $button .removeClass('btn-' + color + ' active') .addClass('btn-default'); } } // Initialization function init() { updateDisplay(); // Inject the icon if applicable if ($button.find('.state-icon').length == 0) { $button.prepend(' '); } } init(); }); });