如何将jquery datepicker添加到动态创建的输入中,该输入位于名为page的ajax中

时间:2014-11-22 09:43:15

标签: javascript php jquery ajax datepicker

请原谅我,如果已经回答,但我使用不同搜索字词的创意版本搜索了此网站,并且显示为空白。

我有一个php网页(index.php),使用ajax加载另一个php页面(dataQuery.php),其上有html表单。我创建了一个小脚本(addInput()),允许用户根据需要动态地向该表单添加任意数量的输入字段。其中一个字段是我想要附加日期选择器的日期字段。在过去,我已将javascript添加到ajax回调中,但在这种情况下,我无法使其发挥作用。

这是我的function Query()

function Query()    
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    { 
    document.getElementById("container").innerHTML=xmlhttp.responseText;

    // Tried this suggestion found on stackoverflow:
    $('body').on('focus',".newlabour_date", function(){
    $(this).datepicker();});

    // And this one:
    $( "#newlabour_date" ).datepicker();
    }
  }
xmlhttp.open("GET","/process/dataQuery.php",true);
xmlhttp.send();
}

这是我的function addInput()

function addInput(table,counter,rowcount)
{
var counter = document.getElementById(counter);
var number = counter.value;
counter.value = ++counter.value;

var rowcount = (rowcount*1+1); // muliply the rowcount by 1 to ensure it doesn't get treated as a concatenation.

var table = document.getElementById(table);
var row = table.insertRow(rowcount);
row.align = "center";

var cell1 = row.insertCell(0);
cell1.className = "bBottom";
cell1.width = "20%";
cell1.height = "21";

cell1.innerHTML = "<input type=\"text\" style=\"position:relative; top:2px;\"
class=\"noborder\" name=\"newlabour_date["+number+"]\" id=\"newlabour_date["+number+"]\" size=\"15\" maxlength=\"\" placeholder=\"\" value=\"\">";
}

我不知道这是否可行,但我有一种感觉。感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

您的代码存在一些错误,您错过了生成的输入字段的 newlabour_date table.insertRow(rowcount);发出愤怒错误。

没有Ajax的工作示例: http://jsfiddle.net/qxarbpcc/

以下是addInput函数的更新版本:

function addInput(table,counter,rowcount)
{
    var counter = document.getElementById(counter);
    var number = counter.value;
    counter.value = ++counter.value;

    var rowcount = parseInt(rowcount)+1; // muliply the rowcount by 1 to ensure it doesn't get treated as a concatenation.

    var table = document.getElementById(table);
    var row = table.insertRow(0);
    row.align = "center";

    var cell1 = row.insertCell(0);
    cell1.className = "bBottom";
    cell1.width = "20%";
    cell1.height = "21";

    cell1.innerHTML = "<input type=\"text\" style=\"position:relative; top:2px;\" class=\"noborder newlabour_date\" name=\"newlabour_date["+number+"]\" id=\"newlabour_date["+number+"]\" size=\"15\" maxlength=\"\" placeholder=\"\" value=\"\">";
}

然后将Ajax回调更改为:

if (xmlhttp.readyState==4 && xmlhttp.status==200)
{ 
    document.getElementById("container").innerHTML=xmlhttp.responseText;

    $('body').on('focus',".newlabour_date", function(){
    $(this).datepicker();});
}

不要忘记在头部添加jquery和jqueryui。