Mattia
Mattia

Reputation: 6534

Get form input value with Dart

I'm trying to get the value of an input element e.g. this is simple form:

<form id="loginForm">
        <label for="username">Username</label>
        <input required type="text" class="form-control" id="username">
        <label for="password">Passowrd</label>
        <input required type="password"id="password">
    </div>
    <button type="submit">Submit</button>
</form>

with jQuery I would have written:

let value = $("#password").val();

or I could even serialize the whole form,

but in Dart this seems not working:

querySelector('#username').getAttribute('value');

, it returns null

I'm not using any frameworks,

any suggestions?

Upvotes: 3

Views: 3074

Answers (4)

Jax0312
Jax0312

Reputation: 1

As of Dart HTML package version 0.15.0, this is the only way that worked for me

String value= document.querySelector('#movie_id').attributes['value'];

querySelector('xxx').attributes returns a map containing the string of value

Upvotes: 0

Michael
Michael

Reputation: 1185

If you type hint the element as an InputElement when you use querySelector you'll be able to access its value.

  InputElement cityInput = querySelector('#city-input');
  final cityName = cityInput.value;

Upvotes: 0

Neil Fraser
Neil Fraser

Reputation: 5

As of Dart version 2.2.0 (2019), the above answers no longer appear to work. Casting now returns this error:

Uncaught CastError: Instance of 'HtmlElement': type 'HtmlElement' is not a subtype of type 'InputElement'

Here's a way to access an input field's value without casting:

String value = document.getElementById('username').text;

Upvotes: 0

DomJack
DomJack

Reputation: 4183

querySelector will only return an HtmlElement. Since you know the result is an InputElement (a TextInputElement at that) you need to cast it to gain access to the value attribute.

(querySelector('#usernames') as InputElement).value

Upvotes: 4

Related Questions