Change Form Field Type with onclick

Asked

Viewed 2,583 times

3

As I don’t have much experience in javascript I would like to know how to exchange between 2 fields when clicking on a link with onclik

   Exemplo

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

   <input type"text" name="nome">  // Ativo <-----------|
                                                        |  Enverter
   <select name"nome">             // Escondido <-------|
   <option value=""></option>
   </select>

2 answers

3


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

Notice you have a mistake in oncllik must be onclick with 1 L. Other things you have to have in that onclick="" is the function that runs. For example: onclick="subsituir()" where replace is a global function. I prefer to do this in Javascript and not inline in HTML, so I’m going to give this one an ID <a> and use this in the example below.

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

You can do so 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 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: http://jsfiddle.net/qq9w1c86/

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

Example: http://jsfiddle.net/qq9w1c86/2/

If you want to do this in multiple cases I suggest you use one data-index for example, this way you keep information on which group to change.

The JS is pretty much 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: http://jsfiddle.net/8jhL4ao4/

  • Perfect... it was just that I tried to put in more in 1 field and giving conflict what I’m doing wrong http://jsfiddle.net/fabioo7/z8n92c49/

  • @Fabiohenrique ok, 2 min and send another version.

  • @Fabiohenrique don’t duplicate code that way. It takes a lot of work to maintain. Here’s a version of what you want: http://jsfiddle.net/8jhL4ao4/ I’ll add to the answer too

1

Follow 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(){
           var valor = 'A';
           carregarDados('<?php echo $_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>

Browser other questions tagged

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