user2609980
user2609980

Reputation: 10504

How to change label text via JavaScript/jQuery after click on HTML form

I am looking for a way to change the text under a name form element on a squarespace.com site. This is a website that helps you build websites, but you cannot change the source code yourself. You can, however, inject JavaScript.

I know the id of the two elements I want to change. Looking from the developer tools I see the elements are labels and have an input field with a string underneath as follows:

<label id="theLabel1">
<input type="text"></input>

"First Name"
</label>

The HTML above only appears after having clicked an element with class name "theClickedClass".

While injecting the following code (with jQuery available):

<script type="text/javascript">
$(function() {
    $('.theClickedClass').click(function() {
        $('#theLabel1').text("THE NEW TEXT");
    });
});
</script>

The HTML stays exactly the same as above.

I know that the clicked function works since I put a console.log there. Adding a wait period (to wait for the label to actually exist) does not make a difference.

I don't know why it does not work. Does anyone else have an idea how the text in the label can be changed?

Thanks.

Upvotes: 1

Views: 13526

Answers (2)

fozzeuh
fozzeuh

Reputation: 41

I give you this JSfiddle. It changes the value after the input.

With this code you can change the value you want:

$('#theLabel1')[0].lastChild.textContent = 'THE NEW TEXT';

http://jsfiddle.net/xggbz60o/1/

Upvotes: 1

Dejo Dekic
Dejo Dekic

Reputation: 2126

I think you are looking something like this :)

<label id="theLabel1">
<input class="my-text" type="text"></input>
"First Name"
</label>



$(document).ready(function(){
 var field = $('.my-text');
   $('#theLabel1').click(function() {
      $("#theLabel1").text('hello there');
      field.insertBefore('#theLabel1');          
});
});

Fiddle here

Upvotes: 2

Related Questions