1

I am completely new to web development and this is my first question on the site.

I am experimenting with the jQuery autocomplete widget with Joomla (hence the jQuery calls), and have mangaged to get it working via a database connection for the first text row input in my table, txtRow1. This input successfully fires the autocomplete widget for stock names.

When I use the 'add' row button, the autocomplete no longer works for the next row, txtRow2. How can I make the autocomplete function fire for all the txtRow input rows on the table?

I tried to use the id 'starts with' expression, as all the table inputs will be called txtRowX, but it still only works for the first one, txtRow1.

As you can probably tell, all the code is taken from web tutorials and is the work of others.

Thankyou for your time.

UPDATE: Thanks to Griegs linking to another question, the following code is working, but I don't know why:

   jQuery(function(){
   jQuery('[id^="txtRow"]').live('keyup.autocomplete', function(){
   jQuery(this).autocomplete({
    source : "stockdata.php",
    minLength: 2
    });
    });
    });

The HTML:

<script type="text/javascript">
jQuery(function() {

    jQuery('[id^="txtRow"]').autocomplete({
            source: "stockdata.php",
            minLength: 2
        });
    });

function addRowToTable()
{
var tbl = document.getElementById('tblSample');
var lastRow = tbl.rows.length;
// if there's no header row in the table, then iteration = lastRow + 1
var iteration = lastRow;
var row = tbl.insertRow(lastRow);

// left cell
var cellLeft = row.insertCell(0);
var textNode = document.createTextNode(iteration);
cellLeft.appendChild(textNode);

// right cell
var cellRight = row.insertCell(1);
var el = document.createElement('input');
el.type = 'text';
el.name = 'txtRow' + iteration;
el.id = 'txtRow' + iteration;
el.size = 40;

el.onkeypress = keyPressTest;
cellRight.appendChild(el);

// select cell
var cellRightSel = row.insertCell(2);
var sel = document.createElement('select');
sel.name = 'selRow' + iteration;
sel.options[0] = new Option('text zero', 'value0');
sel.options[1] = new Option('text one', 'value1');
cellRightSel.appendChild(sel);

}
</script>

<form action="tableaddrow_nw.html" method="get">
<p>
<input type="button" value="Add" onclick="addRowToTable();" />
<input type="button" value="Remove" onclick="removeRowFromTable();" />
<input type="button" value="Submit" onclick="validateRow(this.form);" />
<input type="checkbox" id="chkValidate" /> Validate Submit
</p>
<table border="1" id="tblSample">
<tr>
<th colspan="3">Stocks</th>
</tr>
<tr>
<td>1</td>
<td><input type="text" name="txtRow1" id="txtRow1" size="40" /></td>
<td>
<select name="selRow0">
<option value="value0">text zero</option>
<option value="value1">text one</option>
</select>
</td>
</tr>
</table>
</form>

The php file:

<?php
$dbhost = 'host';
$dbuser = 'user';
$dbpass = 'pass';
$dbname = 'database';

$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname);

$return_arr = array();

/* If connection to database, run sql statement. */
if ($conn)
{
$fetch = mysql_query("SELECT * FROM stocknameticker where stock_name like '%" . mysql_real_escape_string($_GET['term']) . "%'"); 

/* Retrieve and store in array the results of the query.*/
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
    $row_array['id'] = $row['s_id'];
    $row_array['value'] = $row['stock_name'];
    $row_array['abbrev'] = $row['stock_ticker'];

    array_push($return_arr,$row_array);
}
}

mysql_close($conn);

echo json_encode($return_arr);

?>
MGB
  • 37
  • 1
  • 11
  • Matthew, welcome to SO. The way this works is that if an answer given solves the issue you were having you should mark it as the correct answer so that subsequent viewers of this question can see the solution. – griegs Aug 30 '11 at 01:30
  • Don't forget to review the `delegate` as well, I tend to use it more than `live`. See why here: http://brandonaaron.net/blog/2010/03/4/event-delegation-with-jquery – Mark Schultheiss Aug 30 '11 at 11:50
  • Mark, thankyou for the link. Unfortunately, none of the examples work in my ff browser when I click on them. – MGB Aug 30 '11 at 15:04

1 Answers1

1

When dealing with dynamicaly created elements you need to use the live jquery keyword.

$('[id^="txtRow"]').live("autocomplete", function(){
//your code here
});

edit

This might help too; Bind jQuery UI autocomplete using .live()

When you dynamically create an element on a web page, jQuery will not automatially bind it to any events.

So when you have;

$(".MyElement").click(...

the click event will only apply to elements that were present when the page was loaded.

If you now add a new element and want the click even to be applied to it you need to do;

$(".MyElement").live("click", function(...

That instructs jQuery to scan the document and attach events to newly created elements.

Community
  • 1
  • 1
griegs
  • 22,624
  • 33
  • 128
  • 205
  • Thankyou so very much for taking the time to reply. I am stunned at the great attitude in this forum towards the unenlightened. – MGB Aug 30 '11 at 01:36
  • Oops reply fail. I meant to say, however, I don't know exactly 'what' the phrase you wrote should be wrapped around. I've tried a few combinations and they don't work for me. I apologise, but I will need a very direct point. – MGB Aug 30 '11 at 01:37
  • I think this is a 'brackets' issue problem for me now. Trying to work out which pair of brackets should be with which part of the function. I am getting a 'missing variable name' error in the developer console now, when pasting in your solution, and when trying to pair up all the brackets. The error is on the 'source: "stockdata.php",' line, wherever I try to close the statement brackets. I feel silly now, seeing as you have been so helpful. – MGB Aug 30 '11 at 02:03
  • Yeah i think you need to read the link i sent rather than implement my code verbatim. – griegs Aug 30 '11 at 02:10