简体   繁体   中英

Get value from paper-checkbox if checked

A similar question has been asked and I am trying to do the same with paper-checkbox in Polymer 1.1

Here is my full setup:

<dom-module id="my-app">
 <template>
  <firebase-collection
   location="htt://www.abc.com/users"
   order-by-child="formatOrder"
   data="{{users}}">
  </firebase-collection>
  <template is="dom-repeat" items="[[users]]" as="user">
   <paper-checkbox id="user-checked" value="{{user.name}}" on-tap="userRequest">click</paper-checkbox>
  </template>
 </template>
 <script>
  Polymer({
   is: "my-app",

   userRequest: function() {
    var cbs = document.querySelectorAll('#user-checked');
    for(var i = 0; i < cbs.length; i++) {
     cbs[i].addEventListener('change', function() {
      if(this.checked) {
       console.log(this.value);
      }
     });
    }
   },
  });
 </script>
</dom-module>

So basically I want when the checkbox is checked, it shows their name. If I decided to add another checkbox for their age, it does the same. But the code above runs the code twice, when checked or unchecked, even three times. How to get it to execute once when checked and not to execute when unchecked?

Every time someone taps the checkbox you add an event listener for the change event in your userRequest function. Thus, the more often the user taps the checkbox, the more event listeners you will have for the same event. They will all get called each time the event fires. But actually you only need one and you can add in the markup directly .

<paper-checkbox on-change="checkboxChanged">click</paper-checkbox>

Then in your event handler you can access the checkbox value via event.target.value

checkboxChanged : function(event){
    if(event.target.checked) {
        console.log(event.target.value);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM