0

Which selector can I use to iterate through all input elements on the page except for the currently focused one?

This is what I currently have:

total = 0.00;

$(".numbers").each(function() {
  total += parseFloat($(this).val());
});
<input type="number" class="numbers" />

6 Answers 6

1

I don't love initializing a variable outside of the loop itself, so I'd suggest .toArray().reduce(), personally.

$("input:first").focus();   //for demo only

var total = $(".numbers:not(:focus)").toArray().reduce((sum, element) => sum + Number(element.value),0);
console.log(total);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="numbers" value="5" />
<input type="text" class="numbers" value="2" />
<input type="text" class="numbers" value="12" />

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

Comments

0
$(".numbers:not(':focus')").each(function(){
    total += parseFloat($(this).val());
});

Comments

0
$('.numbers:not(:focus)').each(function(){

})

Comments

0
$(".numbers:not(':focus')").each(function(index,element){
    total += parseFloat($(element).val());
});

Comments

0

I prefer this way:

$.each($('.number').not(':focus'), function(idx, ele) {
    total += parseFloat(ele.value);
});

Comments

0

Using :not(:focus) is your anti-select you're looking for. Also you may $('.numbers').not(':focus') to filter an existing set:

function calculate() {
  let total = $(".numbers:not(:focus)").get().reduce((sum, el) =>
    (sum += parseFloat(+el.value), sum), 0);

  console.log('Sum:',total)
}

$('input').on('keydown', calculate)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Change the number of the textbox:</p>
<input class="numbers" value="1" />
<input class="numbers" value="2" />
<input class="numbers" value="3" />
<input class="numbers" value="4" />

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.