I am adding a row to a table. In one of the cells in the row is an input which I want to make an ajax call. However, I am having a problem with passing the value of the input.
I’ve illustrated the problem here:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script language="javascript">
function addElement(){
var id = 0;
var tbl = document.getElementById('myTable');
var rowInd = document.getElementById('row1').rowIndex;
rowInd++;
var row0 = tbl.insertRow( rowInd );
var cell = row0.insertCell(0);
// cell.innerHTML = '<input type="text" id="myInput'+id+'" value="hello world" onkeyup="alert( '+this.value+' );" />';
// acts as expected: hello world
// cell.innerHTML = '<input type="text" id="myInput'+id+'" value="hello world" onkeyup="makeAjaxRequest( \'value='+this.value+'\' )" />';
// Outputs: value=undefined
var theId = "myInput"+id;
// cell.innerHTML = '<input type="text" id="myInput'+id+'" value="hello world" onkeyup="makeAjaxRequest( \'value='+document.getElementById( theId ).value+'\' )" />';
// Output: Object required
cell.innerHTML = '<input type="text" id="myInput'+id+'" value="hello world" onkeyup=" function(){ makeAjaxRequest( \'value='+this.value+'\' ) }" />';
// Nothing happens
}
function makeAjaxRequest( val ){
alert( val );
}
</script>
</head>
<body>
<span onclick="addElement()">
Click me
</span>
<br /><br />
<table id="myTable">
<tr id="row1"><td>hello</td></tr>
</table>
</body>
</html>
It’s going straight to an ajax call, so I need to be able to access either the object or the value so that I do my search. Any help is appreciated.
Thanks for making me discover insertRow, rowIndex and insertCell!
Btw, you’re complicating your life for nothing.
Here is the correct way (DOM-compatible, without innerHTML evil, blablabla):
The problem when you pass
'value=' + this.valueis that you’re passing the following value:value=hello world.The other problem is that for inline event handlers (like the
onkeyupin the HTML) is that you don’t need to wrap in a function. The following would work:I haven’t tested, but I suspect that by wrapping in another function, the
thisis different. Thus why it can’t work.To avoid any ambiguity, don’t use HTML event handlers.