Jump to content

[Resolvido] Radio Button PHP


PF2G

Recommended Posts

Boas,

eu estou a tentar definir um maxlength de uma input text dependendo da radio button seleccionada:

<td>
	 <input type="radio" name="bi_cc" value="BI"> B.I.</input>
	  
	 <input type="radio" name="bi_cc" value="CC"> C.C. </input>
	  
	 <input type="radio" name="bi_cc" value="Passaporte"> Passaporte </input>
	 <br/>
	 <br/>
	 <input class="input" type="text" name="bi_cc" value="<?php echo $user_info['bi_cc'] ?>" maxlength="
	 <?php   if (isset($_POST['bi_cc'])) {
	    if ($_POST['bi_cc'] == 'BI') {
	    echo '9';
	    }
	    else if ($_POST['bi_cc'] == 'CC') {
		 echo '10';
	    }
	    else if ($_POST['bi_cc'] == 'Passaporte') {
		 echo '11';
	    }
	   }
	    ?>"/>
    </td>

Mas não esta a acontecer nada. A unica solução que encontrei na minha pesquisa é ao fazer submit mas eu nao quero fazer submit quero que leia atraves do select da radio button.

Link to comment
Share on other sites

PHP e' uma linguagem Server-Side, para o que tu queres tens que utilizar Javascript que ' uma Linguagem Client-Side

Por muito mais que que estude só aprendo uma coisa, que ainda tenho muita coisa para aprender.

A beleza de um código está em decompor problemas complexos em pequenos blocos simples.

"learn how to do it manually first, then use the wizzy tool to save time."

"Kill the baby, don't be afraid of starting all over again. Fail soon, learn fast."

Link to comment
Share on other sites

Será que assim resultará?

 <script type="text/javascript">
  function maxlength(){
   if(radio_bi_cc.value=="BI"){
 input_bi_cc.maxlength=="9";
   }
   else if(radio_bi_cc.value=="CC"){
 input_bi_cc.maxlength=="10";
   }
   else if(radio_bi_cc.value=="Passaporte"){
 input_bi_cc.maxlength=="11";
   }
  }
 </script>

E depois como chamo a função na input text onde quero aplicar os diferentes maxlength?

Link to comment
Share on other sites

a ideia seria essa, no entanto tens vários problemas com o código que apresentas

- radio_bi_cc não é uma variável existente

- input_bi_ccnão é uma variável existente

- o nome do grupo e o nome da caixa de entrada é igual : "bi_cc"

- essa não é a forma de alterar o valor de um atributo de um elemento DOM, tens de usar a função "setAttribute"

IRC : sim, é algo que ainda existe >> #p@p
Link to comment
Share on other sites

isto está mais ou menos adaptado ao teu exemplo ...

<!DOCTYPE html>
<html>
 <head>
   <script type="text/javascript">
     function maxlength(){
       var radios = document.getElementsByName("bi_cc");
       var val = 0;

       for( i = 0; i < radios.length; i++ ) {
         if( radios[i].checked == true )
          val = radios[i].value;
       }

       if(val == "BI"){
         document.getElementsByName("input")[0].setAttribute("maxlength", "9");
       } else if(val=="CC"){
         document.getElementsByName("input")[0].setAttribute("maxlength", "10");
       } else if(val=="Passaporte"){
         document.getElementsByName("input")[0].setAttribute("maxlength", "11");
       }
     }
   </script>
 </head>
 <body>
   <input type="radio" name="bi_cc" value="BI" onchange="maxlength();"> B.I.</input> 
   <input type="radio" name="bi_cc" value="CC" onchange="maxlength();"> C.C. </input> 
   <input type="radio" name="bi_cc" value="Passaporte" onchange="maxlength();"> Passaporte </input>
   <br/>
   <br/>
   <input class="input" type="text" name="input" value="" maxlength="0" />
 </body>
</html>
Edited by HappyHippyHippo
IRC : sim, é algo que ainda existe >> #p@p
Link to comment
Share on other sites

Hippo estou com algumas dificuldades em preceber é algo assim deste genero?

document.getElementsByName("input")[0].write(8,12);

???

var element = document.getElementsByName("input")[0]; /* guardar o elemento a trabalhar */
element.setAttribute("maxlength", "9");               /* definir o tamanho máximo */
element.value(                                        /* guardar a string no campo value do elemento */
   element.value().substring(                        /* "cortar" a string que existe no campo value do elemento */
       0,                                            /* o resultado do "corte" começa na posição 0 (início) da string */
       9));                                          /* o resultado do "corte" termina na posição do novo máximo da campo */
IRC : sim, é algo que ainda existe >> #p@p
Link to comment
Share on other sites

E é suposto apagar automaticamente? É que não está a resultar:

<script type="text/javascript">
  function maxlength(){
   var radios = document.getElementsByName("bi_cc");
   var element = document.getElementsByName("input")[0];
   var val = 0;
   for( i = 0; i < radios.length; i++ ) {
 if( radios[i].checked == true )
  val = radios[i].value;
  }
  if(val == "BI"){
 element.setAttribute("maxlength", "8");
 element.value(element.value().substring(8, 12));

  } else if(val=="CC"){
 element.setAttribute("maxlength", "14");
  } else if(val=="Passaporte"){
 element.setAttribute("maxlength", "8");
 element.value(element.value().substring(8, 12));	  
  }
  }
 </script>
Link to comment
Share on other sites

element.value(                                        /* guardar a string no campo value do elemento */
   element.value().substring(                        /* "cortar" a string que existe no campo value do elemento */
       0,                                            /* o resultado do "corte" começa na posição 0 (início) da string */
       9));                                          /* o resultado do "corte" termina na posição do novo máximo da campo */

    element.value(element.value().substring(8, 12));

não vou dizer nada porque se disser não serão palavras simpáticas ...

IRC : sim, é algo que ainda existe >> #p@p
Link to comment
Share on other sites

     function maxlength(){
       var radios = document.getElementsByName("bi_cc");
       var input = document.getElementsByName("input")[0];
       var val = 0;

       for( i = 0; i < radios.length; i++ ) {
         if( radios[i].checked == true )
          val = radios[i].value;
       }

       var max = 0;
       if(val == "BI")            max = 9;
       else if(val=="CC")         max = 10;
       else if(val=="Passaporte") max = 11;

       input.setAttribute("maxlength", max);
       input.value = input.value.substring(0, max);
     }
IRC : sim, é algo que ainda existe >> #p@p
Link to comment
Share on other sites

Ta fixe, obrigadao.

Só mais uma pergunta:

eu quero que o BI seja so numeros. Já tenho o script como chamo agora a function?

<SCRIPT language=Javascript>
 <!--
 function isNumberKey(evt)
 {
 var charCode = (evt.which) ? evt.which : event.keyCode
 if (charCode > 31 && (charCode < 48 || charCode > 57))
 return false;
 return true;
 }
 //-->
</SCRIPT>
if(val == "BI") {
  return isNumberKey(evt);/* nao sei se é assim  */
  max = 8;
}
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.