Viraj Dhamal
Viraj Dhamal

Reputation: 5325

Set label text using Jquery

I want to set label text using Jquery. Problem is that label contain text box. Whenever i set label text , textbox within the label get removed. The label code is given below-

<label> Search:<input id="search" type="text" ></label>

and i am trying to set label with JQuery code given below-

 <script type="text/javascript">
        $(document).ready(function() {  
            $("#search").parent().append("some Text");                      
        });
</script>

Upvotes: 0

Views: 887

Answers (4)

Swapnil Deo
Swapnil Deo

Reputation: 281

try this:

<label id="lab"> Search:<input id="search" type="text"></label>
     <button>change label</button>

 $('button').on('click' ,function(){
   var input = $("#search");
   $("#lab").text("some Text").append(input);
 })

Upvotes: -1

Rory McCrossan
Rory McCrossan

Reputation: 337560

You can use contents() to get the nodes within the element, and filter to specifically retrieve the textNodes. With that in mind, this will work for you:

$("#search").closest('label').contents().filter(function () {
    return this.nodeType == 3;
}).first()[0].nodeValue = 'Some text:';

Example fiddle

Alternatively, if you change your HTML structure to place a span around the label text you can simplify the code a lot:

<label> 
    <span>Search:</span>
    <input id="search" type="text" />
</label>
$("#search").siblings('span').text('Some text:');

Upvotes: 1

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

Try this :

<script type="text/javascript">
        $(document).ready(function() {
            //get clone copy of input  
            var $input = $("#search").clone();                      
            //replace text in parent  
            var $parent = $("#search").parent();
            $parent.text("some Text");
            //append input again
            $parent.append($input);
        });
</script>

Demo

Upvotes: 1

Yann86
Yann86

Reputation: 1017

var input = $("#search");
$("#search").parent().text("some Text").append(input);

http://jsfiddle.net/yann86/ez15fuy1/

Upvotes: 2

Related Questions