Changing Form Field Type with onclick

2

   Exemplo

  <a herf="#"  oncllik="">Mudar Campo</a>

   <input type"text" name="nome">  // Ativo <-----------|
                                                        |  Enverter
   <select name"nome">             // Escondido <-------|
   <option value=""></option>
   </select>
    
asked by anonymous 17.05.2015 / 13:51

2 answers

2

If this is for a form that will be submitted in addition to hiding it should disable the field so it will not be submitted.

Notice that you have an error in oncllik must be onclick with 1 L . Other things you have to have in this onclick="" is the function that runs. For example: onclick="subsituir()" where to replace is a global function. I'd rather do this in JavaScript rather than inline in HTML, so I'll give an ID to that <a> and use it in the example below.

In the example below I put a div.alternativos to make it safer to use the selector in .querySelector() and not run the risk of selecting other inputs / selects on the page.

You can do this using native JavaScript:

document.getElementById('mudar').addEventListener('click', substituir);

    function substituir(e) {
        var input = document.querySelector('.alternativos input');
        var select = document.querySelector('.alternativos select');

        mudarEstado(input, !select.disabled);
        mudarEstado(select, select.disabled);
    }

    function mudarEstado(el, mostrar) {
        el.style.display = mostrar ? 'block' : 'none';  // mostra ou esconde
        if (mostrar) el.removeAttribute('disabled');    // ativa ou desativa
        else el.setAttribute('disabled', true);
    }

And HTML, where the select already has disabled="true" :

<a herf="#" id="mudar">Mudar Campo</a>

<div class="alternativos">
    <input type "text" name="nome" />
    <select name="nome" disabled="true">
        <option value="">Escolha 1</option>
    </select>
</div>

Example: link

If you want to make the transition smoother you can do an animation with CSS using transition: opacity and applying visibility at the end of the animation with setTimeout / JavaScript.

Example: link

If you want to do this in multiple cases I suggest you use a data-index for example, so you keep the information on the list of which group to change.

JS is practically the same, only changing to:

function substituir(e) {
    var index = this.dataset.index - 1;
    var grupo = document.querySelectorAll('.alternativos')[index];
    var input = grupo.querySelector('input');
    var select = grupo.querySelector('select'); 

Example: link

    
17.05.2015 / 14:05
0

Here's another example to answer the duplicate question: Change option of a select via javascript

 <?php
    if($_POST) {

        if (isset($_POST['grupo'])) {
            $grupo = $_POST['grupo'];

            if (in_array($grupo, array('A',''))) {
               $return = array(
                  array('id'=>'B','nome'=>'grupo B'),
                  array('id'=>'T','nome'=>'grupo T'),
                );
            }

            if (in_array($grupo, array('B','B1','B2','B3'))) {
               $return = array(
                  array('id'=>'T1','nome'=>'Opção 1 grupo B'),
                  array('id'=>'T2','nome'=>'Opção 2 grupo B'),
                  array('id'=>'T3','nome'=>'Opção 3 grupo B'),
                );
            }

            if (in_array($grupo, array('T','T1','T2','T3'))) {
               $return = array(
                  array('id'=>'B1','nome'=>'Opção 1 grupo T'),
                  array('id'=>'B2','nome'=>'Opção 2 grupo T'),
                  array('id'=>'B3','nome'=>'Opção 3 grupo T'),
                );
            }
       echo json_encode($return);  
       exit();
       }
    }


    ?>


    <a href="javascript:void(0)" id="post_x">Abrir opções</a>

    <div id="select_a">Grupos: <select id="post_a"></select></div>
    <div id="select_b">Grupos nivel 1:<select id="post_b"></select></div>
    <div id="select_c">Grupos nivel 2:<select id="post_c"></select></div>
    <script src="https://code.jquery.com/jquery-latest.min.js"></script><script>$(function(){$('#select_a,#select_b,#select_c').hide();$('#post_x').on('click',function(){varvalor='A';carregarDados('<?phpecho$_SERVER["SCRIPT_NAME"]?>', valor, 'a');

            if(valor == '') {
                  $('#select_a').hide();
             } else {
                  $('#select_a').show();
             }
        });
       $('#select_a select').on('change', function() {
          var valor = $(this).val();
             if(valor == '') {
                  $('#select_b').hide();
             } else {
                  $('#select_b').show();
             }
           carregarDados('<?php echo $_SERVER["SCRIPT_NAME"]?>', valor, 'b');

        });
       $('#select_b select').on('change', function() {
            var valor = $(this).val();

             if(valor == '') {
                  $('#select_b').hide();
             } else {
                  $('#select_b').show();
             }
           carregarDados('<?php echo $_SERVER["SCRIPT_NAME"]?>', valor, 'c');
            $('#select_c').show();
        });

        $('#select_c select').on('change', function() {
            var valor = $(this).val();

             if(valor == '') {
                  $('#select_c').hide();
             } else {
                  $('#select_c').show();
                   alert('Submeter form com valor: '+valor);
             }

        });

    });

    function carregarDados(url, grupo, id_select) {

    var data = {
      grupo:grupo
    };
        $.post(url,data,function(e) {
        var options = [];
     var default_option = '<option value="" selected>Selecione...</option>';
        var grupo = jQuery.parseJSON(e);

           for(var i in grupo){
              options[i] = '<option value="' + grupo[i].id + '">'
                        + grupo[i].nome + 
                      '</option>';
           }
                 var opc = options.join("\n");
            var selects = [
            default_option, 
            opc].join("");
             $('#post_'+id_select).html(selects);
        });

    }

    </script>
    
16.09.2015 / 00:56