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?
You have val
and text
backwards. Swap them:
$('#id\\[2\\]\\[t\\]').change(function() {
var txtval = $('#id\\[2\\]\\[t\\]').val();
$("#textpreview").text(txtval);
});
val
is used to get the value of the textbox. text
to set the text within the div
.
You can further simplify the code by using this
instead of re-querying the element.
$('#id\\[2\\]\\[t\\]').change(function() {
var txtval = this.value;
$("#textpreview").text(txtval);
});
$( document.getElementById( "id[2][t]" ) ).change( function(){
$( "#textpreview" ).text( this.value );
} );
You might consider revising your IDs (though I'm guessing they might be auto-generated). According to this question your IDs are invalid against the spec
Use the attribute selector instead:
var sel = $("[id='id[2][t]']");
sel.change(function() {
$("#textpreview").val(sel.text());
});
text
and val
are being used in the wrong places. - James Montagnedocument
by default) checking every single node for whether it matches that attribute with that value. People should know / understand this. - Raynos
Plain Old JavaScript:
var elem = document.getElementById('id[2][t]');
elem.onchange = function()
{
var elem = document.getElementById('textpreview');
elem.removeChild(elem.firstChild)
elem.appendChild(document.createTextNode(this.value));
}
Ahhh... now doesn't that feel better?
elem.addEventListener('change', function () { ... })
- Raynos.onchange
is cross-browser, addEventListener
is not) - Ryan Kinal.textContent
supports .addEventListener
your argument is null - Raynos
You can try using the attribute selector instead of the id selector.
$('[id="id[2][t]"]')
\\[
and \\]
? For one item in the DOM, who cares if it's slow? You can cache this lookup, or add maybe a class to it or change its ID so you can speed up lookups in the future. I don't know about you, but I hate having backslashes all over my strings, looks hideous. I think they have medicine for you that may help with vomiting, hope you feel better. - Rocket Hazmat
$(this).val() === this.value
remember... you don't need to use jQuery for Everything - rlemon