0

I have following code in my view file:

<?php for ($x = 1; $x <= 5; $x++) {
    echo $this->widget('application.components.FileUploadWidget',array(
    'model'=>$model,
    'attribute'=>'f__10_'.$x,

    'htmlOptions'=>array('class'=>'form-control')
),true);

}

?>


<div class="form-group">
    <div class="col-xs-12 col-sm-2 pull-right" style="">
        <button id="adding" href="#" rel=".copy" class="pull-right add-item btn btn-success" type="button"">
        <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>Add</button>
    </div>
</div>
<div class="form-group">
    <div class="col-xs-12 col-sm-2 pull-right" style="">
        <button id="remove" href="#" rel=".copy" class="pull-right add-item btn btn-danger" type="button"">
        <span class="glyphicon glyphicon-minus" aria-hidden="true"></span></button>
    </div>
</div>

And I have following JavaScript code:

<script>
    $(document).ready(function(){
        $("#Form_f__10_1, #Form_f__10_2, #Form_f__10_3, #Form_f__10_4, #Form_f__10_5").hide();

        $("#remove").click(function(){
            $("#Form_f__10_1").hide();
        });
        $("#adding").click(function(){
            $("#Form_f__10_1").show();
        });
    });

</script>

(JavaScript code is incomplete). when user presses add button, it should show widget which attribute is equal to f__10_1. If a user presses again add button, it should show widget which attribute is equal to f__10_2. etc. This process should be done until attribute of widget equalizes to f__10_5. How can I do it in JavaScript?

phpdev
  • 511
  • 4
  • 22
  • so exactly how do you want the code work? – Kevin Bui May 12 '17 at 10:33
  • make yourself a variable where you provide the current form (`current = "Form_f__10_1"`) as string and then in the two functions for "#remove" and "#adding" replace the last character of that string with the appropriate number. (I don't speak php, so somebody else need to code that for you ;) ) – CFrei May 12 '17 at 11:33

1 Answers1

0

You should use a "stack" mechanism. Store the number of shown widgets in a (globally reachable) counter, this is widget_counter for example. This is how it should work:

  1. 'Add' pressed -> widget_counter++ AND show the element
  2. 'Add' pressed -> widget_counter++ AND show the element
  3. 'Remove' pressed -> widget_counter-- AND hide the element
  4. and so on...

If 5 or 0 is reached, don't do anything. You can get the actual (=last) widget shown from the counter variable and you can build up the next element's name from that.

szako
  • 1,271
  • 1
  • 9
  • 12