Cambiare il tipo ad un tag input – Change type of input field (Cross

Transcript

Cambiare il tipo ad un tag input – Change type of input field (Cross
Cambiare il tipo ad un tag input – Change type of input field (Cross
browsing problem) | 1
Problema: Cambiare il tipo (type) di un tag input (es: da
sumbit a button) tramite javascript al momento del
caricamento della pagina o al verificarsi di qualsiasi altro
evento.
La funzione JQuery .attr() non può cambiare l’attributo type dei vari tag per via di un
problema che si verifica con le seguenti versioni di Internet Explorer (Note: jQuery prohibits
changing the type attribute on an <input type=”text” /> or <button> element and will throw
an error in all browsers. This is because the type attribute cannot be changed in Internet
Explorer):
IE 6, IE 7, IE 8
Eseguendo la funzione…
[JAVASCRIPT]
$(‘#idbutton’).attr(‘type’, ‘submit’);
[/JAVASCRIPT]
…si ottiene quindi il seguente errore
[JAVASCRIPT]
type property can’t be changed
[/JAVASCRIPT]
Per via dell’incompatibilità di cui sopra jquery restituisce l’eccezione con tutti i browser.
La funzione JQuery .prop() permette di alterare l’attributo type con i browser Chrome/Safari,
Firefox, Opera ed Internet Explorer dalla versione 9 in poi
[JAVASCRIPT]
$(‘#idbutton’).prop(‘type’, ‘submit’);
[/JAVASCRIPT]
http://www.nerdammer.it
Cambiare il tipo ad un tag input – Change type of input field (Cross
browsing problem) | 2
Il problema quindi sussiste per le 3 famose versioni del browser ie, purtroppo, ancora in vita
Soluzione: utilizzare la funzione .prop() e nel caso di eccezione:
1.
2.
3.
4.
creare dinamicamente un nuovo elemento
copiare le proprietà del vecchio elemento nel nuovo
impostare il tipo del nuovo elemento a quello desiderato
sostituire il vecchio elemento con il nuovo
[JAVASCRIPT]
try{
$(this).prop(‘type’, ‘button’);
} catch (e) {
var $newInput = copyFrom($(this)); /* punti 1-3 */
$(this).replaceWith($newInput); /* 4 – sostituire il vecchio elemento con il nuovo */
}
[/JAVASCRIPT]
codice copyFrom
[JAVASCRIPT]
function copyFrom(src){
var result = $(‘
// punto 2
Button
‘); /*punto 1 e 3*/
result.attr(‘name’, src.attr(‘name’));
result.attr(‘onclick’, src.attr(‘onclick’));
result.attr(‘href’, src.attr(‘href’));
result.attr(‘title’, src.attr(‘title’));
result.attr(‘class’, src.attr(‘class’));
result.attr(‘value’, src.attr(‘value’));
// copiare altri eventuali attributi
return result;
http://www.nerdammer.it
Cambiare il tipo ad un tag input – Change type of input field (Cross
browsing problem) | 3
}
[/JAVASCRIPT]
Condividi:
Fai clic qui per condividere su Twitter (Si apre in una nuova finestra)
Fai clic per condividere su Facebook (Si apre in una nuova finestra)
Fai clic qui per condividere su Google+ (Si apre in una nuova finestra)
Fai clic qui per condividere su LinkedIn (Si apre in una nuova finestra)
Fai clic qui per inviare l'articolo via mail ad un amico (Si apre in una nuova finestra)
http://www.nerdammer.it