0

I have a hidden input field:

<input type="hidden" id="entity__token" name="entity[_token]" value="SOMEVALUE" />

In my HTML the value of 'entity' in the attributes name and id could be anything, for example:

<input type="hidden" id="example__token" name="example[_token]" value="SOMEVALUE" />

I try to get the value of any kind of input field where the id ends with __token.

After reading this question I tried:

var hiddenField = document.querySelector("[id^='__token']");
console.log(hiddenField.value);

That didn't work. I am looking for a solution without any jQuery.

Dirk J. Faber
  • 4,360
  • 5
  • 20
  • 58
  • 1
    Can you show how an actual name would look like? – Luca Kiebel Jun 17 '19 at 13:01
  • 2
    The attribute selector you tried, `"[id^='__token']"`, selects elements whose `id` *starts* with the string you supplied. You're looking to identify elements whose `id` *ends* with that string: `"[id$='__token']"` – David Thomas Jun 17 '19 at 13:02
  • @LucaKiebel, anything like `id="some__token" name="some[_token]"` where 'some' can change. David's comment together with his comment of Roy's answer is of great help. – Dirk J. Faber Jun 17 '19 at 13:12
  • @DavidThomas unless you're struggling to find a duplicate that you're sure is there, I don't see why you shouldn't post your comment as an actual answer. – Federico klez Culloca Jun 17 '19 at 13:12

1 Answers1

0

* would work!

var hiddenField = document.querySelector("[id*='__token']");
console.log(hiddenField.value);
<input type="hidden" id="entity__token" name="entity[_token]" value="TtoNGqMMgMybh-JVttVSVWAOnyYe6s9eRnSOaBujtAE" />

[attribute^=value]

Matches if the element has the given attribute whose value starts with the provided string.

vs.

[attribute*=value]

Matches if the element has the given attribute whose value contains the provided string.

Roy Bogado
  • 4,299
  • 1
  • 15
  • 31