diff options
Diffstat (limited to 'files/it/web/html/element/input')
| -rw-r--r-- | files/it/web/html/element/input/file/index.html | 520 | ||||
| -rw-r--r-- | files/it/web/html/element/input/index.html | 576 |
2 files changed, 1096 insertions, 0 deletions
diff --git a/files/it/web/html/element/input/file/index.html b/files/it/web/html/element/input/file/index.html new file mode 100644 index 0000000000..1c67ba6c45 --- /dev/null +++ b/files/it/web/html/element/input/file/index.html @@ -0,0 +1,520 @@ +--- +title: <input type="file"> +slug: Web/HTML/Element/input/file +translation_of: Web/HTML/Element/input/file +--- +<div>{{HTMLRef}}</div> + +<p><span class="seoSummary">Gli elementi {{HTMLElement("input")}} con <strong><code>type="file"</code></strong> danno all'utente la possibilità di scegliere uno o più file dalla memoria del proprio dispositivo. Una volta scelti, i file possono essere caricati su un server usando l'<a href="/it/docs/Learn/HTML/Forms">invio del modulo</a>, oppure manipolati usando del codice JavaScript e l'<a href="/it/docs/Web/API/File/Using_files_from_web_applications">API File</a></span></p> + +<div>{{EmbedInteractiveExample("pages/tabbed/input-file.html", "tabbed-shorter")}}</div> + +<div class="hidden">Il codice sorgente di questo esempio interattivo è salvato in un repository GitHub. Se volessi contribuire al progetto di esempi interattivi, clona <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> ed inviaci una "pull request".</div> + +<table class="properties"> + <tbody> + <tr> + <td><strong>{{anch("Value")}}</strong></td> + <td>Una {{domxref("DOMString")}} che rappresenta il percorso del file selezionato.</td> + </tr> + <tr> + <td><strong>Eventi</strong></td> + <td>{{domxref("HTMLElement/change_event", "change")}} e {{domxref("HTMLElement/input_event", "input")}}</td> + </tr> + <tr> + <td><strong>Attributi comuni supportati</strong></td> + <td>{{htmlattrxref("required", "input")}}</td> + </tr> + <tr> + <td><strong>Attributi aggiuntivi</strong></td> + <td>{{htmlattrxref("accept", "input/file")}}, {{htmlattrxref("capture", "input/file")}}, {{htmlattrxref("files", "input/file")}}, {{htmlattrxref("multiple", "input/file")}}</td> + </tr> + <tr> + <td><strong>Attributi IDL</strong></td> + <td><code>files</code> e <code>value</code></td> + </tr> + <tr> + <td><strong>Interfaccia DOM</strong></td> + <td> + <p>{{domxref("HTMLInputElement")}}</p> + </td> + </tr> + <tr> + <td><strong>Proprietà</strong></td> + <td> + <p><a href="/it/docs/Web/API/HTMLInputElement#Properties_file">Proprietà che si applicano soload elementi di tipo file</a></p> + </td> + </tr> + <tr> + <td><strong>Metodi</strong></td> + <td>{{domxref("HTMLInputElement.select", "select()")}}</td> + </tr> + </tbody> +</table> + +<h2 id="Value">Value</h2> + +<p>L'attributo <code>value</code> di un <code>file</code> contiene una {{domxref("DOMString")}} che rappresenta il percorso del file selezionato. Se l'utente seleziona più di un file, l'attributo <code>value</code> rappresenta il primo file nella lista di quelli selezionati. Gli altri file possono essere identificati usando la proprietà <code>HTMLInputElement.files</code>.</p> + +<div class="note"><strong>Note:</strong> + +<ol> + <li>Se vengono selezionati più file, la stringa rappresenta il primo. JavaScript può accedere agli atri file <a href="/it/docs/Using_files_from_web_applications#Getting_information_about_selected_files">attraverso la proprietà <code>files</code> dell'elemento <code>input</code></a></li> + <li>Se non è stato ancora selezionato nessun file, la stringa è <code>""</code> (vuota)</li> + <li>Alla stringa viene aggiunto il prefisso <code>C:\fakepath\</code>, per impedire a software malevolo di intuire la struttura del filesystem dell'utente.</li> +</ol> +</div> + +<h2 id="Attributi_aggiuntivi">Attributi aggiuntivi</h2> + +<p>In aggiunta agli attributi comuni a tutti gli elementi {{HTMLElement("input")}}, gli <code>input</code> di tipo <code>file</code> supportano anche i seguenti: </p> + + + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Attributo</th> + <th scope="col">Descrizone</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>{{anch("accept")}}</code></td> + <td>Uno o più {{anch("Identificatori univoci del tipo di file", "Identificatori univoci del tipo di file")}} che descrivono i tipi di file ammessi</td> + </tr> + <tr> + <td><code>{{anch("capture")}}</code></td> + <td>La sorgente da utilizzare per catturare immagini o dati video</td> + </tr> + <tr> + <td><code>{{anch("files")}}</code></td> + <td>Una {{domxref("FileList")}} che elenca i file scelti</td> + </tr> + <tr> + <td><code>{{anch("multiple")}}</code></td> + <td>Un valore booleano che, se presente, indica che l'utente può selezionare più di un file</td> + </tr> + </tbody> +</table> + +<h3 id="htmlattrdefaccept">{{htmlattrdef("accept")}}</h3> + +<p>Il valore dell'attributo <code><a href="/it/docs/Web/HTML/Attributes/accept">accept</a></code> è una stringa che definisce i tipi di file che l'<code>input</code> accetta.<br> + La stringa è un lista di <strong>{{anch("Identificatori univoci del tipo di file", "Identificatori univoci del tipo di file")}}</strong> separati da virgola. Poiché un determinato tipo di file può essere identificato in più di un modo, è utile fornire un set completo di identificatori di tipo quando sono necessari file di un determinato formato.</p> + +<p>Per esempio, ci sono diversi modi in cui un file di Microsoft Word può essere identificato, quindi un sito che accetta file di Word dovrebbe utilizzare un <code>input</code> come questo:</p> + +<pre class="brush: html"><input type="file" id="docpicker" + accept=".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"></pre> + +<h3 id="htmlattrdefcapture">{{htmlattrdef("capture")}}</h3> + +<p>Il valore dell'attributo <code><a href="/it/docs/Web/HTML/Attributes/capture">capture</a></code> è una stringa che specifica quale camera utilizzare per catturare immagini o dati video, se l'attributo <code><a href="/it/docs/Web/HTML/Attributes/accept">accept</a></code> indica che l'input possa essere di uno di questi due tipi. Il valore <code>user</code> indica che devono essere usati il microfono e/o la camera frontali (lato utente). Il valore <code>environment</code> specifica che devono essere usati il microfono e/o la camera posteriori (lato ambiente). Se l'attributo manca, lo {{Glossary("user agent")}} è libero di scegliere quale tra i due utilizzare secodo le proprie specifiche. Se lo strumento di cattura indicato non è presente, lo {{Glossary("user agent")}} può far ricadere la scelta sulla propria modalità predefinita.</p> + +<div class="note"><strong>Note:</strong> <code>capture</code> originariamente era un attributo booleano che, se presente, richiedeva l'utilizzo di un dispositivo di acquisizione multimediale invece del caricamento di un file.</div> + +<h3 id="htmlattrdeffiles">{{htmlattrdef("files")}}</h3> + +<p>Un oggetto {{domxref("FileList")}} che elenca tutti i file selezionati. Questa lista contiene al massimo un elemento, salvo che non sia stato specificato l'attributo {{htmlattrxref("multiple", "input/file")}}.</p> + +<h3 id="htmlattrdefmultiple">{{htmlattrdef("multiple")}}</h3> + +<p>Quando l'attributo booleano <a href="/en-US/docs/Web/HTML/Attributes/multiple"><code>multiple</code></a> è specificato, il controllo consente di caricare più di un file.</p> + +<h2 id="Attributi_non_standard">Attributi non standard</h2> + +<p>Oltre agli atributi elencati sopra, su alcuni browser sono disponibili anche i seguenti attributi. In generale è consigliabile evitarne l'utilizzo laddove possibile, per consentire una completa funzionalità anche sui browser che non li implementano.</p> + +<table class="standard-table" style=""> + <thead> + <tr> + <th scope="col">Attribute</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>{{anch("webkitdirectory")}}</code></td> + <td> + <p>Un valore booleano che indica se consentire o meno di poter selezionare una o più cartelle (se è presente anche l'attributo <code>{{anch("multiple")}}</code>)</p> + </td> + </tr> + </tbody> +</table> + +<h3 id="htmlattrdefwebkitdirectory_non-standard_inline">{{htmlattrdef("webkitdirectory")}} {{non-standard_inline}}</h3> + +<div id="webkitdirectory-include"> +<p>L'attributo booleano <code>webkitdirectory</code> indica, se presente, che possono essere selezionate solo cartelle nell'interfaccia di selezione dell'utente. Si veda {{domxref("HTMLInputElement.webkitdirectory")}} per ulteriori esempi.</p> + +<div class="note"> +<p><strong>Note:</strong> Anche se originariamente implementato solo per i browser basati su WebKit, l'attributo <code>webkitdirectory</code> è utilizzabile anche su Microsoft Edge e Firefox 50 o superiori. Comunque, anche se ha un supporto relativemente ampio, non è uno standard e dovrebbe essere evitato laddove non strettamente necessario.</p> +</div> +</div> + +<h2 id="Identificatori_univoci_del_tipo_di_file">Identificatori univoci del tipo di file</h2> + +<p>Un <strong>identificatore univoco del tipo di file</strong> è una stringa che descrive un tipo di file che può essere selezionato dall'utente in una elemento {{HTMLElement("input")}} di tipo <code>file</code>. Ogni identificatore univoco del tipo di file può avere una delle seguenti forme:</p> + +<ul> + <li>Una estensione di nomi file valida, che inizia con un carattere di punto ("."). E.g.: <code>.jpg</code>, <code>.pdf</code> o <code>.doc</code>.</li> + <li>Una stringa identificativa di un MIME-type, senza estensione.</li> + <li>La stringa <code>audio/*</code> ad indicare "qualunque file audio".</li> + <li>La stringa <code>video/*</code> ad indicare "qualunque file video".</li> + <li>La stringa <code>image/*</code> ad indicare "qualunque file immagine".</li> +</ul> + +<p>L'attributo <code>accept</code> assume come valore una stringa contenente uno o più di questi identificatori univoci del tipo di file, separati da virgole. Per esempio, </p> + +<p>The <code>accept</code> attribute takes as its value a string containing one or more of these unique file type specifiers, separated by commas. Per esempio, un selettore di file che necessiti di contenuto che possa essere rappresentato come un'immagine, inclusi sia i formati immagine standard che file PDF, potrebbe apparire così:</p> + +<pre class="brush: html"><input type="file" accept="image/*,.pdf"></pre> + +<h2 id="Utilizzo_degli_input_di_tipo_file">Utilizzo degli input di tipo file</h2> + +<h3 id="Un_esempio_base">Un esempio base</h3> + +<pre class="brush: html"><form method="post" enctype="multipart/form-data"> + <div> + <label for="file">Scegli un file da caricare</label> + <input type="file" id="file" name="file" multiple> + </div> + <div> + <button>Invia</button> + </div> +</form></pre> + +<div class="hidden"> +<pre class="brush: css">div { + margin-bottom: 10px; +}</pre> +</div> + +<p>Produce l'output seguente:</p> + +<p>{{EmbedLiveSample('Un_esempio_base', 650, 60)}}</p> + +<div class="note"> +<p><strong>Note</strong>: Puoi trovare questo esempio, in lingua inglese, anche su GitHub — qui puoi trovarne i sorgenti <a href="https://github.com/mdn/learning-area/blob/master/html/forms/file-examples/simple-file.html">i sorgenti</a>, ed anche una <a href="https://mdn.github.io/learning-area/html/forms/file-examples/simple-file.html">una dimostrazione di funzionamento</a>.</p> +</div> + +<p>Indipendentemente dal sistema operativo o dal dispositivo dell'utente, il file input fornisce un bottone che apre una finestra di selezione che consente all'utente di scegliere un file.</p> + +<p>Includendo l'attributo {{htmlattrxref("multiple", "input/file")}}, come mostrato di seguito, specifica che possono essere selezionati più file in un'unica istanza. L'utente può selezionare più file in un qualunque modo consentito dalla propria piattaforma (ad esempio tenendo premuto il tasto <kbd>Shift</kbd> o <kbd>Ctrl</kbd>, e quindi cliccando). Se si desidera che l'utente scelga un solo file per <code><input></code> è sufficiente omettere l'attributo <code>multiple</code>.</p> + +<h3 id="Ottenere_informazioni_sui_file_selezionati">Ottenere informazioni sui file selezionati</h3> + +<p>I file selezionati sono restituiti dalla proprietà dell'elemento <code>HTMLInputElement.files</code>, che è un oggetto {{domxref("FileList")}} contenente una lista di oggetti {{domxref("File")}}. La <code>FileList</code> si comporta come un'array, quindi si può controllarne la proprietà <code>length</code> per conoscere il numero di file selezionati.</p> + +<p>Ogni oggetto <code>File</code> contiene le seguenti informazioni:</p> + +<dl> + <dt><code>name</code></dt> + <dd>Il nome del file</dd> + <dt><code>lastModified</code></dt> + <dd>Un numero che indica la data e l'ora dell'ultima modifica, espressa in millisecondi dalla "UNIX epoch" (1° Gennaio 1970 a mezzanotte).</dd> + <dt><code>lastModifiedDate</code> {{deprecated_inline}}</dt> + <dd>Un oggetto {{jsxref("Date")}} che rappresenta la data e l'ora dell'ultuima modifica. <em>La proprietà è deprecata e non dovrebbe essere utilizzata. Al suo posto utilizzare la proprietà <code>lastModified</code>.</em></dd> + <dt><code>size</code></dt> + <dd>La dimensione del file in byte.</dd> + <dt><code>type</code></dt> + <dd>Il <a href="/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types">MIME-type</a> del file.</dd> + <dt><code>webkitRelativePath</code> {{non-standard_inline}}</dt> + <dd>Una stringa che rappresenta il perorso del file relativo alla cartella selezionata in un appostito selettore di cartelle (i.g. un selettore di file in cui l'attributo {{htmlattrxref("webkitdirectory", "input/file")}} è stato impostato). <em>Non è una proprietà standard e va utilizzata con attenzione</em></dd> +</dl> + +<div class="note"> +<p><strong>Note</strong>: È possibile leggere e scrivere il valore di <code>HTMLInputElement.files</code> in tutti i browser più recenti; in Firefox è stato in all modern browsers; su Firefox questa caratteristica è stata aggiunta di recente, nella versione 57 (si veda {{bug(1384030)}}).</p> +</div> + +<h3 id="Limitare_i_tipi_di_file_accettati">Limitare i tipi di file accettati</h3> + +<p>Spesso si ha la necessità che l'utente non si libero di selezionare arbitrariamente qualunque tipologia di file; quanto piuttosto consentire che possa selezionare file di un tipo specifico. Per esempio, se un file input consente agli utenti di caricare un'immagine di profilo, molto probabilmente occorrerà consentire solo il aricamento di formati immagine compatibili con il web, come {{Glossary("JPEG")}} o {{Glossary("PNG")}}.</p> + +<p>I tipi di file accettati possono essere specificati con l'attributo {{htmlattrxref("accept","input/file")}}, che prende una lista di estensioni consentite o MIME-type, separate da virgola. Ecco alcuni esempi:</p> + +<ul> + <li><code>accept="image/png"</code> o <code>accept=".png"</code> — Accetta file PNG.</li> + <li><code>accept="image/png, image/jpeg"</code> o <code>accept=".png, .jpg, .jpeg"</code> — Accetta file PNG o JPEG.</li> + <li><code>accept="image/*"</code> — Accetta qualunque file con MIME-type <code>image/*</code>. (Molti dispositivi mobili consentono all'utente di scattare una foto quando viene specificato questo formato)</li> + <li><code>accept=".doc,.docx,.xml,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"</code> — accetta qualunque file che sembri un documento di MS Word.</li> +</ul> + +<p>Osserviamo un esempio più completo:</p> + +<pre class="brush: html"><form method="post" enctype="multipart/form-data"> + <div> + <label for="profile_pic">Scegli un file da caricare</label> + <input type="file" id="profile_pic" name="profile_pic" + accept=".jpg, .jpeg, .png"> + </div> + <div> + <button>Invia</button> + </div> +</form></pre> + +<div class="hidden"> +<pre class="brush: css">div { + margin-bottom: 10px; +}</pre> +</div> + +<p>Questo produce un output simile a quello dell'esempio precedente:{{EmbedLiveSample('Limitare_i_tipi_di_file_accettati', 650, 60)}}</p> + +<div class="note"> +<p><strong>Note</strong>: L'esempio si trova, nella versione inglese, anche su GitHub — qui puoi trovarne <a href="https://github.com/mdn/learning-area/blob/master/html/forms/file-examples/file-with-accept.html">i sorgenti</a> ed anche una <a href="https://mdn.github.io/learning-area/html/forms/file-examples/file-with-accept.html">dimostrazione di funzionamento</a>.</p> +</div> + +<p>Potrebbe sembrare simile, ma se si prova a selezionare un file, si vedrà che il selettore consente di scegliere solo i tipi di file specificati nell'attributo <code>accept</code> (il comportamento preciso differisce in base al browser ed al filesystem)</p> + +<p><img alt="Screenshot of a macOS file picker dialog. Files other than JPEG are grayed-out and unselectable." src="https://mdn.mozillademos.org/files/15183/file-chooser.png" style="margin: 0 auto;"></p> + +<p>L'attributo accept non valida i tipi dei file selezionati; semplicemente fornisce un suggerimento per il browser per guidare l'utente alla scelta di file del tipo giusto. In molti casi è ancora possibile per l'utente abilitare o disabilitare un'opzione nel selettore di file che rende possibile sovrascrivere questa limitazione e quindi selezionare i file che vuole, scegliendone uno di un tipo non corretto.</p> + +<p>A causa di ciò è buona norma accertarsi che l'attributo accept sia corredato da una corretta validazione lato server.</p> + +<h3 id="Note">Note</h3> + +<ol> + <li> + <p>Non è possibile impostare il valore di un selettore di file da uno script — una operazione del genere non sortisce alcun effetto:</p> + + <pre class="brush: js">const input = document.querySelector("input[type=file]"); +input.value = "foo"; +</pre> + </li> + <li> + <p>Quando un file viene selezionato usando un <code><input type="file"></code>, il percorso reale del file originale non viene mostrato nell'attributo <code>value</code> per ovvie ragioni di sicurezza. Il nome del file invece viene mostrato, con aggiunti il percorso fittizio <code>C:\fakepath\</code> in cima. </p> + </li> + <li> + <p>When a file is chosen using an <code><input type="file"></code>, the real path to the source file is not shown in the input's <code>value</code> attribute for obvious security reasons. Instead, the filename is shown, with <code>C:\fakepath\</code> appended to the beginning of it. Ci sono alcune ragioni storiche per questa stranezza, ma è supportata da tutti i browser moderni ed in effetti è definita nelle specifiche.</p> + </li> +</ol> + +<h2 id="Esempi">Esempi</h2> + +<p>In questo esempio mostreremo un selettore di file leggermente più sofisticato, che sfrutta le informazioni sui file disponibili nella proprietà <code>HTMLInputElement.files</code>, oltre a mostrare qualche trucchetto.</p> + +<div class="note"> +<p><strong>Note</strong>: Puoi trovare il sorgente completo della versione inglese di questo esempio si GitHub — <a href="https://github.com/mdn/learning-area/blob/master/html/forms/file-examples/file-example.html">file-example.html</a> (<a href="https://mdn.github.io/learning-area/html/forms/file-examples/file-example.html">click qui per provarne il comportamento dal vivo</a>). Non ne spiegheremo il CSS, essendo il JavaScript l'obiettivo principale.</p> +</div> + +<p>Per prima cosa osserviamo l'HTML:</p> + +<pre class="brush: html"><form method="post" enctype="multipart/form-data"> + <div> + <label for="image_uploads">Seleziona le immagini da caricare (PNG, JPG)</label> + <input type="file" id="image_uploads" name="image_uploads" accept=".jpg, .jpeg, .png" multiple> + </div> + <div class="preview"> + <p>Nessun file attualmente selezionato</p> + </div> + <div> + <button>Invia</button> + </div> +</form></pre> + +<div class="hidden"> +<pre class="brush: css">html { + font-family: sans-serif; +} + +form { + width: 580px; + background: #ccc; + margin: 0 auto; + padding: 20px; + border: 1px solid black; +} + +form ol { + padding-left: 0; +} + +form li, div > p { + background: #eee; + display: flex; + justify-content: space-between; + margin-bottom: 10px; + list-style-type: none; + border: 1px solid black; +} + +form img { + height: 64px; + order: 1; +} + +form p { + line-height: 32px; + padding-left: 10px; +} + +form label, form button { + background-color: #7F9CCB; + padding: 5px 10px; + border-radius: 5px; + border: 1px ridge black; + font-size: 0.8rem; + height: auto; +} + +form label:hover, form button:hover { + background-color: #2D5BA3; + color: white; +} + +form label:active, form button:active { + background-color: #0D3F8F; + color: white; +}</pre> +</div> + +<p>Questo, ancora una volta, è simile all'esempio precedente - nulla di speciale di cui aggiungere commenti.</p> + +<p>Proseguiamo con il JavaScript.</p> + +<p>Nelle prime righe dello script ricaviamo i riferimenti all'input stesso della form, e l'elemento {{htmlelement("div")}} di classe <code>.preview</code>. In seguito nascondiamo l'elemento {{htmlelement("input")}} — facciamo questa operazione perchè i file input di solito non hanno un bell'aspetto ed hanno uno stile piuttosto inconsistente tra un browser e l'altro. Si potrà quindi attivare l'elemento <code>input</code> cliccando sulla sua {{htmlelement("label")}}, così che sia più comodo nascondele l'input e dare uno stile alla <code>label</code> simile ad un bottone, così che l'utente sappia che si tratti di un elemento interattivo ed interagisca con questo per caricare i file.</p> + +<pre class="brush: js">const input = document.querySelector('input'); +const preview = document.querySelector('.preview'); + +input.style.opacity = 0;</pre> + +<div class="note"> +<p><strong>Note:</strong> La {{cssxref("opacity")}} viene utilizzata per nascondere il file input al posto di {{cssxref("visibility", "visibility: hidden")}} o {{cssxref("display", "display: none")}}, perchè le tecnologie assistive interpretano gli ultimi due stili come un'indicazione che non si tratti di elementi interattivi.</p> +</div> + +<p>A questo punto aggiungiamo un "event listener" all'input, che intercetti il cambio di elementi selezionati (in questo caso qundo i file vengono selezionati). L'event listener invoca la nostra funzione <code>updateImageDisplay()</code>.</p> + +<pre class="brush: js">input.addEventListener('change', updateImageDisplay);</pre> + +<p>Quando viene invocata la funzione <code>updateImageDisplay()</code>:</p> + +<ul> + <li>Usiamo un loop {{jsxref("Statements/while", "while")}} per svuotare il <code><div></code> del contenuto precedente.</li> + <li>Prendiamo l'oggetto {{domxref("FileList")}} che contiene le informazioni di tutti i file selezionati e lo salviamo in una variabile che chiamiamo <code>curFiles</code>.</li> + <li>Controlliamo che non sia selezionato alcun file, verificando che <code>curFiles.length</code> sia ugule a 0, nel qual caso stampiamo un messaggio nel <code><div></code> ad indicare che non ci sono file selezionati.</li> + <li>Se ci sono file selezionati, cicliamo su ciascuno, stampandone le informazioni nel <code><div></code> di anteprima. Da notare:</li> + <li>Usiamo la funzione <code>validFileType()</code> per controllare che il file sia del tipo corretto (e.g. che il tipo di immagine sia tra quelli specificati nell'attributo <code>accept</code>).</li> + <li>Se così fosse: + <ul> + <li>Stampiamo il nome e la dimensione del file in una lista nel preedente <code><div></code>. La funzione <code>returnFileSize()</code> restituisce una versione formattata della dimensione in bytes/KB/MB (di default il browser riporta una dimensione assoluta in bytes)</li> + <li>Generiamo una anteprima in miniatira dell'immagine chiamando {{domxref("URL.createObjectURL", "URL.createObjectURL(curFiles[i])")}}. Quindi inseriamo l'immagine anche nella lista di oggetti creando un nuovo tag {{htmlelement("img")}} ed impostando la sua {{htmlattrxref("src", "img")}} con la miniatura generata.</li> + </ul> + </li> + <li>Se il tipo di file non è valido mostriamo un messaggio nella lista di oggetti per indicare all'utente che deve selezionarne uno di un tipo differente.</li> +</ul> + +<pre class="brush: js">function updateImageDisplay() { + while(preview.firstChild) { + preview.removeChild(preview.firstChild); + } + + const curFiles = input.files; + if(curFiles.length === 0) { + const para = document.createElement('p'); + para.textContent = 'Nessun file selezionato per il caricamento'; + preview.appendChild(para); + } else { + const list = document.createElement('ol'); + preview.appendChild(list); + + for(const file of curFiles) { + const listItem = document.createElement('li'); + const para = document.createElement('p'); + if(validFileType(file)) { + para.textContent = `File ${file.name}, dimensione ${returnFileSize(file.size)}.`; + const image = document.createElement('img'); + image.src = URL.createObjectURL(file); + + listItem.appendChild(image); + listItem.appendChild(para); + } else { + para.textContent = `File ${file.name}: tipo di file non valido. Aggiorna la tua selezione.`; + listItem.appendChild(para); + } + + list.appendChild(listItem); + } + } +}</pre> + +<p>La funzione personlizzata <code>validFileType()</code> prende un oggetto {{domxref("File")}} come parametro, quindi usa {{jsxref("Array.prototype.includes()")}} per verificare che ci sia almeno una corrispondenza con la proprietà <code>type</code> del file. Se viene trovata una corrispodenza la funzione restituisce il valore <code>true</code>, altrimenti <code>false</code>.</p> + +<pre class="brush: js">// https://developer.mozilla.org/it/docs/Web/Media/Formats/Image_types +const fileTypes = [ + "image/apng", + "image/bmp", + "image/gif", + "image/jpeg", + "image/pjpeg", + "image/png", + "image/svg+xml", + "image/tiff", + "image/webp", + "image/x-icon" +]; + +function validFileType(file) { + return fileTypes.includes(file.type); +}</pre> + +<p>La funzione <code>returnFileSize()</code> prende un numero (di byte, preso dalla proprietà <code>size</code>), e lo trasforma in una stringa correttamente formattata in bytes/KB/MB.</p> + +<pre class="brush: js">function returnFileSize(number) { + if(number < 1024) { + return number + 'bytes'; + } else if(number >= 1024 && number < 1048576) { + return (number/1024).toFixed(1) + 'KB'; + } else if(number >= 1048576) { + return (number/1048576).toFixed(1) + 'MB'; + } +}</pre> + +<p>L'esempio è simile al seguente, proviamo:</p> + +<p>{{EmbedLiveSample('Esempi', '100%', 200)}}</p> + +<h2 id="Specifiche">Specifiche</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specifica</th> + <th scope="col">Stato</th> + <th scope="col">Commento</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', 'input.html#file-upload-state-(type=file)', '<input type="file">')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Definzione iniziale</td> + </tr> + <tr> + <td>{{SpecName('HTML5.1', 'sec-forms.html#file-upload-state-typefile', '<input type="file">')}}</td> + <td>{{Spec2('HTML5.1')}}</td> + <td>Definizione iniziale</td> + </tr> + <tr> + <td>{{SpecName('HTML Media Capture', '#the-capture-attribute','capture attribute')}}</td> + <td>{{Spec2('HTML Media Capture')}}</td> + <td>Attributo <code>capture</code> iniziale</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilità_browser">Compatibilità browser</h2> + + + +<p>{{Compat("html.elements.input.input-file")}}</p> + +<h2 id="Vedi_anche">Vedi anche</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/File/Using_files_from_web_applications">Using files from web applications</a> — contiene numerosi altri esempi utili correlati all'<code><input type="file"></code> e alle <a href="/en-US/docs/Web/API/File">File API</a>.</li> + <li><a href="/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls">Compatibility of CSS properties</a></li> +</ul> diff --git a/files/it/web/html/element/input/index.html b/files/it/web/html/element/input/index.html new file mode 100644 index 0000000000..0bc23cfd54 --- /dev/null +++ b/files/it/web/html/element/input/index.html @@ -0,0 +1,576 @@ +--- +title: '<input>: The Input (Form Input) element' +slug: Web/HTML/Element/input +tags: + - Data entry + - Element + - Forms + - HTML + - HTML forms + - HTML input tag + - Input + - MakeBrowserAgnostic + - NeedsBrowserCompatibility + - NeedsMobileBrowserCompatibility + - NeedsTranslation + - Reference + - TopicStub + - Web +translation_of: Web/HTML/Element/input +--- +<div>{{HTMLRef}}</div> + +<p><span class="seoSummary">The <strong>HTML <code><input></code> element</strong> is used to create interactive controls for web-based forms in order to accept data from the user; a wide variety of types of input data and control widgets are available, depending on the device and {{Glossary("user agent")}}.</span></p> + +<div>{{EmbedInteractiveExample("pages/tabbed/input-text.html", "tabbed-shorter")}}</div> + +<div class="hidden">The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</div> + +<h2 id="Form_<input>_types">Form <code><input></code> types</h2> + +<p>How an <code><input></code> works varies considerably depending on the value of its <code>type</code> attribute, hence the different types are covered in their own separate reference pages. If this attribute is not specified, the default type adopted is <code>text</code>.</p> + +<p>The available types are as follows:</p> + +<ul> + <li><code>{{HTMLElement("input/button", "button")}}</code>: A push button with no default behavior.</li> + <li><code>{{HTMLElement("input/checkbox", "checkbox")}}</code>: A check box allowing single values to be selected/deselected.</li> + <li><code>{{HTMLElement("input/color", "color")}}</code>: {{HTMLVersionInline("5")}} A control for specifying a color. A color picker's UI has no required features other than accepting simple colors as text (<a href="https://www.w3.org/TR/html5/forms.html#color-state-(type=color)">more info</a>).</li> + <li><code>{{HTMLElement("input/date", "date")}}</code>: {{HTMLVersionInline("5")}} A control for entering a date (year, month, and day, with no time).</li> + <li><code>{{HTMLElement("input/datetime-local", "datetime-local")}}</code>: {{HTMLVersionInline("5")}} A control for entering a date and time, with no time zone.</li> + <li><code>{{HTMLElement("input/email", "email")}}</code>: {{HTMLVersionInline("5")}} A field for editing an e-mail address.</li> + <li><code>{{HTMLElement("input/file", "file")}}</code>: A control that lets the user select a file. Use the <strong>accept</strong> attribute to define the types of files that the control can select.</li> + <li><code>{{HTMLElement("input/hidden", "hidden")}}</code>: A control that is not displayed but whose value is submitted to the server.</li> + <li><code>{{HTMLElement("input/image", "image")}}</code>: A graphical submit button. You must use the <strong>src</strong> attribute to define the source of the image and the <strong>alt</strong> attribute to define alternative text. You can use the <strong>height</strong> and <strong>width</strong> attributes to define the size of the image in pixels.</li> + <li><code>{{HTMLElement("input/month", "month")}}</code>: {{HTMLVersionInline("5")}} A control for entering a month and year, with no time zone.</li> + <li><code>{{HTMLElement("input/number", "number")}}</code>: {{HTMLVersionInline("5")}} A control for entering a number.</li> + <li><code>{{HTMLElement("input/password", "password")}}</code>: A single-line text field whose value is obscured. Use the <strong>maxlength</strong> and <strong>minlength</strong> attributes to specify the maximum length of the value that can be entered. + <div class="note"><strong>Note</strong>: Any forms involving sensitive information like passwords (e.g. login forms) should be served over HTTPS; Firefox now implements multiple mechanisms to warn against insecure login forms — see <a href="/en-US/docs/Web/Security/Insecure_passwords">Insecure passwords</a>. Other browsers are also implementing similar mechanisms.</div> + </li> + <li><code>{{HTMLElement("input/radio", "radio")}}</code>: A radio button, allowing a single value to be selected out of multiple choices.</li> + <li><code>{{HTMLElement("input/range", "range")}}</code>: {{HTMLVersionInline("5")}} A control for entering a number whose exact value is not important.</li> + <li><code>{{HTMLElement("input/reset", "reset")}}</code>: A button that resets the contents of the form to default values.</li> + <li><code>{{HTMLElement("input/search", "search")}}</code>: {{HTMLVersionInline("5")}} A single-line text field for entering search strings. Line-breaks are automatically removed from the input value.</li> + <li><code>{{HTMLElement("input/submit", "submit")}}</code>: A button that submits the form.</li> + <li><code>{{HTMLElement("input/tel", "tel")}}</code>: {{HTMLVersionInline("5")}} A control for entering a telephone number.</li> + <li><code>{{HTMLElement("input/text", "text")}}</code>: A single-line text field. Line-breaks are automatically removed from the input value.</li> + <li><code>{{HTMLElement("input/time", "time")}}</code>: {{HTMLVersionInline("5")}} A control for entering a time value with no time zone.</li> + <li><code>{{HTMLElement("input/url", "url")}}</code>: {{HTMLVersionInline("5")}} A field for entering a URL.</li> + <li><code>{{HTMLElement("input/week", "week")}}</code>: {{HTMLVersionInline("5")}} A control for entering a date consisting of a week-year number and a week number with no time zone.</li> +</ul> + +<p>Some input types are now obsolete:</p> + +<ul> + <li><code>{{HTMLElement("input/datetime", "datetime")}}</code>: {{HTMLVersionInline("5")}} {{deprecated_inline}} {{obsolete_inline}} A control for entering a date and time (hour, minute, second, and fraction of a second) based on UTC time zone. <strong>This feature has been <a href="https://github.com/whatwg/html/issues/336">removed from WHATWG HTML.</a></strong></li> +</ul> + +<h2 id="Attributes">Attributes</h2> + +<p>The <code><input></code> element is one of the most powerful and complex in all of HTML due to the sheer number of combinations of input types and attributes. Since every <code><input></code> element, regardless of type, is based on the {{domxref("HTMLInputElement")}} interface, they technically all share the exact same set of attributes. However, in reality, many attributes only function on specific input types, and some input types support very few of these attributes. In addition, some input types handle certain attributes in special ways.</p> + +<p>Here, you'll find information about the individual attributes which are common to all <code><input></code> element types, as well as a few non-standard attributes that may be worth knowing about.</p> + +<h3 id="Attributes_common_to_all_input_types">Attributes common to all input types</h3> + +<p>This section lists the attributes which are used by all form <code><input></code> types. Attributes that are unique to particular input types—or attributes which are common to all input types but have special behaviors when used on a given input type—are instead documented on those types' pages.</p> + +<div class="note"> +<p><strong>Note</strong>: This includes the <a href="/en-US/docs/Web/HTML/Global_attributes">global HTML attributes</a>.</p> +</div> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Attribute</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>{{anch("autocomplete")}}</code></td> + <td>A string indicating the type of autocomplete functionality, if any, to allow on the input</td> + </tr> + <tr> + <td><code>{{anch("autofocus")}}</code></td> + <td>A Boolean which, if present, makes the input take focus when the form is presented</td> + </tr> + <tr> + <td><code>{{anch("disabled")}}</code></td> + <td>A Boolean attribute which is present if the input should be disabled</td> + </tr> + <tr> + <td><code>{{anch("form")}}</code></td> + <td>The {{domxref("Element.id", "id")}} of the {{HTMLElement("form")}} of which the input is a member; if absent, the input is a member of the nearest containing form, or is not a member of a form at all</td> + </tr> + <tr> + <td><code>{{anch("list")}}</code></td> + <td>The <code>id</code> of a {{HTMLElement("datalist")}} element that provides a list of suggested values for the input</td> + </tr> + <tr> + <td><code>{{anch("name")}}</code></td> + <td>The input's name, to identify the input in the data submitted with the form's data</td> + </tr> + <tr> + <td><code>{{anch("readonly")}}</code></td> + <td>A Boolean attribute which, if true, indicates that the input cannot be edited</td> + </tr> + <tr> + <td><code>{{anch("required")}}</code></td> + <td>A Boolean which, if true, indicates that the input must have a value before the form can be submitted</td> + </tr> + <tr> + <td><code>{{anch("tabindex")}}</code></td> + <td>A numeric value providing guidance to the {{Glossary("user agent")}} as to the order in which controls receive focus when the user presses the <kbd>Tab</kbd> key</td> + </tr> + <tr> + <td><code>{{anch("type")}}</code></td> + <td>A string indicating which {{anch("Form <input> types", "input type")}} the <code><input></code> element represents</td> + </tr> + <tr> + <td><code>{{anch("value")}}</code></td> + <td>The input's current value</td> + </tr> + </tbody> +</table> + +<h4 id="htmlattrdefautocomplete">{{htmlattrdef("autocomplete")}}</h4> + +<p>A string that describes what if any type of autocomplete functionality the input should provide. A typical implementation of autocomplete simply recalls previous values entered in the same input field, but more complex forms of autocomplete can exist. For instance, a browser could integrate with a device's contacts list to autocomplete email addresses in an email input field. See {{SectionOnPage("/en-US/docs/Web/HTML/Attributes/autocomplete", "Values")}} for permitted values.</p> + +<p>This attribute has no effect on input types that do not return numeric or text data, such as <code>checkbox</code> or <code>image</code>.</p> + +<p>See <a href="/en-US/docs/Web/HTML/Attributes/autocomplete">The HTML autocomplete attribute</a> for additional information.</p> + +<h4 id="htmlattrdefautofocus">{{htmlattrdef("autofocus")}}</h4> + +<p>A Boolean attribute which, if present, indicates that the input should automatically have focus when the page has finished loading (or when the {{HTMLElement("dialog")}} containing the element has been displayed).</p> + +<div class="note"> +<p><strong>Note:</strong> An element with the <code>autofocus</code> attribute may gain focus before the {{domxref("DOMContentLoaded")}} event is fired.</p> +</div> + +<p>No more than one element in the document may have the <code>autofocus</code> attribute, and <code>autofocus</code> cannot be used on inputs of type <code>hidden</code>, because hidden inputs can't be focused.</p> + +<div class="warning"> +<p><strong>Warning:</strong> Automatically focusing a form control can confuse visually-impaired people using screen-reading technology. When <code>autofocus</code> is assigned, screen-readers "teleport" their user to the form control without warning them beforehand.</p> +</div> + +<h4 id="htmlattrdefdisabled">{{htmlattrdef("disabled")}}</h4> + +<p>A Boolean attribute which, if present, indicates that the user should not be able to interact with the input. Disabled inputs are typically rendered with a dimmer color or using some other form of indication that the field is not available for use.</p> + +<p>Specifically, disabled inputs do not receive the {{event("click")}} event, and disabled inputs are not submitted with the form.</p> + +<div class="note"> +<p><strong>Note:</strong> Although not required by the specification, Firefox will by default <a href="https://stackoverflow.com/questions/5985839/bug-with-firefox-disabled-attribute-of-input-not-resetting-when-refreshing">persist the dynamic disabled state</a> of an <code><input></code> across page loads. Use the {{htmlattrxref("autocomplete","input")}} attribute to control this feature.</p> +</div> + +<h4 id="htmlattrdefform">{{htmlattrdef("form")}}</h4> + +<p>A string specifying the {{HTMLElement("form")}} element with which the input is associated (that is, its <strong>form owner</strong>). This string's value, if present, must match the {{htmlattrxref("id")}} of a <code><form></code> element in the same document. If this attribute isn't specified, the <code><input></code> element is associated with the nearest containing form, if any.</p> + +<p>The <code>form</code> attribute lets you place an input anywhere in the document but have it included with a form elsewhere in the document.</p> + +<div class="note"> +<p><strong>Note:</strong> An input can only be associated with one form.</p> +</div> + +<h4 id="htmlattrdeflist">{{htmlattrdef("list")}}</h4> + +<p>The {{domxref("Element.id", "id")}} of a {{HTMLElement("datalist")}} element located in the same document which provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the {{htmlattrxref("type", "input")}} are not included in the suggested options.</p> + +<p>The <code>list</code> attribute is not supported by the <code>hidden</code>, <code>password</code>, <code>checkbox</code>, <code>radio</code>, <code>file</code>, or any of the button types.</p> + +<h4 id="htmlattrdefname">{{htmlattrdef("name")}}</h4> + +<p>A string specifying a name for the input control. This name is submitted along with the control's value when the form data is submitted, as well as with the owning {{HTMLElement("form")}} element's {{domxref("HTMLFormElement.elements", "elements")}} object.</p> + +<p>When an input element is given a <code>name</code>, that name becomes a property of the owning form element's {{domxref("HTMLFormElement.elements")}} property. That means if you have an input whose <code>name</code> is set to <code>guest</code> and another whose <code>name</code> is <code>hat-size</code>, the following code can be used:</p> + +<pre class="brush: js">let form = document.querySelector("form"); +let guestName = form.elements.guest; +let hatSize = form.elements["hat-size"]; +</pre> + +<p>When this code has run, <code>guestName</code> will be the {{domxref("HTMLInputElement")}} for the <code>guest</code> field, and <code>hatSize</code> the object for the <code>hat-size</code> field.</p> + +<div class="warning"> +<p><strong>Warning:</strong> You should avoid giving form elements a <code>name</code> that corresponds to a built-in property of the form, since you would then override the predefined property or method with this reference to the corresponding input.</p> +</div> + +<p>The name <code>_charset_</code> has a special meaning. If used as the name of an <code><input></code> element of type <code><a href="/en-US/docs/Web/HTML/Element/input/hidden">hidden</a></code>, the input's <code>value</code> is automatically set by the {{Glossary("user agent")}} to the character encoding being used to submit the form.</p> + +<p>If no <code>name</code> is specified, or <code>name</code> is empty, the input's value is not submitted with the form.</p> + +<div class="note"> +<p><strong>Note:</strong> For historical reasons, the name <code>isindex</code> is not allowed. If you really want to know why, see <a href="https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#attr-fe-name">Naming form controls: the <code>name</code> attribute</a> in the HTML specification.</p> +</div> + +<h4 id="htmlattrdefreadonly">{{htmlattrdef("readonly")}}</h4> + +<p>A Boolean attribute which, if present, indicates that the user should not be able to edit the value of the input.</p> + +<p>The difference between <code>disabled</code> and <code>readonly</code> is that read-only controls can still function, whereas disabled controls generally do not function as controls until they are enabled.</p> + +<div class="blockIndicator note"> +<p><strong>Note:</strong> The <code>required</code> attribute is not permitted on inputs with the <code>readonly</code> attribute specified.</p> +</div> + +<div class="blockIndicator note"> +<p><strong>Note:</strong> Only text controls can be made read-only, since for other controls (such as checkboxes and buttons) there is no useful distinction between being read-only and being disabled, so the <code>readonly</code> attribute does not apply.</p> +</div> + +<h4 id="htmlattrdefrequired">{{htmlattrdef("required")}}</h4> + +<p><code>required</code> is a Boolean attribute which, if present, indicates that the user must specify a value for the input before the owning form can be submitted. The <code>required</code> attribute is supported by all input types <em>except the following</em>:</p> + +<div class="threecolumns"> +<ul> + <li><code><a href="/en-US/docs/Web/HTML/Element/input/color">color</a></code></li> + <li><code><a href="/en-US/docs/Web/HTML/Element/input/hidden">hidden</a></code></li> + <li><code><a href="/en-US/docs/Web/HTML/Element/input/range">range</a></code></li> + <li><code><a href="/en-US/docs/Web/HTML/Element/input/submit">submit</a></code></li> + <li><code><a href="/en-US/docs/Web/HTML/Element/input/image">image</a></code></li> + <li><code><a href="/en-US/docs/Web/HTML/Element/input/reset">reset</a></code></li> + <li><code><a href="/en-US/docs/Web/HTML/Element/input/button">button</a></code></li> +</ul> +</div> + +<p>When an input has the <code>required</code> attribute, the {{cssxref(":required")}} pseudo-class also applies to it. Conversely, inputs without the <code>required</code> attribute (except the elements that don't support it) have the {{cssxref(":optional")}} pseudo-class applied.</p> + +<div class="note"> +<p><strong>Note:</strong> Because a read-only field cannot have a value, <code>required</code> does not have any effect on inputs with the {{htmlattrxref("readonly", "input/text")}} attribute also specified.</p> +</div> + +<h4 id="htmlattrdeftabindex">{{htmlattrdef("tabindex")}}</h4> + +<p>An optional numeric value that defines both whether or not the input should be focusable through use of the <kbd>Tab</kbd> key as well as whether or not the element participates in sequential focus navigation. This value also establishes the order in which the element is reached using the <kbd>Tab</kbd> key.</p> + +<p>The values of <code>tabindex</code> have special meanings depending on sign:</p> + +<ul> + <li>A negative value of <code>tabindex</code> indicates that the element should be focusable by the user, but not using sequential keyboard navigation. It's recommended to always use a value of -1 as using other values can be complicated.</li> + <li>A <code>tabindex</code> of 0 means that the element should be focusable and should be reachable by sequential keyboard navigation, but that the tab order is left up to the {{Glossary("user agent")}}, which should apply the user's platform conventions. This is usually the best value to use when you want an element to be focusable and to participate in keyboard navigation rather than trying to manage the tab order yourself.</li> + <li>A positive value of <code>tabindex</code> indicates the tabbing order of the element. Each time the user presses the <kbd>Tab</kbd> key, the element with the next sequentially higher <code>tabindex</code> is focused. Most platforms provide a reverse-tab feature, typically using the combination of <kbd>Shift</kbd> + <kbd>Tab</kbd>, which reverses the tabbing order.</li> +</ul> + +<p>If <code>tabindex</code> is omitted or is not a valid integer, the user agent follows platform conventions to determine what to do.</p> + +<h4 id="htmlattrdeftype">{{htmlattrdef("type")}}</h4> + +<p>A string specifying the type of control to render. For example, to create a checkbox, a value of <code>checkbox</code> is used. If omitted (or an unknown value is specified), the input type <code>text</code> is used, creating a plaintext input field.</p> + +<p>Permitted values are listed in {{anch("Form <input> types")}}.</p> + +<h4 id="htmlattrdefvalue">{{htmlattrdef("value")}}</h4> + +<p>The input control's value. When specified in the HTML, this is the initial value, and from then on it can be altered or retrieved at any time using JavaScript to access the respective {{domxref("HTMLInputElement")}} object's <code>value</code> property. The <code>value</code> attribute is always optional.</p> + +<div class="note"> +<p><strong>Note:</strong> Unlike other input controls, checkboxes and radio buttons are only included in the submitted data if the checkbox or radio button is currently <code>checked</code>. If it is, then the <code>value</code> attribute is reported as the input's value.</p> + +<p>For example, if a checkbox whose <code>name</code> is <code>status</code> has a <code>value</code> of <code>active</code>, and the checkbox is checked, the form data submitted will include <code>status=active</code>. If the checkbox isn't active, it isn't listed in the form data at all. The default <code>value</code> for checkboxes and radio buttons is <code>on</code>.</p> +</div> + +<h2 id="Methods">Methods</h2> + +<p>The following methods are provided by the {{domxref("HTMLInputElement")}} interface which represents <code><input></code> elements in the DOM. Also available are those methods specified by the parent interfaces, {{domxref("HTMLElement")}}, {{domxref("Element")}}, {{domxref("Node")}}, and {{domxref("EventTarget")}}.</p> + +<dl> + <dt>{{domxref("HTMLInputElement.checkValidity", "checkValidity()")}}</dt> + <dd>Immediately runs the validity check on the element, triggering the document to fire the {{domxref("HTMLInputElement.invalid_event", "invalid")}} event at the element if the value isn't valid.</dd> + <dt>{{domxref("HTMLInputElement.reportValidity", "reportValidity()")}}</dt> + <dd>Returns <code>true</code> if the element's value passes validity checks; otherwise, returns <code>false</code>.</dd> + <dt>{{domxref("HTMLInputElement.select", "select()")}}</dt> + <dd>Selects the entire content of the <code><input></code> element, if the element's content is selectable. For elements with no selectable text content (such as a visual color picker or calendar date input), this method does nothing.</dd> + <dt>{{domxref("HTMLInputElement.setCustomValidity", "setCustomValidity()")}}</dt> + <dd>Sets a custom message to display if the input element's value isn't valid.</dd> + <dt>{{domxref("HTMLInputElement.setRangeText", "setRangeText()")}}</dt> + <dd>Sets the contents of the specified range of characters in the input element to a given string. A <code>selectMode</code> parameter is available to allow controlling how the existing content is affected.</dd> + <dt>{{domxref("HTMLInputElement.setSelectionRange", "setSelectionRange()")}}</dt> + <dd>Selects the specified range of characters within a textual input element. Does nothing for inputs which aren't presented as text input fields.</dd> + <dt>{{domxref("HTMLInputElement.stepDown", "stepDown()")}}</dt> + <dd>Decrements the value of a numeric input by one, by default, or by the specified number of units.</dd> + <dt>{{domxref("HTMLInputElement.stepUp", "stepUp()")}}</dt> + <dd>Increments the value of a numeric input by one or by the specified number of units.</dd> +</dl> + +<h2 id="Styling_input_elements">Styling input elements</h2> + +<p>You can style <code><input></code> elements using various color-related attributes in particular. One unusual one that is specific to text entry-related elements is the CSS {{cssxref("caret-color")}} property, which lets you set the color used to draw the text input caret:</p> + +<h3 id="HTML">HTML</h3> + +<pre class="brush: html"><label for="textInput">Note the red caret:</label> +<input id="textInput" class="custom" size="32"> +</pre> + +<h3 id="CSS">CSS</h3> + +<pre class="brush: css">input.custom { + caret-color: red; + font: 16px "Helvetica", "Arial", "sans-serif" +} +</pre> + +<h3 id="Result">Result</h3> + +<p>{{EmbedLiveSample('Styling_input_elements', 500, 80)}}</p> + +<p>For more information about adding color to elements in HTML, see <a href="/en-US/docs/Web/HTML/Applying_color">Applying color to HTML elements using CSS</a>.</p> + +<h2 id="Labels_and_placeholders">Labels and placeholders</h2> + +<div class="note"> +<p><strong>TL;DR:</strong> To save you time, here's the key point: don't use the {{htmlattrxref("placeholder", "input")}} attribute if you can avoid it. If you need to label an <code><input></code> element, use the {{HTMLElement("label")}} element.</p> +</div> + +<p>There are three seemingly similar ways to associate assistive text with an <code><input></code>. However, they are actually quite different, and only one of them is always a good choice. Here we will look at each of them and learn best practices for providing the user with guidance when entering data into a form.</p> + +<h3 id="The_<label>_element">The <label> element</h3> + +<p>The {{HTMLElement("label")}} element is the only way to provide explanatory information about a form field that is <em>always</em> appropriate (aside from any layout concerns you have). It's never a bad idea to use a <code><label></code> to explain what should be entered into an <code><input></code> or {{HTMLElement("textarea")}}.</p> + +<h3 id="The_placeholder_attribute">The placeholder attribute</h3> + +<p>The {{htmlattrxref("placeholder", "input")}} attribute lets you specify a text that appears within the <code><input></code> element's content area itself when empty. It's intended to be used to show an example input, rather than an explanation or prompt, but tends to be badly misused.</p> + +<p>Here are two inputs that take a password, each with a placeholder:</p> + +<p><img alt="Example of correct and incorrect placeholder usage" src="https://mdn.mozillademos.org/files/16094/placeholder-badgood.png" style="border-style: solid; border-width: 1px; height: 66px; width: 230px;"></p> + +<p>The first one uses a placeholder string <code>MyGr8P@sswrd</code>, demonstrating what a password might look like. And no, that's not <em>really</em> a great password.</p> + +<p>The second one uses a prompt string, <code>Enter your password</code> as a placeholder. The first, and most obvious, problem with doing this is that as soon as the user types their first character, they no longer have a prompt explaining what that field is for.</p> + +<p>That's why, instead, you should use the {{HTMLElement("label")}} element. The placeholder should never be required in order to understand your forms. While some people are able to remember what a given empty box is meant for after its only identifying text vanishes, others cannot.</p> + +<p>If the user can't understand your form if the placeholders are missing (say, in a browser that doesn't support <code>placeholder</code>, or in the case above where the user starts typing then gets confused), you're not using placeholders properly.</p> + +<p>In addition, browsers with automatic page translation features may skip over attributes when translating. That means the <code>placeholder</code> may not get translated, resulting in important information not being translated.</p> + +<p>If you feel like you need to use a placeholder, it's possible to use both a placeholder and a label:</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/16110/label-and-placeholder.png" style="border-style: solid; border-width: 1px; height: 48px; width: 234px;"></p> + +<h3 id="Unadorned_text_adjacent_to_the_<input>_element">Unadorned text adjacent to the <input> element</h3> + +<p>You can also just have plain text adjacent to the <code><input></code> element, like this:</p> + +<pre class="brush: html"><p>Enter your name: <input id="name" type="text" size="30"></p></pre> + +<p>Please don't do this. This doesn't create a relationship between the prompt and the <code><input></code> element, which is important for reasons we'll get into in the next section.</p> + +<h3 id="Why_you_should_use_labels">Why you should use labels</h3> + +<p>In addition to the information provided above, there are a number of other reasons why <code><label></code> is the best way to explain <code><input></code>s:</p> + +<ul> + <li>The semantic pairing of <code><input></code> and <code><label></code> elements is useful for assistive technologies such as screen readers. By pairing them using the <code><label></code>'s {{htmlattrxref("for", "label")}} attribute, you bond the label to the input in a way that lets screen readers describe inputs to users more precisely.</li> + <li>By pairing a <code><label></code> with an <code><input></code>, clicking on either one will focus the <code><input></code>. If you use plaintext to "label" your input, this won't happen. Having the prompt part of the activation area for the input is helpful for people with motor control conditions.</li> + <li>As web developers, it's important that we never assume that people will know all the things that we know. The diversity of people using the web—and by extension your web site—practically guarantees that some of your site's visitors will have some variation in thought processes and/or circumstances that leads them to interpret your forms very differently from you without clear and properly-presented labels.</li> +</ul> + +<h2 id="Examples">Examples</h2> + +<p>You can find multiple examples of <code><input></code> element usage on the pages covering each individual type — see {{anch("Form <input> types")}}, and also see the {{anch("Live example")}} at the top of the article.</p> + +<h2 id="Technical_summary">Technical summary</h2> + +<table class="properties"> + <tbody> + <tr> + <th scope="row"><a href="/en-US/docs/Web/HTML/Content_categories">Content categories</a></th> + <td><a href="/en-US/docs/Web/HTML/Content_categories#Flow_content">Flow content</a>, listed, submittable, resettable, form-associated element, <a href="/en-US/docs/Web/HTML/Content_categories#Phrasing_content">phrasing content</a>. If the {{htmlattrxref("type", "input")}} is not <code>hidden</code>, then labelable element, palpable content.</td> + </tr> + <tr> + <th scope="row">Permitted content</th> + <td>None, it is an {{Glossary("empty element")}}.</td> + </tr> + <tr> + <th scope="row">Tag omission</th> + <td>Must have a start tag and must not have an end tag.</td> + </tr> + <tr> + <th scope="row">Permitted parents</th> + <td>Any element that accepts <a href="/en-US/docs/Web/HTML/Content_categories#Phrasing_content">phrasing content</a>.</td> + </tr> + <tr> + <th scope="row">Permitted ARIA roles</th> + <td> + <ul> + <li><code>type=button</code>: {{ARIARole("link")}}, {{ARIARole("menuitem")}}, {{ARIARole("menuitemcheckbox")}}, {{ARIARole("menuitemradio")}}, {{ARIARole("radio")}}, {{ARIARole("switch")}}, {{ARIARole("tab")}}</li> + <li><code>type=checkbox</code>: {{ARIARole("button")}}, {{ARIARole("menuitemcheckbox")}}, {{ARIARole("option")}}, {{ARIARole("switch")}}</li> + <li><code>type=image</code>: {{ARIARole("link")}}, {{ARIARole("menuitem")}}, {{ARIARole("menuitemcheckbox")}}, {{ARIARole("menuitemradio")}}, {{ARIARole("radio")}}, {{ARIARole("switch")}}</li> + <li><code>type=radio</code>: {{ARIARole("menuitemradio")}}</li> + <li><code>type=color|date|datetime|datetime-local|email|file</code>: None</li> + <li><code>type=hidden|month|number|password|range|reset</code>: None</li> + <li><code>type=search|submit|tel|text|url|week</code>: None</li> + </ul> + </td> + </tr> + <tr> + <th scope="row">DOM interface</th> + <td>{{domxref("HTMLInputElement")}}</td> + </tr> + </tbody> +</table> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', 'forms.html#the-input-element', '<input>')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('HTML Media Capture', '#the-capture-attribute','<input capture>')}}</td> + <td>{{Spec2('HTML Media Capture')}}</td> + <td>Adds the <code>capture</code> attribute</td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', 'forms.html#the-input-element', '<input>')}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('HTML4.01', 'interact/forms.html#h-17.4', '<form>')}}</td> + <td>{{Spec2('HTML4.01')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Accessibility_concerns">Accessibility concerns</h2> + +<h3 id="Labels">Labels</h3> + +<p>When including inputs, it is recommended to add labels along side. This is so those who use assistive technologies can tell what the input is for. For more information about labels in general see {{anch("Labels and placeholders")}} .</p> + +<p>The following is an example of how to associate the <code><label></code> with an <code><input></code> element in the above style. You need to give the <code><input></code> an <code>id</code> attribute. The <code><label></code> then needs a <code>for</code> attribute whose value is the same as the input's <code>id</code>.</p> + +<pre><label for="peas">Do you like peas?</label> +<input type="checkbox" name="peas" id="peas"> +</pre> + +<h3 id="Size">Size</h3> + +<p>Interactive elements such as form input should provide an area large enough that it is easy to activate them. This helps a variety of people, including people with motor control issues and people using non-precise forms of input such as a stylus or fingers. A minimum interactive size of 44 by 44 <a href="https://www.w3.org/TR/WCAG21/#dfn-css-pixels">CSS pixels</a> is recommended.</p> + +<ul> + <li><a href="https://www.w3.org/WAI/WCAG21/Understanding/target-size.html">Understanding Success Criterion 2.5.5: Target Size | W3C Understanding WCAG 2.1</a></li> + <li><a href="http://adrianroselli.com/2019/06/target-size-and-2-5-5.html">Target Size and 2.5.5 | Adrian Roselli</a></li> + <li><a href="https://a11yproject.com/posts/large-touch-targets/">Quick test: Large touch targets - The A11Y Project</a></li> +</ul> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<div>{{Compat("html.elements.input")}}</div> + +<p>[1] It is recognized but there is no UI.</p> + +<p>[2] Missing for <code>type="checkbox"</code> and <code>type="radio"</code>.</p> + +<p>[3] In Safari <code>autocapitalize="words"</code> capitalizes every word's second character.</p> + +<p>[4] <code>datetime</code> has been removed from the spec and browsers in favour of <code>datetime-local</code>.</p> + +<p>[5] see {{bug(1355389)}}</p> + +<p>[6] Not yet implemented. For progress, see {{bug("888320")}} and <a href="https://wiki.mozilla.org/TPE_DOM/Date_time_input_types">TPE DOM/Date time input types</a>.</p> + +<h2 id="Notes">Notes</h2> + +<h3 id="Custom_error_messages">Custom error messages</h3> + +<p>If you want to present a custom error message when a field fails to validate, you need to use the <a href="/en-US/docs/Web/API/Constraint_validation#Constraint_validation_interfaces">Constraint validation features</a> available on <code><input></code> (and related) elements. Take the following form:</p> + +<pre class="brush: html"><form> + <label for="name">Enter username (upper and lowercase letters): </label> + <input type="text" name="name" id="name" required pattern="[A-Za-z]+"> + <button>Submit</button> +</form></pre> + +<p>The basic HTML form validation features will cause this to produce a default error message if you try to submit the form with either no valid filled in, or a value that does not match the <code>pattern</code>.</p> + +<p>If you wanted to instead display custom error messages, you could use JavaScript like the following:</p> + +<pre class="brush: js">const nameInput = document.querySelector('input'); +const form = document.querySelector('form'); + +nameInput.addEventListener('input', () => { + nameInput.setCustomValidity(''); + nameInput.checkValidity(); +}); + +nameInput.addEventListener('invalid', () => { + if(nameInput.value === '') { + nameInput.setCustomValidity('Enter your username!'); + } else { + nameInput.setCustomValidity('Usernames can only contain upper and lowercase letters. Try again!'); + } +});</pre> + +<p>The example renders like so:</p> + +<p>{{EmbedLiveSample('Custom_error_messages')}}</p> + +<p>In brief:</p> + +<ul> + <li>We check the valid state of the input element every time its value is changed by running the <code>checkValidity()</code> method via the <code>input</code> event handler.</li> + <li>If the value is invalid, an <code>invalid</code> event is raised, and the <code>invalid</code> event handler function is run. Inside this function we work out whether the value is invalid because it is empty, or because it doesn't match the pattern, using an <code>if()</code> block, and set a custom validity error message.</li> + <li>As a result, if the input value is invalid when the submit button is pressed, one of the custom error messages will be shown.</li> + <li>If it is valid, it will submit as you'd expect. For this to happen, the custom validity has to be cancelled, by invoking <code>setCustomValidity()</code> with an empty string value. We therefore do this every time the <code>input</code> event is raised. If you don't do this, and a custom validity was previously set, the input will register as invalid, even if it current contains a valid value on submission.</li> +</ul> + +<div class="blockIndicator note"> +<p><strong>Note</strong>: Firefox supported a proprietary error attribute — <code>x-moz-errormessage</code> — for many versions, which allowed you set custom error messages in a similar way. This has been removed as of version 66 (see {{bug(1513890)}}).</p> +</div> + +<h3 id="Localization">Localization</h3> + +<p>The allowed inputs for certain <input> types depend on the locale. In some locales, 1,000.00 is a valid number, while in other locales the valid way to enter this number is 1.000,00.</p> + +<p>Firefox uses the following heuristics to determine the locale to validate the user's input (at least for <code>type="number"</code>):</p> + +<ul> + <li>Try the language specified by a <code>lang</code>/<code>xml:lang</code> attribute on the element or any of its parents.</li> + <li>Try the language specified by any Content-Language HTTP header or</li> + <li>If none specified, use the browser's locale.</li> +</ul> + +<h3 id="Using_mozactionhint_on_Firefox_mobile">Using mozactionhint on Firefox mobile</h3> + +<p>You can use the {{htmlattrxref("mozactionhint", "input")}} attribute to specify the text for the label of the enter key on the virtual keyboard when your form is rendered on Firefox mobile. For example, to have a "Next" label, you can do this:</p> + +<pre class="brush: html"><input type="text" mozactionhint="next"> +</pre> + +<p>The result is:</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/3251/mozactionhint.png" style="border-style: solid; border-width: 1px; height: 400px; width: 240px;"></p> + +<p>Note the "Next" key in the lower-right corner of the keyboard.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>Other form-related elements: {{HTMLElement("form")}}, {{HTMLElement("button")}}, {{HTMLElement("datalist")}}, {{HTMLElement("legend")}}, {{HTMLElement("label")}}, {{HTMLElement("select")}}, {{HTMLElement("optgroup")}}, {{HTMLElement("option")}}, {{HTMLElement("textarea")}}, {{HTMLElement("keygen")}}, {{HTMLElement("fieldset")}}, {{HTMLElement("output")}}, {{HTMLElement("progress")}} and {{HTMLElement("meter")}}.</li> + <li><a href="/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation">Form constraint validation</a></li> + <li><a class="external" href="http://webdesignerwall.com/tutorials/cross-browser-html5-placeholder-text">Cross-browser HTML5 placeholder text</a></li> + <li>The CSS {{cssxref("caret-color")}} property</li> + <li>In certain cases (typically involving non-textual inputs and specialized interfaces), the <code><input></code> element is a <a href="/en-US/docs/Web/CSS/Replaced_element">replaced element</a>. When it is, the position and size of the element's size and positioning within its frame can be adjusted using the CSS {{cssxref("object-position")}} and {{cssxref("object-fit")}} properties</li> +</ul> |
