简体   繁体   English

使用Jquery按名称选择输入

[英]Select input by name with Jquery

I'm adding this input field via an external .js file on clicking a button. 我通过单击按钮通过外部.js文件添加此输入字段。 This is added every time a button is clicked. 每次单击按钮时都会添加。

<input name=​"new" id=​"date" type=​"text" value>​

I want to append the Jquery-ui datepicker to this field. 我想将Jquery-ui datepicker附加到此字段。

Here's the code I'm using right now but class="hasDatepicker" isn't getting associated with the new field that's added when I inspect it using the console. 这是我现在正在使用的代码,但是当我使用控制台检查它时,class =“ hasDatepicker”没有与添加的新字段相关联。

$('[name="new"]').datepicker({
        maxDate: '+0d',
    dateFormat: 'yy/mm/dd'
});

I want to select this by name and not id as the id's will be unique for each field that's added. 我想按名称而不是id进行选择,因为id对于添加的每个字段都是唯一的。

The datepicker is added to other fields on my page so it should work here as well. 日期选择器已添加到我页面上的其他字段,因此它也应在此处工作。

I also want to append class="btn btn-darkgrey" to make the input field into a button via Jquery. 我还想附加class =“ btn btn-darkgrey”,以通过Jquery将输入字段变成按钮。

Try like 尝试像

$('input[name="new"]').datepicker({
    maxDate: '+0d',
    dateFormat: 'yy/mm/dd'
});

Working FIDDLE 工作场所

As you said every time input field added when button gets clicked. 如您所说,每次单击按钮时都会添加输入字段。 so , where you added the new input field at that place you have to initialize input with datepicker. 因此,您必须在该位置添加新输入字段的地方使用datepicker初始化输入。 That means on button click, you added code to insert new input field below that you have to find input by $input = parent_element.find('input[name="new"]').last(). 这意味着在单击按钮时,您添加了代码以在下面输入新的输入字段,您必须通过$ input = parent_element.find('input [name =“ new”]')。last()查找输入。

Here parent_element = in which you are appending/inserting your new input. 在此处parent_element =中,您将在其中添加/插入新输入。

And initialize that input. 并初始化该输入。

$input.datepicker({
  maxDate: '+0d',
  dateFormat: 'yy/mm/dd'
});

Try this. 尝试这个。 hope it will work for you. 希望它对您有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM