Utilize the bind-attribute "for" in Ember.js

I'm having trouble setting a unique ID for an tag in order to create a custom checkbox. The {{input}} tag works fine, but the

<label {{bind-attr for=binding}}>
is not displaying as expected. I am new to Ember as a frontend developer, so I believe this issue should be easy to resolve.

<ul class="col-menu dropdown-menu">
  {{#each columns}}
    <li>
      {{input type="checkbox" checked=checked id=binding}} 
      <label {{bind-attr for=binding}}><span></span></label>
      <span>{{heading}}</span>
      {{columns}}
    </li>
  {{/each}}
</ul>

Upon generating the output ...

<li>
  <input id="activityTotal" class="ember-view ember-checkbox" type="checkbox" checked="checked"> 
  <label data-bindattr-2689="2689">
    <span></span>
  </label>
  <span>
    <script id="metamorph-53-start" type="text/x-placeholder"></script>
    Events
    <script id="metamorph-53-end" type="text/x-placeholder"></script>
  </span>
  <script id="metamorph-54-start" type="text/x-placeholder"></script>
  <script id="metamorph-54-end" type="text/x-placeholder"></script>

Answer №1

Begin by encapsulating all of this within a component.

Manually binding the id in this way is not recommended, as Ember handles it internally. However, in this scenario, it may be acceptable to ensure uniqueness.

To guarantee a unique id and utilize it, consider implementing something like this:

 checkBoxId: Ember.computed(function(){
    return "checker-" + this.elementId;
  }),

This snippet showcases the Javascript file for the component that will run when activated:

App.XCheckboxComponent = Ember.Component.extend({
  setup: Ember.on('init', function() {
     this.on('change', this, this._updateElementValue);
   }),
  checkBoxId: Ember.computed(function(){
     return "checker-" + this.elementId;
   }),
  _updateElementValue: function() {
     this.sendAction();

     return this.set('checked', this.$('input').prop('checked'));
   }
});

Below is the template for the component, utilizing unbound to link the unique checkBoxId with the label's 'for' attribute:

<label for="{{unbound checkBoxId}}">
   {{label}}
  <input id="{{unbound checkBoxId}}" type="checkbox" {{bind-attr checked="checked"}}>
</label>

This is how you could implement it:

<ul>
  {{#each contact in model}}
    <li>{{x-checkbox label=contact.name enabled=contact.enabled}}</li>
  {{/each}}
</ul>

Check out the functioning jsbin for ember 1.7.1 and another one for ember 1.11.1 here.

Answer №2

Starting from version 1.11, the usage of bind-attr is no longer necessary. Instead, you can simply bind the attribute in this manner:

<label for={{binding}}></label>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Utilizing jQuery to Trigger CSS3 Transform Animation Replays After a Set Number of Iterations

I currently have an animated image set up like this: <div class="image_for_sping"> <img src="/anyimage.png"> </div> The image has a style attribute added by jQuery which contains the following animation properties: animation: spin3 ...

Is it possible for window.open to sometimes fail in opening a popup window?

There is a process that requires an update. In order to update a third-party database, I need to call a service provided by them. My Ajax function is working properly. Below is the code snippet for the success callback. $.ajax({ . . success : funt ...

What is the best way to integrate nano.uuid into a series of promises that are fetching data from the database?

When working with express routing and nano, I encountered a challenge: router.get('/', function (request, response) { db.view('designdoc', 'bydate', { 'descending': true }) .then(results => { // data ...

Regex: Enabling commas in the name of an Excel file

My JavaScript code is set up to extract data from an excel file. As a first step, I define a regular expression and assign it to a variable named regex var regex = /^([a-zA-Z0-9\s_!()\\.\-:])+(.xls|.xlsx)$/; Following this, there is s ...

Creating XML using information from CSV

I am currently working on a project that involves uploading a CSV file locally and using its data to generate an XML file client-side. While I have managed to extract the CSV data, I am still learning JavaScript and would appreciate some guidance on how to ...

Trigger a click event on a file input in Ionic 3 Android by using the Fire method

In my Ionic 3 project, I've enabled users to upload multiple images through the application. I am seeking a way to trigger the file browser to open when a Button is clicked, as shown below. Here is the snippet of code I am currently working with: hom ...

Ways to switch out the background image using jQuery

I am currently using jQuery to dynamically change the background image of a web page. Right now, I have implemented two separate buttons that toggle between Image A and Image B. By default, Image A is displayed on the page. My goal is to enhance this func ...

Is it possible to enable auto play on HTML5 Video for iPad similar to BBC iPlayer?

Can HTML5 Videos automatically play on iPads? I used to believe that it wasn't possible because of iOS restrictions, but after trying BBC iPlayer on my iPad, I noticed that the videos did autoplay upon loading. Could this indicate that it is indeed ...

How to Create Smooth Transitions for Text Arrays using jQuery's Fade In and Fade Out Features

I need to loop through an array of text and apply jQuery's fadeIn and fadeOut functions to each element. var greetings = ["hi, I'm", "bonjour, je m'appelle", "hallo, ich heiße"] The HTML structure I want is as follows: <h2><span ...

Locate an array within a Multidimensional array and relocate it to the starting position

I've been attempting to figure out a solution for moving a specific array within another array to the beginning. The problem I'm encountering is that the code I was using, as suggested in a previous question, only removes the last value and plac ...

Steps for creating a button that increments by using ng loop:1. Begin

I am attempting to create a button that can be used to increment and decrement. However, I am facing an issue where all input fields are being affected instead of just one. This is the code in body.component.html <div class="items-detail-detail" *n ...

Retrieve an array from the success function of a jQuery AJAX call

After successfully reading an rss file using the jQuery ajax function, I created the array function mycarousel_itemList in which I stored items by pushing them. However, when I tried to use this array in another function that I had created, I encountered t ...

What is the best way to obtain the inner ID with JQuery?

How can I assign values to inside id using JQuery? Sample code from controller.cs: public GroupModel Get() { IGroupTypeRepository groupTypeRepo = new GroupTypeRepository(); IGroupRepository groupRepo = new GroupRepository(); var model = new ...

Getting the chosen value from a dropdown menu on form submission using PHP

How to Populate a Combo Box from a Database in PHP? <td>Item Name:</td> <td><select name="items"> <option value="0" selected="selected"> Choose</option> <?php while($row = mysql_fetch_ass ...

How can I code in React to make one button change color while the others remain a different color, instead of all having the same color?

I developed a quiz application that changes the color of answer buttons based on user selection. If the user clicks the correct answer button, it turns green, and if they click the wrong answer, it turns red with the correct answer displayed in green. Howe ...

Leveraging vanilla JavaScript within durandal.js

Currently working with durandal.js and I need to trigger a plugin on page load. This is how it can be done in plain JavaScript: $('.testingShifter').shapeshift(); I am wondering if there is a specific durandal (knockout) binding that I can uti ...

Obtain the index when clicked using jquery

I am currently working on creating a 2 player checkers game for my college project. However, I have hit a roadblock in determining the index of the 2D array when I click on a game piece. The HTML code structure I have divided into: table - representing ...

Does the onchange function in the dropdown list only work when the first item is changed?

Here is a snippet of my HTML code featuring a list item generated from a database using a foreach loop: <select class="form-control select" id="inventoryitem" name="inventoryitem" onchange="getunit();"> <option>---Select an item---</o ...

Is there a way to disable the automatic refreshing of the useForm feature?

Upon clicking submit, all field information is supposed to be sent to the backend, but instead, it is being appended to the browser's URL. Furthermore, the error messages from yup are not being displayed. I attempted to use event.preventDefault in ha ...

Tips for executing getJSON requests one after the other

My goal is to showcase a weather forecast for a specific date on my website. Here are excerpts from the code I've used on a trial page that isn't functioning correctly: <script> function displayWeather(date){ $.getJSON(url + apiKey + "/" ...