Hidden fields appear/are modified with a select Multiple

Asked

Viewed 1,526 times

3

Hello, I have the following select:

<select name="hierarquia[]" multiple>
    <option value="Usuário" selected> Usuário</option>
    <option value="Moderador" selected> Moderador</option>
    <option value="Administrador"> Administrador</option>
</select>

I also have following fields (examples):

<input type="hidden" id="campo-1" name ="campo-1" value="0000">
<input type="hidden" id="campo-2" name ="campo-2" value="0000">

I’m setting up an administrative panel, where the form configuration comes automatically. I select the data from the SQL table into a variable, call a function that pulls an array with their fields and types (I’ll come back to that later) and from a repeat structure, the software creates all inputs, selects, radios, etc.

The fact is that there are some fields that are special, only appear when you add a specific user type, evidenced by $_GET['mode'], that is, if this $_GET['mode'] = 'moderador', it displays the hidden fields applicable to the record to the moderator correctly, if $_GET['mode'] = 'admin', it displays those of the administrators, but not those of the moderator, and so on.

These fields are Hidden for a single reason: I validate all incoming entries. If the function that validates does not find the $_GET, the only answer he will find valid will be 0000.

The point is that field-1 or field-2 are not necessarily Texts, but can be select with various options, loaded from the bench, radios, up to files, or other various things.

While writing this, I came up with two ideas: when changing the select, I checked which(s) were selected and depending on the case, carrying new fields via ajax (?). Then it would take, since they could not have fields that were loaded twice and that these loaded fields replace the hiddens. This would also require a modification in validation, but providential.

The other idea would be a little less evasive, less radical and preferable. By changing the select field, I would reload the page with the $_GET['mode'] corresponding to the one that was selected. The big problem is that I could not lose the data that was already filled.

I leave this to you, I need to change between several fields when different options are selected, including more than one option can be selected. If possible, launch new ideas or functions to use.

Additional detail: the $_GET['mode'] may be in format: $_GET['mode'] = 'admin,moderador'

  • how are you mounting the page? You can post the code?

  • I am far from my source code, when I get my edit note here!

2 answers

3


And if you used the jQuery to check the selected/unselected modes and show/hide the fields in the event change select?

It would look something like this:

$(document).on('change', '#multiple' function(){
    $('#multiple option').each(function(i, e){ 
      var mode = $(e).data("mode");
      var type = $(e).data("type");

      $('[data-mode=' + mode + ']').show();

      if (type != undefined || type != ''){
          $('[data-mode=' + mode + ']').attr('type', type);
      }
    });
});

but for this example to work you must add in your inputs two attributes data-. the data-mode and the data-type.

  • data-mode => the way the input should be activated;
  • data-type => the type of input when it is activated;

So, according to the example you gave, the inputs would look like this:

<input type="hidden" data-mode="moderador" data-type="date" id="campo-1" name ="campo-1" value="0000">
<input type="hidden" data-mode="administrador" data-type="file" id="campo-2" name ="campo-2" value="0000">

In this case, the first input will be activated for the mode moderador and will be like date, while the second will be activated for the mode administrador and will be like file.

This example is valid also for any type of input, select, textarea, etc..., just have the attribute data-mode. But for elements that are not inputs, like selects for example, you should check if there is an attribute data-type and if there is no simply display the control.

Editing:

In case you need to load data to fill a select when displaying it, you could do as follows:

<select name="nome" data-ajax-load="true" data-url="/dados.php"></select>

And change the event change to understand these two new attributes, thus:

$(document).on('change', '#multiple' function(){
    $('#multiple option').each(function(i, e){ 
      var mode = $(e).data("mode");
      var type = $(e).data("type");
      var ajax = $(e).data("ajax-load");

      if (ajax)
      {
          var url = $(e).data("url");

          $.ajax({
             cache: false,
             type:  tipo,
             data:  data,
             url: location.origin + "/" + url,
             success: function (response) {
                $(e).html(response);
             }
          });
      }

      $('[data-mode=' + mode + ']').show();

      if (type != undefined || type != ''){
          $('[data-mode=' + mode + ']').attr('type', type);
      }
    });
});
  • It’s an interesting solution, but what if it was a select with certain DB data?

  • If this data is dynamic, it should be loaded only when it is displayed you could use ajax. I will update the response.

  • Answer totally solved the problem I had, unfortunately I had to modify the project and asked me to change to individual tables for each one in the hierarchy. In the future your code will be used. :)

2

You can use a simple Javascript to do what you want.

To do that you can do the Submit from the form, to the page itself, whenever you change your select as follows:

<form id='formId' action=''>
<!-- ... -->
<select id="hierarquia" name="hierarquia[]" onchange="this.form.submit();" >

In case you need to save the form on another page, please note that you must remove the action in the onchange:

<form id='formId' action='gravar.php'>
<!-- ... -->
<select id="hierarquia" name="hierarquia[]"
   onchange="document.getElementById('formId').action='';this.form.submit();" >

Then you just take all the fields with the POST and put the values caught in your fields:

if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    $value_campo1 = filter_input(INPUT_POST, 'campo-1');
    $hierarquia   = filter_input(INPUT_POST, 'hierarquia');
    //outros valores que precises apanhar
}

Example of a input:

<input type="hidden" id="campo-1" name ="campo-1" 
   value="<?php ($value_campo1 != NULL) ? echo $value_campo1 : echo "0000"?>">

Example of a select from the comic book:

$sql    = "SELECT * FROM table";
$result = mysqli_query( $connection , $sql);
while($row = mysqli_fetch_array($result))
{
    $selected = "";
    // verifica a seleção que já foi feita depois do submit
    if($row['hierarquia']==$hierarquia)   
        $selected = "  selected=\"selected\"";

    echo "<option $selected value='{$row['hierarquia']}'> {$row['hierarquia']} </option>";
}

As for the fields you want mode just do the check before showing the field;

if($_GET['mode']=='admin')
{
?>
     <!-- campo(s) de admin -->
<?php
}
else if($_GET['mode']=='moderador')
{
?>
    <!-- campo(s) de moderador -->
<?php
}
  • I forgot to mention, but there is no such file 'write.php' and it is not even possible to add it.

  • That’s indifferent, just don’t write.php.

  • Check out my @Gabrieltadramainginski edition

  • Ah did purposely with if + echo and ternary condition + HTML on purpose to see the two forms.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.