¿Cómo acceder al objeto por variable de cadena en JQuery?

I have a name as string like

var name = "senderId";

I can access the object the "oldschool" way like

var button = document.getElementById(name);

That works. But how can i access the object with that id with JQuery? I tried this:

var button = $("#"+name);
var button = $(name);

pero tampoco funciona.

preguntado el 28 de mayo de 14 a las 13:05

it works have you included jquery?? -

If document.getElementById(senderId); trabajos, $("#"+senderId) should work as well. Simple. You should share a bit more details and/or use the console/debugger built into your browser to debug your code. -

it will definitely work jsfiddle.net/Ry3Lv/13 -

It don't work, as @JamesDonnelly said, he made a mistake in his var names. -

@Superdrac He claimed document.getElementById(senderId) obras. -

2 Respuestas

Tu variable se llama nameno, senderId:

var name = "senderId";

Cambie su selector a:

var button = $("#"+name);

If that doesn't fix your problem then it sounds like you don't have jQuery included on your page. You can either download it (from jQuery's own website) and host it locally, including it using:

<script src="/path/to/jquery-1.11.0.min.js"></script>

Or you can instead use a CDN like De Google incluyendo:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

Note that these should be included before your own JavaScript, and should be wrapped within a $(document).ready() función.

contestado el 28 de mayo de 14 a las 13:05

@user3351652 are you sure that your vars are defined in same space ? - superdrac

@user3351652 Next time, please AT LEAST read the basic jQuery tutorial before asking questions like this. Please. - Kapa

Is this view page is having jsf components?

If JSF components are involved like h:form then you have access by form id then element in jquery

contestado el 28 de mayo de 14 a las 13:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.