开发者

jQuery Cloning autocomplete Chain only chaining on first row

I have not found a solution to this and a new few set of eyes is needed to solve this issue. Basically you autocomplete search the vehicle and upon select a filter request is sent with json filling the models select list. Everything works fine except when I create a row and select the autocomplete value it only chains to the first row models not the appended row. I plan on doing another filter for the models based on makes (not in this example).

The JS:

function setAutocomplete() {
  $('#vehicle_id').val("");
  $text = jQuery(".veh_selector");
  $.each($text, function(i, val) {
    $(val).autocomplete({
      source: 'vehicles.php',
      minLength: 2,
      select: function(event, ui) {
        $('#veh_desc_id').val(ui.item.id);
        $('#vehicle_id').val(ui.item.vehicle_id);
        $.getJSON("vehicles.php?filter=" + ui.item.vehicle_id, function(jsonData) {

          $("select.model").html(""); //clear old options
          jsonData = eval(jsonData); //get json array
          for (i = 0; i < jsonData.length; i++) //iterate over all options
          {
            for (key in jsonData[i]) //get key => value
            {
              $("select.model").get(0).add(new Option(jsonData[i][key], [key]), document.all ? i : null);
            }
          }
        });
      }
    });
  });
}

var current = 0;

var addVehicleFields = function() {
  current++;
  $newVehicle = $("#searchtemplate").clone();
  $newVehicle.removeAttr("id");
  $newVehicle.removeClass("hide_element");
  $prefix = "extra" + current;
  $newVehicle.children("div").children(":input").each(function(i) {
    var $currentElem = $(this);
    $currentElem.attr("name", $prefix + $currentElem.attr("name"));
  });
  $newVehicle.appendTo("#vehiclesField");
  $('.remove-this').show('fast');
  $('#remove-me').removeAttr('disabled');
  setAutocomplete();
}

$(document).ready(function() {
  setAutocomplete();
  $("#addVehicle").live("click", addVehicleFields);
  $('.remove-this').live('click', function() {
    $(this).parent().remove();
  });
});

The html

<div id="models-makes">
  <fieldset id="vehiclesField">
  <label>Search Vehicles</label>
  <div class="vehicle"></div>
</div>
</fieldset>
<div>
  <div class="model-make original">
      <label for="veh_desc"></label>
      <input type="hidden" class="veh_selector" id="veh" name="veh" size="30"/>
    </p>
    <input type="hidden" id="veh_desc_id" name="veh_desc_id" />
    <div class="vehicle hide_element" id="searchtemplate">
      <input class="veh_selector" id="veh" name="_veh" size="30"/>
 开发者_运维百科     <select class="model empty">
        <option>Models</option>
      </select>
      <select class="make empty">
        <option>Makes</option>
      </select>
      <input name="remove-this" class="remove-this" value="Remove" type="button">
    </div>
  </div>
</div>
<div>
  <input type="button" id="addVehicle" value="Add A Vehicle">
  <input name="reset" id="reset" value="Reset" type="reset">
</div>


I don't have it up anywhere only on test server, as really nothing to put up. Below is a sql ex for the vehicles and two files: getvehicles.php and makevehicles.php. Also is an updated js. Thanks

SQL

CREATE TABLE `vehicles` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`vehicle_id` int(11) DEFAULT NULL,
`veh_desc` text CHARACTER SET latin1,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

INSERT INTO `vehicles` VALUES ('1', '1', 'Car');
INSERT INTO `vehicles` VALUES ('2', '2', 'Minivan');
INSERT INTO `vehicles` VALUES ('3', '3', 'Truck');

CREATE TABLE `makevehicles` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`vehicle_id` int(11) NOT NULL DEFAULT '0',
`make` text CHARACTER SET latin1,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

INSERT INTO `makevehicles` VALUES ('1', '1', 'Acura');
INSERT INTO `makevehicles` VALUES ('2', '1', 'Audi');
INSERT INTO `makevehicles` VALUES ('3', '1', 'BMW');
INSERT INTO `makevehicles` VALUES ('4', '2', 'Dodge');
INSERT INTO `makevehicles` VALUES ('5', '3', 'Chevy');

getvehicles.php

<?php  
  $username = "root";  
  $password = "";  
  $hostname = "localhost";  
  $dbh = mysql_connect($hostname, $username, $password) or die("Unable to connect   
  to MySQL");  
  $selected = mysql_select_db("DATABASE_NAME",$dbh) or die("Could not connect");  

  $return_arr = array();

$fetch = mysql_query("SELECT * FROM vehicles where veh_desc 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['id'];
    $row_array['value'] = $row['veh_desc'];
    $row_array['vehicle_id'] = $row['vehicle_id'];

    array_push($return_arr,$row_array);
}
  echo json_encode($return_arr);  
?> 

makevehicles.php

<?php  
  $username = "root";  
  $password = "";  
  $hostname = "localhost";  
  $dbh = mysql_connect($hostname, $username, $password) or die("Unable to connect   
  to MySQL");  
  $selected = mysql_select_db("DATABASE_NAME",$dbh) or die("Could not connect");  
  $filter = strtolower($_GET["filter"]);

$query =
  "SELECT vehicle_id, make FROM makevehicles WHERE vehicle_id='$filter'";  
  $result=mysql_query($query);     
  $outArray = array(); 
  if ($result) { 
  while ($row = mysql_fetch_assoc($result)) $outArray[] = $row; 
} 
  echo json_encode($outArray);  
?> 

Updated JS. All I did was change source in autocomplete and getJSON url for two files above. My script is very complex so just took these two out. Let me know if this helps. BTW: I fixed the html and still no go. This uses jqueryui. If you need that too let me know.

function setAutocomplete() {
$('#vehicle_id').val("");
$text = jQuery(".veh_selector");
$.each($text, function(i, val) {
$(val).autocomplete({
  source: 'getvehicles.php',
  minLength: 2,
  select: function(event, ui) {
    $('#veh_desc_id').val(ui.item.id);
    $('#vehicle_id').val(ui.item.vehicle_id);
    $.getJSON("makevehicles.php?filter=" + ui.item.vehicle_id, function(jsonData) {

      $("select.model").html(""); //clear old options
      jsonData = eval(jsonData); //get json array
      for (i = 0; i < jsonData.length; i++) //iterate over all options
      {
        for (key in jsonData[i]) //get key => value
        {
          $("select.model").get(0).add(new Option(jsonData[i][key], [key]), document.all ? i : null);
           }
      }
      });
     }
   });
  });
 }

var current = 0;

var addVehicleFields = function() {
current++;
$newVehicle = $("#searchtemplate").clone();
$newVehicle.removeAttr("id");
$newVehicle.removeClass("hide_element");
$prefix = "extra" + current;
$newVehicle.children("div").children(":input").each(function(i) {
var $currentElem = $(this);
$currentElem.attr("name", $prefix + $currentElem.attr("name"));
 });
 $newVehicle.appendTo("#vehiclesField");
 $('.remove-this').show('fast');
 $('#remove-me').removeAttr('disabled');
 setAutocomplete();
}

$(document).ready(function() {
setAutocomplete();
$("#addVehicle").live("click", addVehicleFields);
$('.remove-this').live('click', function() {
$(this).parent().remove();
   });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜