Milos Cuculovic
Milos Cuculovic

Reputation: 20223

How to get the value of an input element directly in the twig template

I have this form in my twig template:

<form id="search-box" action="/search" method="get">
    <input id="search-query" type="text" placeholder="Search..." name="search" role="textbox">
    <a id="search-btn" href="....."></a>
</form>

My goal is to use the value of the input id="search-query" to create the href for the a id="search-btn"

For this, I have to access the value of the input id="search-query".

I have tryed:

{{ form.search-query.value }}

and

{{ search-box.search-query.value }}

But none of those works. I am getting the error that form or search does not exists.

Any idea?

Upvotes: 0

Views: 7301

Answers (2)

Florian Klein
Florian Klein

Reputation: 8915

you should use {{ form.search-query.all.value }}

Upvotes: 1

Dimitris Damilos
Dimitris Damilos

Reputation: 2438

In general, you can do this with jQuery:

var given_val = '';
var wanted_href = '';
given_val = $('input#search-query').val();
wanted_href = 'http://www.example.com/' + given_val;
$('a#search-btn').attr('href',wanted_href);

Upvotes: 3

Related Questions