Change Label to Textbox on edit hyperlink click

前端 未结 5 1070
花落未央
花落未央 2020-12-05 09:01

I am new to ruby on rails and twitter bootstrap. Accept my apologize if my question sound dumb. I am using twitter bootstrap for my site design. I have been trying to use b

5条回答
  •  情话喂你
    2020-12-05 09:27

    I fiddled a litte more with Amyth's answer. This one just lets you click the text to edit it. You just need to add a class to any text element to enable the functionality. Enter key updates the text. Click outside the input to abort.

    HTML:

    Click to edit
    

    JS:

    $(document).ready(function() {
      $('.edit-on-click').click(function() {
        var $text = $(this),
          $input = $('')
    
        $text.hide()
          .after($input);
    
        $input.val($text.html()).show().focus()
          .keypress(function(e) {
            var key = e.which
            if (key == 13) // enter key
            {
              $input.hide();
              $text.html($input.val())
                .show();
              return false;
            }
          })
          .focusout(function() {
            $input.hide();
            $text.show();
          })
      });
    });
    

    JSFiddle

    Update (implementing AJAX to update db value):

    Here's how I ended up using it in practice: this uses data attributes on the original element for id, model, and field to update in an ajax request. (This is from a Django app using Bootstrap, so some lines might be obsolete for you depending on your setup.)

    HTML:

    Click to edit
    

    JS:

    function editOnClick(el) {
        var $text = $(el),
                $input = $('');
    
        $text.hide()
                .after($input);
    
        $input.val($.trim($text.html())).show()
                .tooltip({title:"press ENTER to save
    click outside to cancel", container:"body", trigger:'focus', html:true}) .focus() .keypress(function(e) { var key = e.which; if (key == 13) // enter key { $.ajax({ type: "POST", data: { value:$input.val(), obj_id:$text.attr('data-id'), obj_model:$text.attr('data-model'), obj_field:$text.attr('data-field'), csrfmiddlewaretoken:'{{ csrf_token }}' }, url: "{% url 'edit_on_click' %}", cache: false, dataType: "html", success: function(html, textStatus) { $input.hide(); $text.html(html) .show(); }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert('Error: ' + XMLHttpRequest.responseText) } }); return false; } }) .focusout(function() { $input.hide(); $text.show(); }) }

提交回复
热议问题