1

i'm still new in html javascript. I want to ask can i use for loop to optimize or make this dynamic

 var port = [];         
 port[0]=$('#slcPort_0').val();
 port[1]=$('#slcPort_1').val();
 port[2]=$('#slcPort_2').val();
 port[3]=$('#slcPort_3').val();
 port[4]=$('#slcPort_4').val();

i used this code in function to retrieve data from html form

thanks

3 Answers 3

2

You could use:

// selects all the elements whose 'id' starts-with "slcPort_":
var port = $('[id^=slcPort_]').map(function(){
              // returns the value from those elements:
              return this.value;
          // converts to an array:
          }).get();

This isn't guaranteed to be in numerical order, though it will be in order of the appearance of those elements in the DOM.

References:

Sign up to request clarification or add additional context in comments.

Comments

0

Simply, you can do the following:

var port = Array();
for (i = 0; i < 5; i++){
  port[i] = $("#slcPort_"+i).val();
}

DEMO: http://jsbin.com/yiyaruweja/1/

Comments

0

It might make more sense to give all those elements a class, like slcPort. Then something like

var port = [];
$.each($('.slcPort'), function(index,value) {
    port[index] = $(value).val();
});

Much prettier. Plus all those elements are related anyways, so just class em up.

$.each documentation

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.