Selecting the next input of an event.target

半世苍凉 提交于 2019-12-13 03:21:06

问题


I have (an array of) two inputs product and category.

The product one is an autocomplete. I would like to fill in the category when a product is selected.

the problem that the event.target is not a jquery object, so it seems I can't apply the jQquery's .next("input")

Here is my code:

var addedProduct = $(".produit:last > input");
addedProduct.autocomplete( {
        source: Object.keys(availableProducts),
        select: function(event, ui){
            var category = event.target.next("input"); // something like this ???
            category.value = availableProducts[ui.item.value]; //{"product1":"category1",...}
        }
    })

The inputs location is like this:


回答1:


You can create a new jQuery object from the event target with $(event.target). You'll be able to call .next on it afterwards

The other solution without jQuery is to use the native DOM API. You can select the next element with nextElementSibling. The only requirement is that the element you want to target must be immediately the next element.

EDIT: From the DOM structure provided you can use .parent().next() to select the next element at the parent level. Then on this new element use .find() to select the wanted input. Note that the code is highly tied to the DOM structure. You could use the id to directly select the element.

$(event.target).parent().next().find("input");


来源:https://stackoverflow.com/questions/54214830/selecting-the-next-input-of-an-event-target

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!