Last active
December 14, 2015 17:28
-
-
Save enrique-ramirez/5121912 to your computer and use it in GitHub Desktop.
Inconsistencias tontas en JavaScript//jQuery usando attribute selectors con values que usan square brackets. Confusing. I know.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Regresa un objeto del input con atributo name="HOLA" | |
*/ | |
$('input[name=HOLA]'); | |
/** | |
* No regresa nada... | |
*/ | |
$('input[name=HOLA[ULISES]]'); | |
/** | |
* ... tienes que escapear los square brackets con doble diagonal invertida. | |
* Este sí regresa el input con atributo name="HOLA[ULISES]" | |
*/ | |
$('input[name=HOLA\\[ULISES\\]]'); | |
/** | |
* No regresa nada. De hecho, regresa un error en jquery.js de sintaxis | |
*/ | |
var string = "HOLA[ULISES]"; | |
$('input[name=' + string + ']'); | |
/** | |
* "No problemo!" te dices, ingenuamente, a tí mismo. "Sólo tengo que escapear los | |
* square brackets aquí también!" | |
* | |
* ¡Pero NO! Esto también regresa un error de sintaxis. | |
*/ | |
var string = "HOLA\\[ULISES\\]"; | |
$('input[name=' + string + ']'); | |
/** | |
* Si te vas por el camino complicado, dices "BUENO, voy a reemplazar | |
* los square brackets con un REGEX para escapearlos y ya": | |
*/ | |
var string = "HOLA[ULISES]", | |
escapedString = string.replace('[','\\\\[').replace(']','\\\\]'); | |
$('input[name=' + string + ']'); // Valor de escapedString: 'organization\\[sharing_access_level\\]' | |
/** | |
* PERO NO! Te regresa un error de sintaxis! WTF!? | |
* Curiosamente, si vas a usar una variable para el valor de string, sólo necesitas UNA diagonal | |
* escapeando el square bracket. | |
*/ | |
var string = "HOLA[ULISES]", | |
escapedString = string.replace('[','\\[').replace(']','\\]'); | |
$('input[name=' + string + ']'); // Valor de escapedString: 'organization\[sharing_access_level\]' | |
/** | |
* EUREKA! | |
* Pero hay una forma TODAVÍA MÁS FÁCIL! | |
*/ | |
var string = "HOLA[ULISES]"; | |
$('input[name="' + string + '"]'); // (Notese las dobles comillas wrappeando el valor del 'name') | |
/** | |
* Tidbit del día. (sun) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment