Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference an id with brackets in jQuery

I'm painfully new to jQuery and I need to grab the value on change of a text input box with an id of id[2][t] and display that text in a div to be styled later on (also styled with jQuery).

This is the input box code:

<input id="id[2][t]" name="id[2][t]" maxlength="20" type="text">

This is the div I am trying to display it in:

<div id="textpreview"></div>

This is what I have tried, among other variation with no success:

$(document).ready(function() {

$('#id\\[2\\]\\[t\\]').change(function() {
  var txtval = $('#id\\[2\\]\\[t\\]').text();
  $("#textpreview").val(txtval);
});

});

I know the brackets are a problem but they need to remain for other reasons.

Any ideas?

like image 414
Rob Avatar asked Nov 30 '11 20:11

Rob


People also ask

Can HTML ID have brackets?

An id cannot include square brackets. It is forbidden by the spec.

Can I use id in jquery?

id is not a valid jquery function. You need to use the . attr() function to access attributes an element possesses. You can use .

Does jquery use id or name?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.

What do square brackets mean in jquery?

It means a table row who has an id that starts with "message": $('tr // a table row [id //having an id ^="message"]') // starting with 'message' http://api.jquery.com/category/selectors/attribute-selectors/ Follow this answer to receive notifications.


1 Answers

$( document.getElementById( "id[2][t]" ) ).change( function(){
  $( "#textpreview" ).text( this.value );
} );
like image 135
Esailija Avatar answered Oct 06 '22 09:10

Esailija