jQuery 克隆自动完成链仅在第一行链接

发布于 2024-11-28 05:20:43 字数 2919 浏览 1 评论 0原文

我还没有找到解决方案,需要新的几双眼睛来解决这个问题。基本上,您会自动完成搜索车辆,并在选择后发送一个过滤器请求,其中包含填充模型选择列表的 json。一切正常,除了当我创建一行并选择自动完成值时,它仅链接到第一行模型而不是附加行。我计划根据品牌对模型进行另一个过滤器(不在本例中)。

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();
  });
});

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 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>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

九歌凝 2024-12-05 05:20:44

我只在测试服务器上没有任何地方,因为真的没有什么可放的。下面是车辆的 sql ex 和两个文件:getvehicles.php 和 makevehicles.php。还有一个更新的js。感谢

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);  
?> 

更新了 JS。我所做的就是更改上面两个文件的自动完成和 getJSON url 中的源。我的脚本非常复杂,所以就把这两个去掉了。让我知道这是否有帮助。顺便说一句:我修复了 html,但仍然不行。这里使用jqueryui。如果您也需要,请告诉我。

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();
   });
});

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();
   });
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文