Hidden fields appear / modified with a select multiple

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>

And 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 am putting together an administrative panel, where the configuration of the forms comes automatically. I set the SQL table data in a variable, call a function that pulls an array with the fields and their types (I'll go back on that later) and from a repeat structure, the software creates all the 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 that $_GET['mode'] = 'moderador' , it displays hidden fields that can be moderator correctly, case $_GET['mode'] = 'admin' , it displays those of the admin, but not those of the moderator, and so on.

These fields are hidden for a single reason: I validate all incoming entries. If the validating function does not find $_GET , the only answer it will find valid is 0000.

The issue is that field-1 or field-2 are not necessarily texts, but can be select with varying options, loaded from the database, radios, even files, or various other things.

As I wrote this, two ideas came to mind: when I changed the select, I checked which ones were selected and depending on the case, loading new fields via ajax (?). Then he would pick up, since they could not have fields that were loaded twice and those charged fields replace the hiddens. This would also require a change in validation, but it will be provided.

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

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

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

    
asked by anonymous 01.03.2015 / 06:51

2 answers

3

What if you used jQuery to check the selected / deselected modes and to show / hide the fields in the change event of the 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, you should add two attributes data- to your inputs. the data-mode and the data-type .

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

Then, 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 moderador mode and will be of type date , while the second will be activated for administrador mode and will be file type.

This example is also valid for any type of input, select, textarea, etc ..., just have the data-mode attribute. But for elements other than inputs, such as selects for example, you should check for the data-type attribute and if you do not simply display the control.

Editing:

If you need to load data to populate a select while displaying it, you could do it 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);
      }
    });
});
    
03.03.2015 / 12:44
2

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

To do this, you can do the submit of the form for 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 you have to note that you have to remove action in onchange :

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

Then just pick up all the fields with POST and put the values collected 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 coming from DB:

$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 appearing the fields you want depending on 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
}
    
03.03.2015 / 12:27