Ekta Shukla
Ekta Shukla

Reputation: 480

How to convert label to textbox?

Hi I want to convert label field to textbox on image click event. My html file is

<div>
    <div id="tagCust">Customer Details<img src="images/edit.png" class="alignright"/></div>
</div>

<div id="contactdetail">
    <div id="contactInfo">
        <label for="emailid" class="contactText" data-inline="true">Email Id*</label>
    </div>
         <label for="mobileno" class="contactText" data-inline="true">Mobile No.</br></label>
         <label for="custid" class="contactText" data-inline="true">Customer Id.</label>
</div>

I want to convert the mobileno and the emailid labels to textboxes, when the user clicks on edit image. How can I do that?

Upvotes: 1

Views: 7653

Answers (2)

Dominic Green
Dominic Green

Reputation: 10260

I would suggest the code below or at http://jsfiddle.net/qAZZc/ also i would not remove the label for accessibilty reasons better to append an input and hide the label.

$("label").each(function(){
        if(($(this).attr("for") == "emailid")||($(this).attr("for") == "mobileno")){
           $(this).after("<input type='text' id='"+ $(this).attr("for") +"'/>");
           $(this).hide();
        }
    });

Its also better to add a unique id or class to your button or else .alignright every where will fire your function

Upvotes: 0

jAndy
jAndy

Reputation: 235972

You cannot really "convert" it, but you can either .replaceWith() the label html, or .hide() and .show() it.

For instance:

$('.alignright').on('click', function() {
    $('label.contactText').slice(0,2).each(function() {
        $(this).replaceWith( '<input type="text"/>' );
    });
});

.replaceWith can also address a node reference instead HTML strings. However, this would work in a destructive manner and only makes sense if you don't need to show your labels ever again. Otherwise, create those <input> elements the same time you create your <label> nodes, just give them the CSS style display: none. On click, you can either switch those styles (none to block and vice versa) or switch classes.

Upvotes: 4

Related Questions