Autofill an input when another input is filled using jquery chosen on both

荒凉一梦 提交于 2019-12-11 23:57:39

问题


I was helping another user here on stackoverflow when I faced a problem - I explained how to solve something, but I couldn't get my code (that I wanted to add as an example) to actually work. I'm pretty new to jQuery, so even though I understand the basics and what can and can't be done, I still find myself struggling with simple tasks.

In this case, I am trying to create two input fields, both using a tagging system (jQuery chosen). Both inputs have the same list of options, and I want that when you enter an item for the first input it automatically adds it to the second input as well. The idea is you can remove any item you want from the second list without affecting the first one.

You can see my attempts in this jsfiddle. I tried extracting the value from the first input and looping over it, but for some reason it doesn't really loop beyond the first item.

I also tried to apply the first item to the second list like so:

$('#shipping option[text='+value.value+']').attr('selected', 'selected');

and after the loop doing this:

$(".chosen-select").trigger('chosen:updated');

I knew this wouldn't work beyond the first item, but it didn't even work for that. I'm pretty confused at what I should do next. It's obvious that the chosen changes the input and it doens't behave like a usual one, but I can't understand how to work this out. Any help would be much appreciated!


回答1:


Use this line:

$('#shipping option[value="'+value+'"]').prop('selected', true);

Beware that if you select "United States" or "United Kingdom", they will show twice in Chosen plugin, since those options exist twice in your html, but you can use the :first selector to avoid this

$('#shipping option[value="'+value+'"]:first').prop('selected', true);

EDIT

Here is the code working: http://jsfiddle.net/rf90210/uZBXM/2/



来源:https://stackoverflow.com/questions/18432783/autofill-an-input-when-another-input-is-filled-using-jquery-chosen-on-both

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