1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- console.clear();
- 'use strict';
- function validateText(value) {
- return value !== '' ? true : false;
- }
- function sendToServer(value) {
- console.log('Send to server', value);
- }
- $('body').on('click', '[editable]', function(event){
- event.preventDefault(); // сбросили поведение элементов по молчанию, если была бы ссылка она бы не работала (защита от дурака)
- var $element = $(this);
- var type = $element.attr('editable');
- var $firstButton = $('#firstButton');
- var $secondButton = $('#secondButton');
-
- $firstButton.show();
- $secondButton.show();
- function hideButton(){
- $firstButton.hide();
- $secondButton.hide();
- }
- var events = {
- before: $element.attr('onbeforesave') ? $element.attr('onbeforesave') : null,
- after: $element.attr('onaftersave') ? $element.attr('onaftersave') : null
- };
- function onEdit() {
- $element
- .text( $(this).val() )
- .insertAfter(this);
-
- events.after && window[events.after]( $(this).val() );
- $(this).remove();
- }
- var $inp = $('<input>')
- .attr('type', type)
- .val( $element.text() )
- .insertAfter($element)
- .focus()
- .select()
- .after( $secondButton )
- .after( $firstButton );
- $inp
- .on('keyup', function(event) { // обработчик событий на элементе и проверяем клавиши 13 -энтер, 27 -эск
- if (event.which === 13) {
- if (events.before) {
- var valid = window[events.before]( $(this).val() );
- if (valid) {
- onEdit.call(this);
- hideButton();
- }
- } else {
- onEdit.call(this);
- hideButton();
- }
-
- } else if (event.which === 27) { //27 код клавиши esc
- $element.insertAfter(this);
- $(this).remove(); // ремув удаляет обработчик событий вместе с элементом
- hideButton();
- }
- })
- $element.remove();
- $firstButton.one('click', function() {
- onEdit.call($inp);
- hideButton();
- event.stopPropagation();
- })
- $secondButton.one('click', function() {
- $element.clone().insertAfter($inp.val( $element.text() ) );
- $inp.remove(); // ремув удаляет обработчик событий вместе с элементом
- event.stopPropagation();
- hideButton();
- })
- })
|