Foros del Web » Programando para Internet » PHP »

quiero habilitar textbox al tildar checkbox

Estas en el tema de quiero habilitar textbox al tildar checkbox en el foro de PHP en Foros del Web. Hola gente, a ver si me pueden dar una mano con esto. Tengo una pagina en php en la cual tengo una tabla la cual ...
  #1 (permalink)  
Antiguo 14/03/2012, 18:26
 
Fecha de Ingreso: septiembre-2010
Mensajes: 74
Antigüedad: 13 años, 7 meses
Puntos: 1
Exclamación quiero habilitar textbox al tildar checkbox

Hola gente, a ver si me pueden dar una mano con esto.

Tengo una pagina en php en la cual tengo una tabla la cual muestra productos de un negocio, al final de cada tabla le he agregado un checkbox y un textbox, esto es para que el usuario tilde los productos que quiera vender e ingrese en el textbox la cantidad del mismo producto que desea vender.

este es el codigo:

Código PHP:
<?php
include_once 'lib.php';


$conexionmysql_connect($dbhost$dbuser$dbpassword);
mysql_select_db($database$conexion);
$result mysql_query("SELECT id_stock, codigo, descrip, pre_min, pre_may, disponibles  FROM stock where activo = '1'"$conexion);

echo
"<form name='borrar' method='post' action='vender_prod.php'>";
echo
"<table border='2'>
<tr>
    <th>ID</th>
    <th>Codigo</th>
    <th>Descrip</th>
    <th>Prec.Min</th>
    <th>Prec.May</th>
    <th>Disponibles</th>
    <th></th>
    <th style='border: none'></th>
    <th>Cantidad</th>
    
</tr>"
;
$i=0;
while(
$row mysql_fetch_array($result)){
    
    echo 
"<tr>
        <td>$row[id_stock]</td>
        <td>$row[codigo]</td>
        <td>$row[descrip]</td>
        <td align=right>$$row[pre_min]</td>
        <td align=right>$$row[pre_may]</td>
        <td align=center>$row[disponibles]</td>
        <td><input name='seleccion[]' type='checkbox' value=$row[id_stock]></td>
        <td style='border: none'></td>
        <td><input name='text[$row[id_stock]]' type='text' style='width: 60'></td>  
        </tr>"
;
        
    
$i++;
}
echo 
"</table>";
echo 
"<br>";
echo 
"<input type='submit' name='submit' value='enviar'>";
echo 
"</form>";
echo 
"</form>";  
?>
luego envio los datos a otra pagina en php donde los muestro para que el usuario confirme la venta.

Lo que quiero hacer es que los textbox se habiliten unicamente si e checkbox esta tildado. Como hago esto. gracias
  #2 (permalink)  
Antiguo 14/03/2012, 18:32
Avatar de neglivv  
Fecha de Ingreso: julio-2011
Mensajes: 103
Antigüedad: 12 años, 9 meses
Puntos: 11
Respuesta: quiero habilitar textbox al tildar checkbox

creo que deberias usar JavaScript, especificamente la funcion onChange, la agregas a los checkbox, si el checkbox cambia, entonces habilitas los textbox. No sabria explicarte especificamente, pero creo que puedes comenzar por ahi.
  #3 (permalink)  
Antiguo 14/03/2012, 19:01
Avatar de xxxivanxxx  
Fecha de Ingreso: julio-2010
Ubicación: /home
Mensajes: 114
Antigüedad: 13 años, 8 meses
Puntos: 21
Respuesta: quiero habilitar textbox al tildar checkbox

como bien dise neglivv tienes que usar JS, con el evento onChange se hace un poco facil mira:

Código HTML:
Ver original
  1. <input type="checkbox" id="chk" onChange="validarchk();" />
  2. <input type="text" disabled="disabled" id="txt" />
  3. </form>
  4.  
  5.  
  6.  
  7. function validarchk(){
  8. var chk = document.getElementById('chk');
  9. var txt = document.getElementById('txt');
  10. if(chk.checked){
  11.     txt.disabled='';
  12. }else{
  13.     txt.value='';
  14.     txt.disabled='disabled';
  15. }
  16. }
__________________
<?="Hello World"?> -> si te gustÓ dale +1
  #4 (permalink)  
Antiguo 14/03/2012, 19:30
 
Fecha de Ingreso: septiembre-2010
Mensajes: 74
Antigüedad: 13 años, 7 meses
Puntos: 1
Respuesta: quiero habilitar textbox al tildar checkbox

Cita:
Iniciado por xxxivanxxx Ver Mensaje
como bien dise neglivv tienes que usar JS, con el evento onChange se hace un poco facil mira:

Código HTML:
Ver original
  1. <input type="checkbox" id="chk" onChange="validarchk();" />
  2. <input type="text" disabled="disabled" id="txt" />
  3. </form>
  4.  
  5.  
  6.  
  7. function validarchk(){
  8. var chk = document.getElementById('chk');
  9. var txt = document.getElementById('txt');
  10. if(chk.checked){
  11.     txt.disabled='';
  12. }else{
  13.     txt.value='';
  14.     txt.disabled='disabled';
  15. }
  16. }
desde ya muchas gracias por tu respuesta xxxivanxxx y a ti tambien neglivv, el problema es que la pagiina esta en php, no en html. Y creo que no se puede integrar java en php. por lo que no podria aplicar la solucion que me brindaron
  #5 (permalink)  
Antiguo 14/03/2012, 21:09
Avatar de xxxivanxxx  
Fecha de Ingreso: julio-2010
Ubicación: /home
Mensajes: 114
Antigüedad: 13 años, 8 meses
Puntos: 21
Respuesta: quiero habilitar textbox al tildar checkbox

Cita:
el problema es que la pagiina esta en php, no en html
PHP es el lenguaje de programacion, lo que muestra en tu pantalla (el resultado) es HTML, asi que puedes combinar tu codigo PHP y JS
asi:

Código Combine:
Ver original
  1. <?php
  2. //codigophp
  3. ?>
  4. codigo html;
  5. <script>
  6. //codigo js
  7. </script>
-------------------------------------------------------------------------------------------------
Cita:
Y creo que no se puede integrar java en php.
creo que estas confundiendo, no es JAVA es JAVASCRIPT y perfectamente funciona :)
__________________
<?="Hello World"?> -> si te gustÓ dale +1
  #6 (permalink)  
Antiguo 15/03/2012, 06:51
 
Fecha de Ingreso: septiembre-2010
Mensajes: 74
Antigüedad: 13 años, 7 meses
Puntos: 1
Respuesta: quiero habilitar textbox al tildar checkbox

Cita:
Iniciado por xxxivanxxx Ver Mensaje
PHP es el lenguaje de programacion, lo que muestra en tu pantalla (el resultado) es HTML, asi que puedes combinar tu codigo PHP y JS
asi:

Código Combine:
Ver original
  1. <?php
  2. //codigophp
  3. ?>
  4. codigo html;
  5. <script>
  6. //codigo js
  7. </script>
-------------------------------------------------------------------------------------------------

creo que estas confundiendo, no es JAVA es JAVASCRIPT y perfectamente funciona :)
Hola xxxivanxxx, te comento que tenias razon, pude meter el codigo javascript sin problemas, el problema es que nose porque solo me funciona con el primer tilde y textbox. Las otras textbox siguen desabilitadas asi las tilde o no.
el codigo quedo asi
Código PHP:
<?php
include_once 'lib.php';


$conexionmysql_connect($dbhost$dbuser$dbpassword);
mysql_select_db($database$conexion);
$result mysql_query("SELECT id_stock, codigo, descrip, pre_min, pre_may, disponibles  FROM stock where activo = '1'"$conexion);

echo
"<form name='borrar' method='post' action='vender_prod.php'>";
echo
"<table border='2'>
<tr>
    <th>ID</th>
    <th>Codigo</th>
    <th>Descrip</th>
    <th>Prec.Min</th>
    <th>Prec.May</th>
    <th>Disponibles</th>
    <th></th>
    <th style='border: none'></th>
    <th>Cantidad</th>
    
</tr>"
;
$i=0;
while(
$row mysql_fetch_array($result)){
    
    echo 
"<tr>
        <td>$row[id_stock]</td>
        <td>$row[codigo]</td>
        <td>$row[descrip]</td>
        <td align=right>$$row[pre_min]</td>
        <td align=right>$$row[pre_may]</td>
        <td align=center>$row[disponibles]</td>
        <td><input id='chk' name='seleccion[]' type='checkbox' value=$row[id_stock] onclick='validarchk();'></td>
        <td style='border: none'></td>
        <td><input id='txt' name='text[$row[id_stock]]' disabled='disabled' type='text' style='width: 60'></td>  
        </tr>"
;
        
    
$i++;
}
echo 
"</table>";
echo 
"<br>";
echo 
"<input type='submit' name='submit' value='enviar'>";
echo 
"</form>";  
?>
<script>
 
function validarchk(){
var chk = document.getElementById('chk');
var txt = document.getElementById('txt');
if(chk.checked){
    txt.disabled='';
}else{
    txt.value='';
    txt.disabled='disabled';
}
}
</script>
Que puede ser???
  #7 (permalink)  
Antiguo 15/03/2012, 06:57
Avatar de h2swider  
Fecha de Ingreso: julio-2007
Ubicación: Ciudad de Buenos Aires
Mensajes: 932
Antigüedad: 16 años, 9 meses
Puntos: 194
Respuesta: quiero habilitar textbox al tildar checkbox

Cita:
Iniciado por tesistas Ver Mensaje
desde ya muchas gracias por tu respuesta xxxivanxxx y a ti tambien neglivv, el problema es que la pagiina esta en php, no en html. Y creo que no se puede integrar java en php. por lo que no podria aplicar la solucion que me brindaron
JavaScript es lo mas alejado a java que te puedas imaginar. Necesitas leer un poco de php para entender lo básico de programación web.

HTML
Programación servidor PHP
Programación cliente Javascript

Los 3 estas en contacto constante en la mayoría de las aplicaciones web existentes.
__________________
Codifica siempre como si la persona que finalmente mantedra tu código sea un psicópata violento que sabe donde vives
  #8 (permalink)  
Antiguo 15/03/2012, 06:59
Avatar de h2swider  
Fecha de Ingreso: julio-2007
Ubicación: Ciudad de Buenos Aires
Mensajes: 932
Antigüedad: 16 años, 9 meses
Puntos: 194
Respuesta: quiero habilitar textbox al tildar checkbox

Cita:
Iniciado por tesistas Ver Mensaje
Hola xxxivanxxx, te comento que tenias razon, pude meter el codigo javascript sin problemas, el problema es que nose porque solo me funciona con el primer tilde y textbox. Las otras textbox siguen desabilitadas asi las tilde o no.
el codigo quedo asi
Código PHP:
<?php
include_once 'lib.php';


$conexionmysql_connect($dbhost$dbuser$dbpassword);
mysql_select_db($database$conexion);
$result mysql_query("SELECT id_stock, codigo, descrip, pre_min, pre_may, disponibles  FROM stock where activo = '1'"$conexion);

echo
"<form name='borrar' method='post' action='vender_prod.php'>";
echo
"<table border='2'>
<tr>
    <th>ID</th>
    <th>Codigo</th>
    <th>Descrip</th>
    <th>Prec.Min</th>
    <th>Prec.May</th>
    <th>Disponibles</th>
    <th></th>
    <th style='border: none'></th>
    <th>Cantidad</th>
    
</tr>"
;
$i=0;
while(
$row mysql_fetch_array($result)){
    
    echo 
"<tr>
        <td>$row[id_stock]</td>
        <td>$row[codigo]</td>
        <td>$row[descrip]</td>
        <td align=right>$$row[pre_min]</td>
        <td align=right>$$row[pre_may]</td>
        <td align=center>$row[disponibles]</td>
        <td><input id='chk' name='seleccion[]' type='checkbox' value=$row[id_stock] onclick='validarchk();'></td>
        <td style='border: none'></td>
        <td><input id='txt' name='text[$row[id_stock]]' disabled='disabled' type='text' style='width: 60'></td>  
        </tr>"
;
        
    
$i++;
}
echo 
"</table>";
echo 
"<br>";
echo 
"<input type='submit' name='submit' value='enviar'>";
echo 
"</form>";  
?>
<script>
 
function validarchk(){
var chk = document.getElementById('chk');
var txt = document.getElementById('txt');
if(chk.checked){
    txt.disabled='';
}else{
    txt.value='';
    txt.disabled='disabled';
}
}
</script>
Que puede ser???
Lo que pasa es que tienes muchos elementos con el mismo ID, dentro de tu while todos se llaman chk y txt esto esta MAL los ids deben ser unicos.
Aparte de eso, los indices de $row tambien estan mal, necesitan estar entre comillas dobles o simple. Y el </br> lleva una barra para finalizar la etiqueta :S
__________________
Codifica siempre como si la persona que finalmente mantedra tu código sea un psicópata violento que sabe donde vives
  #9 (permalink)  
Antiguo 15/03/2012, 07:05
 
Fecha de Ingreso: septiembre-2010
Mensajes: 74
Antigüedad: 13 años, 7 meses
Puntos: 1
Respuesta: quiero habilitar textbox al tildar checkbox

Cita:
Iniciado por h2swider Ver Mensaje
Lo que pasa es que tienes muchos elementos con el mismo ID, dentro de tu while todos se llaman chk y txt esto esta MAL los ids deben ser unicos
Gracias h2swider, tenes razon, el problema es que no se me ocurre como hacer, ya que los checkbox y los textbox se crean en un while dependiendo de la cantidad de datos que tenga la tabla, no son fijos.

Alguna idea???
  #10 (permalink)  
Antiguo 15/03/2012, 07:14
Avatar de Malenko
Moderador
 
Fecha de Ingreso: enero-2008
Mensajes: 5.323
Antigüedad: 16 años, 3 meses
Puntos: 606
Y utilizar jquery y usar clases o nombres para acceder a los elementos enlugar de los ids.
  #11 (permalink)  
Antiguo 15/03/2012, 07:24
 
Fecha de Ingreso: septiembre-2010
Mensajes: 74
Antigüedad: 13 años, 7 meses
Puntos: 1
Respuesta: quiero habilitar textbox al tildar checkbox

Cita:
Iniciado por Malenko Ver Mensaje
Y utilizar jquery y usar clases o nombres para acceder a los elementos enlugar de los ids.
lo que pasa que es un proyecto grande y todas las otras tablas estan en php
  #12 (permalink)  
Antiguo 15/03/2012, 07:27
Avatar de h2swider  
Fecha de Ingreso: julio-2007
Ubicación: Ciudad de Buenos Aires
Mensajes: 932
Antigüedad: 16 años, 9 meses
Puntos: 194
Respuesta: quiero habilitar textbox al tildar checkbox

aquí tienes algo que te podría servir. Rehice todo tu codigo, espero que sepas agradecerlo.

Saludos

Código PHP:
Ver original
  1. <?php
  2. include_once 'lib.php';
  3.  
  4. $conexion = mysql_connect($dbhost, $dbuser, $dbpassword);
  5. mysql_select_db($database, $conexion);
  6. $result = mysql_query("SELECT id_stock, codigo, descrip, pre_min, pre_may, disponibles  FROM stock where activo = '1'", $conexion);
  7. ?>
  8. <form name="borrar" method="post" action="vender_prod.php">
  9.     <table border="2">
  10.         <tr>
  11.             <th>ID</th>
  12.             <th>Codigo</th>
  13.             <th>Descrip</th>
  14.             <th>Prec.Min</th>
  15.             <th>Prec.May</th>
  16.             <th>Disponibles</th>
  17.             <th></th>
  18.             <th style='border: none'></th>
  19.             <th>Cantidad</th>
  20.  
  21.         </tr>
  22.         <?php
  23.         $i = 0;
  24.         while ($row = mysql_fetch_array($result)) {
  25.             ?>
  26.             <tr>
  27.                 <td><?php echo $row['id_stock'] ?></td>
  28.                 <td><?php echo $row['codigo'] ?></td>
  29.                 <td><?php echo $row['descrip'] ?></td>
  30.                 <td align="right"><?php echo $row['pre_min'] ?></td>
  31.                 <td align="right"><?php echo $row['pre_may'] ?></td>
  32.                 <td align="center"><?php echo $row['disponibles'] ?></td>
  33.                 <td><input id="chk_<?php echo $i ?>" name="seleccion[]" type="checkbox" value="<?php echo$row['id_stock'] ?>" class="chk"/></td>
  34.                 <td style="border: none"></td>
  35.                 <td><input id=txt_<?php echo $i ?>" name="text[<?php $row['id_stock'] ?>]" disabled="disabled" type="text" style="width: 60" class="txt"/></td>  
  36.             </tr>
  37.  
  38.             <?php
  39.             $i++;
  40.         }
  41.         ?>
  42.     </table>
  43.     <br />
  44.     <input type="submit" name="submit" value="enviar">
  45. </form>
  46.  
  47. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  48. <script type="text/javascript">
  49.    
  50.     $(document).ready(function(){
  51.        
  52.         $(".chk").change(function(){
  53.             var comentario = $( '.txt', $( this ).parents ( 'tr' ) );
  54.             if( $(this).is(':checked')){            
  55.                 comentario.removeAttr('disabled');
  56.             } else {
  57.                 comentario.attr('disabled', true);
  58.             }
  59.         });
  60.     });
  61.    
  62. </script>
__________________
Codifica siempre como si la persona que finalmente mantedra tu código sea un psicópata violento que sabe donde vives
  #13 (permalink)  
Antiguo 15/03/2012, 07:29
 
Fecha de Ingreso: septiembre-2010
Mensajes: 74
Antigüedad: 13 años, 7 meses
Puntos: 1
Respuesta: quiero habilitar textbox al tildar checkbox

Cita:
Iniciado por h2swider Ver Mensaje
Lo que pasa es que tienes muchos elementos con el mismo ID, dentro de tu while todos se llaman chk y txt esto esta MAL los ids deben ser unicos.
Aparte de eso, los indices de $row tambien estan mal, necesitan estar entre comillas dobles o simple. Y el </br> lleva una barra para finalizar la etiqueta :S
hola h2swider, se podria hacer algo asi ??

Código PHP:
while($row mysql_fetch_array($result)){
    
    echo 
"<tr>
        <td>$row[id_stock]</td>
        <td>$row[codigo]</td>
        <td>$row[descrip]</td>
        <td align=right>$$row[pre_min]</td>
        <td align=right>$$row[pre_may]</td>
        <td align=center>$row[disponibles]</td>
        <td><input id='chk[$row[id_stock]]' name='seleccion[]' type='checkbox' value=$row[id_stock] onChange='validarchk($row[id_stock]);'></td>
        <td style='border: none'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
        <td><input id='txt[$row[id_stock]]' name='text[$row[id_stock]]' disabled='disabled' type='text' style='width: 60'></td>  
        </tr>"
;
        
    
$i++;
}


<
script>
 
function 
validarchk(id){
var 
chk document.getElementById('chk');
var 
txt document.getElementById('txt');
if(
chk[id].checked){
    
txt[id].disabled='';
}else{
    
txt[id].value='';
    
txt[id].disabled='disabled';
}
}
</script> 
osea pasarle el $row[id_stock] para asi hacer un nombre compuesto el cual no se repetira. pero nose como hacerlo ya que nose javascript
  #14 (permalink)  
Antiguo 15/03/2012, 07:32
Avatar de h2swider  
Fecha de Ingreso: julio-2007
Ubicación: Ciudad de Buenos Aires
Mensajes: 932
Antigüedad: 16 años, 9 meses
Puntos: 194
Respuesta: quiero habilitar textbox al tildar checkbox

Cita:
Iniciado por tesistas Ver Mensaje
hola h2swider, se podria hacer algo asi ??

osea pasarle el $row[id_stock] para asi hacer un nombre compuesto el cual no se repetira. pero nose como hacerlo ya que nose javascript
No, no se pueden tratar de esa forma los elementos. El código que te pase arriba debería funcionarte, ademas de eso también limpie y arregle mucho tu código anterior.

Solo arregla esto de la linea 33 echo$row que me quedo mal, luego el código debería funcionarte sin ningún otro cambio
__________________
Codifica siempre como si la persona que finalmente mantedra tu código sea un psicópata violento que sabe donde vives

Última edición por h2swider; 15/03/2012 a las 07:40
  #15 (permalink)  
Antiguo 15/03/2012, 07:41
 
Fecha de Ingreso: septiembre-2010
Mensajes: 74
Antigüedad: 13 años, 7 meses
Puntos: 1
Respuesta: quiero habilitar textbox al tildar checkbox

Cita:
Iniciado por h2swider Ver Mensaje
aquí tienes algo que te podría servir. Rehice todo tu codigo, espero que sepas agradecerlo.

Saludos

Código PHP:
Ver original
  1. <?php
  2. include_once 'lib.php';
  3.  
  4. $conexion = mysql_connect($dbhost, $dbuser, $dbpassword);
  5. mysql_select_db($database, $conexion);
  6. $result = mysql_query("SELECT id_stock, codigo, descrip, pre_min, pre_may, disponibles  FROM stock where activo = '1'", $conexion);
  7. ?>
  8. <form name="borrar" method="post" action="vender_prod.php">
  9.     <table border="2">
  10.         <tr>
  11.             <th>ID</th>
  12.             <th>Codigo</th>
  13.             <th>Descrip</th>
  14.             <th>Prec.Min</th>
  15.             <th>Prec.May</th>
  16.             <th>Disponibles</th>
  17.             <th></th>
  18.             <th style='border: none'></th>
  19.             <th>Cantidad</th>
  20.  
  21.         </tr>
  22.         <?php
  23.         $i = 0;
  24.         while ($row = mysql_fetch_array($result)) {
  25.             ?>
  26.             <tr>
  27.                 <td><?php echo $row['id_stock'] ?></td>
  28.                 <td><?php echo $row['codigo'] ?></td>
  29.                 <td><?php echo $row['descrip'] ?></td>
  30.                 <td align="right"><?php echo $row['pre_min'] ?></td>
  31.                 <td align="right"><?php echo $row['pre_may'] ?></td>
  32.                 <td align="center"><?php echo $row['disponibles'] ?></td>
  33.                 <td><input id="chk_<?php echo $i ?>" name="seleccion[]" type="checkbox" value="<?php echo$row['id_stock'] ?>" class="chk"/></td>
  34.                 <td style="border: none"></td>
  35.                 <td><input id=txt_<?php echo $i ?>" name="text[<?php $row['id_stock'] ?>]" disabled="disabled" type="text" style="width: 60" class="txt"/></td>  
  36.             </tr>
  37.  
  38.             <?php
  39.             $i++;
  40.         }
  41.         ?>
  42.     </table>
  43.     <br />
  44.     <input type="submit" name="submit" value="enviar">
  45. </form>
  46.  
  47. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  48. <script type="text/javascript">
  49.    
  50.     $(document).ready(function(){
  51.        
  52.         $(".chk").change(function(){
  53.             var comentario = $( '.txt', $( this ).parents ( 'tr' ) );
  54.             if( $(this).is(':checked')){            
  55.                 comentario.removeAttr('disabled');
  56.             } else {
  57.                 comentario.attr('disabled', true);
  58.             }
  59.         });
  60.     });
  61.    
  62. </script>
Anduvo impresionante, nunca nadie me dio una mano tan grande. GRACIAS h2swider, SOS LO MAXIMO!!

Etiquetas: checkbox, habilitar, mysql, quiero, tabla, textbox, usuarios
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta

SíEste tema le ha gustado a 1 personas




La zona horaria es GMT -6. Ahora son las 23:48.