I’m trying to get the value of an <input type=text> with the method keyup from jQuery but whenever i log it it logs undefined.
Here is my code:
$.each(editables,function(i){
current = $(editables[i]);
var value;
current.on('keyup', function(){
value = $(this).val();
console.log( value );
});
current.html( value );
});
Thanks in advance
EDIT
I have a table wich displays all the information of a database, and i have a button to edit the information, what i do is i convert all of the <td class="editable"> to an <input type="text"> and i’m trying to get the value from them after i click the button again, i will send the info via $.post() but i can’t get the value from these inputs
EDIT 2
Here is the full code of the handler hope it helps, thanks to all that have contributed
$(‘.edit’).on(‘click’,function(e){
$this = $(this);
editables = $this.parents('tr').find('td.editable');
if($this.text() == "Save"){
row = $this.parents('tr');
table = row.data('table');
id = row.data('id');
field = row.data('field');
/*
$.each(editables,function(i){
current = $(editables[i]);
var value;
current.on('keyup', function(){
value = $(this).val();
console.log( value );
});
console.log( current );
current.html( value );
});
*/
editables.each(function(i){
var current = $(this);
value;
current.on('keyup',function(){
value = $(this).val();
console.log(value);
})
});
$this.val('Edit');
} else {
$.each(editables,function(i){
current = $(editables[i]);
currentValue = current.text();
current.html("<input type='text' value='"+currentValue+"'></input>");
});
$this.val('Save');
}
e.preventDefault();
});
UPDATE
there was something else wrong in my code outside of the one i shared here that messed up the funcionality.
Thanks to everyone who helped
editablesis still the<td>tag based on your updated code, not the input that is now inside. Use the.findto target the new input tags instead.(Answer to updated question above)
(Answer to original question below)
First, you need to move your
.html()statement inside the.on('keyup'. Otherwise it will run only once and beforekeyuphas occurred. Essentially what you are doing is:1. initialize
value. 2. setcurrent.htmlto the initialized variable with no value (undefined). 3. Listen forkeyup. 4. Onkeyupchange value of the variable and do nothing.When
.html()is inside the.onit will run only afterkeyupand on eachkeyup. Which guaranteesvaluewill be more than initialized before its used.assuming editables are regions in which you wish to display the outcome of the text field. The
currenteditable is not the text field itself and will not respond tokeyupor.val()OR
If editables are actually the text fields themselves, then they have no interior and you cannot use
.html()on them. Nor should you want to. So assuming you DO with to output the result on the page somewhere.