简体   繁体   中英

Javascript on change update input values in foreach

So I have to update values in each form from one drop down elemnt

Here is code from my group select box

              echo $this->Form->input('groups', ['options' => $groups, 'id' => 'groups', 'class' => 'selectpicker', 'label' => false, "onchange"=>"updateGroupId(this.value)"]);

Here is code where I generate forms

<table class="table table-striped">
       <tbody>
       <?php foreach($allProducts as $product): ?>
         <tr>
             <td>
                <form class="form-inline" name="uploadform-<?= $product->id ?>" id="uploadform-<?= $product->id ?>" onsubmit="return checkInput<?= $product->id ?>()" enctype="multipart/form-data" action="/upload/<?= $product->id ?>" method="post">
                  <span class="btn btn-primary btn-file">
                    <span><i class="zmdi zmdi-upload zmdi-hc-fw"></i><?= __('Upload CSV') ?></span>
                    <input id="browsefiles-<?= $product->id ?>" name="uploadcsv" type="file" required="required" />
                    <span id="errornotification-<?= $product->id ?>" class="hidden"><?= __('Select CSV File') ?></span>
                  </span>
                  <input type="text" name="group_id-<?= $product->id ?>" id="group_id-<?= $product->id ?>" value="<?= key($groups) ?>" />
                </form>
             </td>
         </tr>
       <?php endforeach; ?>
       </tbody>
     </table>

And here is my javascript code

<?php
$i=0;
foreach ($allProducts as $product) {
?>
  function updateGroupId(ish){
    document.forms["uploadform-<?= $product->id ?>"]["group_id-<?= $product->id ?>"].value = ish;
  } } ?>

With this code I can update values on change only for last input, but I need for all inputs (groups_id).

I have figured out an answer, so if somebody need solution here it is!

So, this is how to change values on all inputs with same name using select box (on.change function)

Select box select input need ->

"onchange"=>"updateGroupId(this.value)"

input for change

<input type="hidden" name="group_id" value="<?= key($groups) ?>" />

And JS code

function updateGroupId(ish){
      var group_ids = document.getElementsByName('group_id');
      for (var i=0;i<group_ids.length;i++) {
        group_ids[i].value = ish;
      }
    }

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