Teddy
Teddy

Reputation: 59

How to get hidden value from multiple input text?

I'm creating a small program to input sales target for multiple salesman. How to get salesman id only if target is not empty.

I'm using array input type hidden to store salesman id. But everytime i tried to get salesman id whose target field not empty, it printed all salesman id.

This is the input:

<form method="POST" action="">
  <input type="submit" name="send" value="send"><br/>
  <?
      $getSales = "SELECT sales_id, sales_name FROM SALESMAN";
      $execSales = odbc_exec($conn,$getSales);
      while(odbc_fetch_row($execSales)) {
         $idSales = odbc_result($execSales,"sales_id");
         $nameSales = odbc_result($execSales,"sales_name");

         ?>
         <tr>
            <input type="hidden" name="salesid[]" id="salesid">
            <td><input type="text" name="target[]" id="target"></td>
         </tr>
         <?
         }
    ?>
</form>

This form will result something like this

Sales Id   || Target     |
--------------------------
SLS0001    || |______30| | ==> 30 for sls0001
SLS0002    || |________| | ==> no target for sls0002
SLS0003    || |______10| | ==> 10 for sls0002

to get the salesid with target not empty, i create this

foreach (array_filter($_POST['salesid']) as $key => $salesId)
{
    echo $salesId.'<br/>';
}

What i expect for the result is

SLS0001
SLS0003

but the result is

SLS0001
SLS0002
SLS0003

How to get the expected result? Thank you.

Upvotes: 2

Views: 100

Answers (2)

Michael Peng
Michael Peng

Reputation: 926

If I understand correctly, I think you need to be checking if $_POST['target'] is empty, not salesid.

You can use array_combine in conjunction with array_filter to achieve this result. See more info on array_combine here: https://www.php.net/manual/en/function.array-combine.php

array_combine($_POST['salesid'], $_POST['target']) will give you an array like:

array(
 'SLS0001' => '30',
 'SLS0002' => '',
 'SLS0003' => '10'
);

Then applying array_filter it will give you the correct result.

// makes salesid your key, and target your value, array_filter will filter out empties from target
foreach (array_filter(array_combine($_POST['salesid'], $_POST['target'])) as $salesid => $target)
{
    echo $salesid.'<br/>';
}

Upvotes: 4

Veyis Aliyev
Veyis Aliyev

Reputation: 323

foreach (array_filter($_POST['salesid']) as $key => $salesId)
{
    if (!/* here you use condition for is empty or null */)
        echo $salesId.'<br/>';
}

Upvotes: 0

Related Questions