简体   繁体   中英

Jquery script - Fill select with input text and vice versa

I have 2 scripts that I need to combine, I basically have a script that allows a text input to be filled when you select an item in a select list. I also have a script that fills a select list based on input of a text input. Now I am trying to figure out how can I combine these 2 scripts so they can work together.

Heres an example of a multi select filling a text input. http://jsfiddle.net/akhyp/1963/

    function loopSelected()
{
  var txtSelectedValuesObj = document.getElementById('hidden_input');
  var selectedArray = new Array();
  var selObj = document.getElementById('selected_items');
  var i;
  var count = 0;
  for (i=0; i<selObj.options.length; i++) {
    if (selObj.options[i].selected) {
      selectedArray[count] = selObj.options[i].value;
      count++;
    }
  }
  txtSelectedValuesObj.value = selectedArray;
}

Heres an example of a text input filling a multi select based on input. http://jsfiddle.net/akhyp/1964/

  $("#txt").change(function(e){
    var ar = $(this).val().split(",");
    $("#sel option").each(function(){
        if(ar.indexOf($(this).val()) != -1)
           $(this).attr("selected","selected");
    });
  });

What I am trying to accomplish is something like this: If text input is null then fill text input with selected option from the select list. If the text input is already filled then fill in the multi select based on input from the text input.

Any help would be appreciated.

Final update: Finally got the results I wanted, here the final product http://jsfiddle.net/akhyp/1966/ been working on this for weeks possibly months lol. Really happy to have this working.

I added another change script function, seems to have made it work. Your change set the selected, and mine transfers the values.

$('#sel').change(function(){
    $('#txt').val($('#sel').val());
});

http://jsfiddle.net/snlacks/akhyp/1965/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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