Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

Cambiar color input text y Habilitar / Deshabilitar input text con JavaScript

Tiempo de lectura: 2 minutos

Buenos días compañeros, hoy os he preparado un tutorial como realizar una serie de acciones sobre un formulario, haciendo uso de DOM en Java Script para el acceso a elementos de un formulario.

DOM (Document Object Model), permite acceder, modificar, eliminar, etc de forma dinámica a los diferentes elementos de un HTML.

Os voy a dejar un ejemplo muy sencillo.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DevCodeLight</title>
</head>
<body>
<script>
function cambiarUno(elemento){
if(elemento.id=="rojo"){
for(element of document.form.elements){
if(element.type=="text"){
element.style.color="red";
}
}
}
if(elemento.id=="azul"){
for(element of document.form.elements){
if(element.type=="text") {
element.style.color="blue";
}
}
}
}
function cambiarDos(elemento){
if(elemento.id=="hab"){
for(element of document.form.elements){
if(element.type=="text") {
element.disabled=false;
}
}
}
if(elemento.id=="desab"){
for(element of document.form.elements){
if(element.type=="text") {
element.disabled=true;
}
}
}
}
</script>
<form name="form">
Nombre: <input type="text" id="nombre" name="nombre" /></br>
Apellidos: <input type="text" id="app" name="app" /></br>
Dirección: <input type="text" id="dir" name="dir" /></br>
Teléfono: <input type="text" id="tel" name="tel" /></br>
Edad: <input type="text" id="edad" name="edad" /></br>
<input type="button" value="Texto rojo" id="rojo" name="rojo" onclick="cambiarUno(this);" />
<input type="button" value="Texto azul" id="azul" name="azul" onclick="cambiarUno(this);" />
<input type="button" value="Habilitar" id="hab" name="hab" onclick="cambiarDos(this);" />
<input type="button" value="Deshabilitar" id="desab" name="desab" onclick="cambiarDos(this);" />
</form>
<div id="miDiv"></div>
</body>
</html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>DevCodeLight</title> </head> <body> <script> function cambiarUno(elemento){ if(elemento.id=="rojo"){ for(element of document.form.elements){ if(element.type=="text"){ element.style.color="red"; } } } if(elemento.id=="azul"){ for(element of document.form.elements){ if(element.type=="text") { element.style.color="blue"; } } } } function cambiarDos(elemento){ if(elemento.id=="hab"){ for(element of document.form.elements){ if(element.type=="text") { element.disabled=false; } } } if(elemento.id=="desab"){ for(element of document.form.elements){ if(element.type=="text") { element.disabled=true; } } } } </script> <form name="form"> Nombre: <input type="text" id="nombre" name="nombre" /></br> Apellidos: <input type="text" id="app" name="app" /></br> Dirección: <input type="text" id="dir" name="dir" /></br> Teléfono: <input type="text" id="tel" name="tel" /></br> Edad: <input type="text" id="edad" name="edad" /></br> <input type="button" value="Texto rojo" id="rojo" name="rojo" onclick="cambiarUno(this);" /> <input type="button" value="Texto azul" id="azul" name="azul" onclick="cambiarUno(this);" /> <input type="button" value="Habilitar" id="hab" name="hab" onclick="cambiarDos(this);" /> <input type="button" value="Deshabilitar" id="desab" name="desab" onclick="cambiarDos(this);" /> </form> <div id="miDiv"></div> </body> </html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DevCodeLight</title>
</head>
<body>
    <script>
    function cambiarUno(elemento){
        if(elemento.id=="rojo"){
            for(element of document.form.elements){
                if(element.type=="text"){
                    element.style.color="red";
                }
            }
        }
        if(elemento.id=="azul"){
            for(element of  document.form.elements){
                if(element.type=="text") {
                    element.style.color="blue";
                }
            }     
        }        
    }
        
    function cambiarDos(elemento){
        
        if(elemento.id=="hab"){
            for(element of document.form.elements){
                if(element.type=="text") {
                    element.disabled=false;
                }
            }
        }
        if(elemento.id=="desab"){
            for(element of document.form.elements){
                if(element.type=="text") {
                    element.disabled=true;
                }
            }
        }
    }
        </script>
             <form name="form">
                Nombre: <input type="text" id="nombre" name="nombre" /></br>
                Apellidos: <input type="text" id="app" name="app" /></br>
                Dirección: <input type="text" id="dir" name="dir" /></br>
                Teléfono: <input type="text" id="tel" name="tel" /></br>
                Edad: <input type="text" id="edad" name="edad" /></br>
        
                <input type="button" value="Texto rojo" id="rojo" name="rojo" onclick="cambiarUno(this);" />
                <input type="button" value="Texto azul" id="azul" name="azul" onclick="cambiarUno(this);" />
                <input type="button" value="Habilitar" id="hab" name="hab" onclick="cambiarDos(this);" />
                <input type="button" value="Deshabilitar" id="desab" name="desab" onclick="cambiarDos(this);" />
            </form>
            <div id="miDiv"></div>
</body>
</html>

Lo que hacemos es lo siguiente:

La función function cambiarUno(elemento) se encarga del color del texto. Lo que decimos es que, si el id del elemento input que hemos creado abajo, es «rojo«, recorra todo el documento y los elementos del formulario, y a contuniación lo que le decimos es que si el elemento es de tipo «text«, cambie la propiedad style del elemento de tipo texto a rojo. Para el caso de cambiar el texto a azul, lo mismo.

En el caso de la función function cambiarDos(elemento), se encarga de los input text. Lo que decimos es que, si el id del elemento input que hemos creado abajo es «hab» recorra todo el documento y los elementos del formulario, y a continuación lo que le decimos es que si el elemento es de tipo «text«, habilite el elemento input. Para el caso de deshabilitar los input igual, pero evaluándo el id «desab«

Por lo que en el HTML lo que hacemos es que, en los input de tipo «button» que son los que queremos que hagan la función, les añadimos el elemento onclick (este evento ocurre cuándo el usuario hace click en un elemento), ejecuta esa función el propio botón, por eso ponemos el onclick=»cambiarUno(this);» (ejem: el this, evalúa el elemento que le hemos indicado en la función, cada vez que lo pulsamos evalua el elemento y por eso hace una cosa u otra, dependiendo de lo que hayamos pulsado. Lo mismo para el onclick=»cambiarDos(this);

Espero que os ayude y os sirva para aprender, nos vemos en el siguiente 🙂

3

Deja un comentario