user1944672
user1944672

Reputation: 87

Selecting multiple input parameter in dropdown in JS

I am trying to create a dropdown list that takes two input parameters (name, IPAddress). I have declared global variable Name and IP to track which name and ip address have been selected. However, the part that I am having a trouble is that it is not recognizing the IP address. Single name can have multiple IP address that I want to recognize both name and IP address when it was selected in dropdown list :(

Any advise on this would be appreciated! Thank you!

 //called after name changed
 function selectName(){
   Name = $(#"name :selected").val();
  }

//create dropdown list for name and IPAddress
function createDropList (name, IPAddress){
  $('#name').empty();
  $('#name').append('<option disabled selected value=""> Select Name </option>');
    for (var i=0; i<IPAddress.length; i++) {
        $('#name').append('<option value= "'+name[i]+'" >'+IPAddress[i] + " (IP :"+IPAddress[i] +")" +'</option>');
  }}

Upvotes: 0

Views: 225

Answers (1)

Steve H.
Steve H.

Reputation: 6947

Your code:

$('#name').append('<option value= "'+name[i]+'" >'+
    IPAddress[i] + " (IP :"+IPAddress[i] +")" +'</option>');

generates this:

<option value= "name" >1.2.3.4 (IP :1.2.3.4)</option>

You need:

$('#name').append('<option value= "'+name[i]+':'+
    IPAddress[i] + '">(IP :"'+IPAddress[i] +")" +'</option>');

to generate:

<option value= "name:1.2.3.4">(IP :1.2.3.4)</option>

In this way, your value will be the name and IP separated by a colon (:)

To set the global variable "IP" to the value when selected:

$('#name').on('change', function() {
    var value= $('#name').val().split(':');
    Name= value[0];
    IP= value[1];
}

Upvotes: 1

Related Questions