Polymer Get Paper Input Value

2019-06-16 21:08发布

问题:

I am using Polymer for a short time and now i want to get the value of a paper input. I don't know how can I do this. This is not working:

this.form.password

I want to get the Value of this field:

<paper-input label="Password" type="password" id="password" name="password" size="25" value=""></paper-input>

I also want get the Input for submitting of the e-mail input:

<paper-input label="Login" id="email" name="email" size="25" value=""></paper-input>

For submitting I am using:

<paper-button raised value="Login" type="submit" onclick="formhash(this.form, this.form.password);">Login</paper-button>

With normal input fields is this working.

回答1:

You can use document.querySelector('#password').value to get the value of paper-input with id password in the formhash() function call or inside the function definition.

You can also use polymer's Automatic node finding to get value of an element using its id. In which keep the form/input in custom-element and use this.$.password.value to get the value of an element with id password. Like this

<!-- create a custom component my-form --> 
<dom-module id="my-form">
    <template> 
      <form is="iron-form" id="form" method="post">
        <paper-input name="name" label="name" id="name"></paper-input>
        <paper-button raised on-click="submitForm">Submit</paper-button>
      </form>
    </template>
    <script type="text/javascript">
        Polymer({
            is: "my-form",
            submitForm: function() {
                alert(this.$.name.value);
                if(this.$.name.value != "") // whatever input check
                   this.$.form.submit();
            }
        })
    </script>
</dom-module>

<my-form></my-form> <!-- use custom-component my-form -->


回答2:

If you don't want to use <form> you can also simply store the paper-input values in instance variables and use them later wherever you want.

All you have to do is store the input inside a value like this:

<paper-input label="Password" type="password" id="password" name="password" size="25" value="{{valueNameToStore}}"></paper-input>

And later access it like this:

var myPassword = this.valueNameToStore;



回答3:

Using <form is="iron-form"> allows you to use <paper-input> and other input elements in forms https://elements.polymer-project.org/elements/iron-form

<form is="iron-form" id="form" method="post" action="/form/handler">
  <paper-input name="name" label="name"></paper-input>
  <input name="address">
  ...
  <paper-button raised onclick="submitForm()">Submit</paper-button>
</form>


function submitForm() {
  document.getElementById('form').submit();
}


标签: input polymer