简体   繁体   中英

how to change/edit value of label with jquery/javascript?

i have a standart html label with value:

<label id="telefon" value="101"></label>

i like to edit this value by clicking on the label and enter on the appeared textbox new value (like value="202" ).

how can i do such a tricky thing?

i tried it with JQuery function, but it really dont wont to work:

$(function() {

  $('a.edit').on("click", function(e) {
    e.preventDefault();
    var dad = $(this).parent().parent();
    var lbl = dad.find('label');
    lbl.hide();
    dad.find('input[type="text"]').val(lbl.text()).show().focus();
  });

  $('input[type=text]').focusout(function() {
    var dad = $(this).parent();
    $(this).hide();
    dad.find('label').text(this.value).show();
  });

});

http://jsfiddle.net/jasuC/ , Since you didnt provide the markup, take a look into this working example

$(document).on("click", "label.mytxt", function () {
    var txt = $(".mytxt").text();
    $(".mytxt").replaceWith("<input class='mytxt'/>");
    $(".mytxt").val(txt);
});

$(document).on("blur", "input.mytxt", function () {
    var txt = $(this).val();
    $(this).replaceWith("<label class='mytxt'></label>");
    $(".mytxt").text(txt);
});

You don't need the jquery.

To made almost all tag elements editable set the contentEditable to true .

So, you can change using the default features of a HTML.

// You can add an event listener to your form tag and code the handler which will be common to all your labels ( Fiddle HERE )

// HTML

<form id="myform">
    <label style="background-color:#eee" title="101">Value is 101<label>
</form>

// JS

$(function(){
    $('#myform').on('click',function(e){
        var $label = $(e.target), $form = $(this), $editorInput = $('#editorInput'), offset = $label.offset();
        if($label.is('label')){
            if( !$editorInput.length){
                $editorInput = $('<input id="editorInput" type="text" value="" style="" />').insertAfter($label);
            }
            $editorInput.css('display','inline-block')
                .data('editingLabel', $label.get(0))
                .focus()
                .keydown(function(e){
                    var $l = $($(this).data('editingLabel')), $t = $(this);
                    if(e.which == 13){
                        $l  .attr('title', $t.val().replace(/(^\s+)|(\s+$)/g,''))
                            .text('value is now ' + $l.attr('title'));

                        // UPDATE YOUR DATABASE HERE

                        $t.off('keydown').css('display','none');
                        return false;
                    }
                });
        }
    });
});

// A bit of CSS

#editorInput{display:none;padding:2px;border:1px solid #eee;margin-left:5px}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM