0

I am trying to use multiple form ids inside a javascipt function, but it doesn't work. The code is:

    $('#Rate1').keyup(function(){
    var Amt1;
    var Amt2;
    var Amt3;
    var Amt4;
    textone = parseFloat($('#Amt1').val());
    texttwo = parseFloat($('#Amt2').val());
    textthree = parseFloat($('#Amt3').val());
    textfour = parseFloat($('#Amt4').val());
    var result = textone + texttwo + textthree + textfour;
    $('#TotalInvoiceValue').val(result.toFixed(2));


});

And I want to use multiple ids like this:

$('#Rate1' || '#Rate2' || '#Rate3' || '#Rate4').keyup(function(){
    var Amt1;
    var Amt2;
    var Amt3;
    var Amt4;
    textone = parseFloat($('#Amt1').val());
    texttwo = parseFloat($('#Amt2').val());
    textthree = parseFloat($('#Amt3').val());
    textfour = parseFloat($('#Amt4').val());
    var result = textone + texttwo + textthree + textfour;
    $('#TotalInvoiceValue').val(result.toFixed(2));


});

But it's not working. Please point out what I am doing wrong here..

If you have a better suggestion to use something other than keyup is also welcomed.

2

2 Answers 2

3

It sounds like you just want to assign the same event handler to multiple selectors.

https://api.jquery.com/multiple-selector/

Try using comma ',' instead of logical or '||'

I.e

$('#Rate1, #Rate2, #Rate3, #Rate4').keyup(function(){
var Amt1;
Sign up to request clarification or add additional context in comments.

3 Comments

Alternatively, give the elements a shared class (like class="rate") and use the class as your jQuery selector: $('.rate')
@JonUleis Hi can you show how I can assign multiple elements in a class?
@CodyCoderson I just did! If you included some HTML I could point it out better.
0

The first answer answers your question exactly. But as the comments mention, using classes can simplify things and is more flexible.

html

<input id="Amt1" class="rate" type="text">
<input id="Amt2" class="rate" type="text">
<input id="Amt3" class="rate" type="text">
<input id="Amt4" class="rate" type="text">

javascript

$('.rate').on('keyup', function() {
  let result = 0;
  $('.rate').each(function() { result += parseFloat(this.value); });
  $('#TotalInvoiceValue').val(result.toFixed(2));
})

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.