Set focus for paper-input via radio button

1.2k views Asked by At

In Polymer (1.0), how can I set the focus of the iron-input when (as example) radiobutton 'radio1' is selected.

<div>
  <div>Title:</div> 
  <paper-radio-group>
    <paper-radio-button name="radio1">Radio1Label</paper-radio-button>
    <paper-radio-button name="radio2">Radio2Label</paper-radio-button>
  </paper-radio-group>
  <paper-input-container>
    <input is="iron-input">
  </paper-input-container>
</div>
2

There are 2 answers

3
Ben Thomas On BEST ANSWER

You will need to bind a click event to radio1:

<paper-radio-button name="radio1" on-click="_setInputFocus">Radio1Label</paper-radio-button>

Then define the function _setInputFocus so that it selects the input and sets the focus to it:

<script>
    Polymer({
        is: 'the-name-of-your-element',
        _setInputFocus: function () {
            this.$$("input").focus();
        }
    });
</script>

EDIT: Now we want the input disabled until the user selects the radio button. So we give the iron-input the disabled attribute:

<paper-input-container>
    <input is="iron-input" disabled>
</paper-input-container>

Then we change our JavaScript function so that we remove the disabled attribute and sets the input focus:

<script>
    Polymer({
        is: "focus-test",
         _setInputFocus: function () {
            var inputElement = this.$$("input"); // grab the element
            inputElement.toggleAttribute("disabled", false); // remove the disabled attribute
            inputElement.focus(); // set the focus to this input
        }
    });
</script>
0
markop On

You could also use the <paper-input> instead of the <paper-input-container> element and then use

setTimeout(function() {
        this.$.tabname.inputElement.focus()
    }.bind(this), 200);

in your function. (The set timeout is sometimes necessary because if another element had focus and is about to close (e.g. an iron-dropdown) then you would have to wait for this to finish before giving focus to the input)