user5563910
user5563910

Reputation:

Jquery Applying single function for multiple IDs

I am generating IDs of three sets of input boxes dynamically (autoincrement). So one set has IDs such as "inputbox1, inputbox2 etc" and the other set has IDs such as "value1, value2 etc" and the third set has "result1, result2 etc"

My basic function in jquery is this:

$("#button").click(function() {
var inputbox1 = parseInt($('#inputbox1').val());
var value1 = parseInt($('#value1').val());

$("#result1").val(inputbox1 + value1);
});

I don't know how many inputboxes will be there since they are dynamically generated. So how can i apply this same basic function for all the textboxes? I know that multiple functions like this would be inefficient and it is probably not the right way to go about it.

$("#button").click(function() {
var inputbox1 = parseInt($('#inputbox1').val());
var value1 = parseInt($('#value1').val());
$("#result1").val(inputbox1 + value1);

var inputbox2 = parseInt($('#inputbox2').val());
var value2 = parseInt($('#value2').val());
$("#result2").val(inputbox2 + value2);
});

Upvotes: 0

Views: 58

Answers (3)

gurvinder372
gurvinder372

Reputation: 68383

$("#button").click(function() {

  $('input[id="^inputbox"]').each( function(){
    var inputbox = parseInt($(this).val());
    var number = $(this).attr( "id" ).split ( "inputbox" )[ 1 ];
    var value =  parseInt($('#value' + number).val());
    $("#result" + number).val(inputbox + value);

  });
});

Upvotes: 2

Zoltán Tamási
Zoltán Tamási

Reputation: 12754

You can write a query for the ID attributes to match the prefix substring, so you get every element which has an ID attribute beginning with "inputbox" for example.

$("[id^='inputbox']").each(function() { 
  // extract the number with a simple split or substring, and do whatever you need 
});

Or be more specific if you need:

$("input[id^='inputbox']").each(function() { 
  // extract the number with a simple split or substring, and do whatever you need
});

See the documentation

Upvotes: 1

Cruiser
Cruiser

Reputation: 1616

Try using .each() :

$('input').each(function(e){
    //do your stuff
});

You may need to identify the specific inputs to be included with another class. Using an id won't work in this case.

Check out this page: http://api.jquery.com/each/

Upvotes: 0

Related Questions