简体   繁体   English

属性以选择器开头,适用于第一个输入字段(不适用于其他输入字段)

[英]attribute starts with selector ,working for first input field(not for others)

Here i am having an issue with attribute starts with selector ,i have tried to do validation of multiple fields ,having dynamic ids ,but not succeed . 在这里,我遇到了一个以选择器开始的属性问题,我尝试对具有动态ID的多个字段进行验证,但未成功。

below is what i tried so far . 下面是我到目前为止尝试过的。

i have seen other suggestion in So,but unable to made it. 我在So中看到了其他建议,但未能实现。

  $("input[id^='product-unit-price-']").keydown(function (event) {
    });

Html HTML

 <input type="text"  class="form-control pro-input valfields" id="product-unit-price-<?php echo $id;?>" name="unit_price[]" onblur="getTotalPrice(<?php echo $id;?>)" required="">

here id is dynamic like 这里的id是动态的

product-unit-price-0 产品单价-0

product-unit-price-1 产品单价-1

product-unit-price-2 产品单价2

product-unit-price-3 产品单价-3

and so on.. 等等..

here its working for only the first id (product-unit-price-0) ,but not for rests. 在这里,它仅适用于第一个id(product-unit-price-0),而不适用于其余的ID。 Its all the things. 它所有的东西。

Suggest me. 建议我。

thank you. 谢谢。

I think you are using $("input[id^='product-unit-price-']") to refer the element inside the handler in this case while applying val() method which always return the value of the first element, not the element which is fired the event. 我认为您在这种情况下使用$("input[id^='product-unit-price-']")引用处理程序中的元素,同时应用了val()方法,该方法始终返回第一个元素的值,不是触发事件的元素。 In such case use $(this) to refer the element where this refers to the dom object of event fired element. 在这种情况下,请使用$(this)引用元素,其中this引用事件触发元素的dom对象。

$("input[id^='product-unit-price-']").keydown(function (event) {
    // refer element by `$(this)`    
})

FYI : It's always better to provide a common class for the group of the element and select based on that which is the better way to do it. 仅供参考:最好为元素组提供一个通用的类,然后根据该元素进行选择,这是更好的方法。

Why you not go with class selector? 为什么不选择类选择器?

$(".form-control.pro-input.valfields").keydown(function (event) {
// your logics here
}

Because from class selector you can select set of same class group elements and apply event on each element of set. 因为从类选择器中,您可以选择相同类组元素的集合,并将事件应用于集合的每个元素。

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

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