3

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?

Mattia
  • 5,909
  • 3
  • 26
  • 41

4 Answers4

4

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

DomJack
  • 4,098
  • 1
  • 17
  • 32
  • 3
    While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – 31piy Aug 19 '18 at 03:56
0

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;

0

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;
Michael
  • 1,075
  • 1
  • 10
  • 24
0

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