0

I want to add text boxes on button click using jquery in lightning component. On a button click i am unable to maintain a counter value in helper file. Where can i maintain counter value. How can i achieve the same. Here is my code.

Controller.js

addOption: function(component, event, helper) {         
     helper.addOption();
}

Helper.js

addOption: function(component, event, helper){
    alert("Add option button clicked");       

    if(counter>4)
    {
        alert("Only 4 options allowed");
        return false;
    }

    //Iterate number of option and create option textbox.     
    var newTextBoxDiv = $(document.createElement('div'))
    .attr("id", 'OptionDiv' + counter);                
    newTextBoxDiv.after().html('<label>Option #'+ counter + ' : </label>' +
                               '<input type="text" name="option' + counter + 
                               '" id="option' + counter + '" value="" >');            
    newTextBoxDiv.appendTo("#OptionGroup");
    counter++;
}
1
  • Where you defined counter variable? Commented Apr 8, 2016 at 6:16

1 Answer 1

1

It is recommend that DOM manipulations should be done in lightning way as mentioned here.

In this case you can do something like this:

testCmp.cmp

<aura:application access="global">
   <aura:attribute name="inps" type="Object[]"/>
   <aura:iteration items="{!v.inps}" var="x">
      <ui:inputText aura:id="{!x.id}" label="{!x.label}"/>
   </aura:iteration> 
   <ui:button press="{!c.addInputBox}" label="add"/>
</aura:application>

testCmpController.js

({
   addInputBox : function(component, event, helper) {
       var arr = component.get("v.inps");
       var count = helper.getCounter();
       arr.push({
          'label':'label-'+count,
          'id':'txtId-'+count
       });
       helper.increCounter();
       component.set("v.inps",arr);
    }
})

testCmpHelper.js

({
    counter:1,
    getCounter : function() {
       return this.counter;
    },
    increCounter:function(){
       this.counter++;
    }
})

----- UPDATE -----

Above approach might not really need an helper to use counter to achieve the same functionality.

For this the testCmpController.js should look like this:

testCmpController.js

({
   addInputBox : function(component, event, helper) {
       var arr = component.get("v.inps");
       var count = arr.length + 1;
       arr.push({
          'label':'label-'+count,
          'id':'txtId-'+count
       });
       component.set("v.inps",arr);
    }
})

Hope it helps.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .