Changing label text with javascript

Hi everybody

I am working with a CRM that is cloud based and so I dont have direct access to the code.

My problem is that I have form with several fields where I need to change the label text to different languages.

The form looks something like this:

<label>text1</label>

<input name="field1" id="field1" value="" size="50" maxlength="255" onchange="inputChanged=true;;" autocomplete="off" type="text">

<label>text2</label>

<input name="field2" id="field2" value="" size="50" maxlength="255" onchange="inputChanged=true;;" autocomplete="off" type="text">

The labels have no id, and I cant give them one either. So how do I go around this?

My primary thought was something very simple like this:

<label id="text1"></label>
<script>
  document.getElementById('text1').innerHTML = 'newText';
</script>

But I have no id :frowning:

I am noob at javascript, so i dont know if this can be accomplished.

You can use previousElementSibling from the input to gain access to the label. The form does have a unique identifier, doesn’t it?

var form = document.querySelector("#myForm");
var label1 = form.elements.field1.previousElementSibling;
var label2 = form.elements.field2.previousElementSibling;

The form does not have a unique identifier, but I would have to double check tomorrow.

If it does have an identifier I will for sure try your suggestion.

Thank you for trying to help!

It it doesn’t, you can use a querySelector to get the first form on the page, or figure out some other way to reference the appropriate form.

var form = document.querySelector("form");

The <label>s don’t have “for” attributes so they can be used as targets for their corresponding inputs?

1 Like

He can’t do much about that.

2 Likes

I tested the code and it works, but not when I try to implement it. It should be simple, but there must be something that interfers.

Thank you for your time!

I got it working now! Juhuuu! :slight_smile:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.