Paul Lucero Paul Lucero - 4 months ago 15
jQuery Question

Require only 2 of 3 form fields

I am making a yield calculator. There are 3 fields. Yield Percentage, Purchase Price, and Rent.

For example, I want a 10% yield, and I pay 500k, then my calculator will get the monthly rent to achieve the 10% yield.
Also, If I want a 10% yield, and I input a monthly rent of 500, then my calculator gets the purchase price.
Lastly, If I pay 500k, and let the rent be 500, then my calculator would get the yield percentage.

<form>
<input type="number" name="purchase_price">
<input type="number" name="rent">
<input type="number" name="yield">
<input type="submit" value="Calculate">
</form>


FURTHERMORE:

how do I make it that if any 2 of the fields are populated, the 3rd one get's disabled?

Example:

price & rent = yield field gets disabled

price & yield = rent field gets disabled

rent & yield = price field gets disabled

Answer

    var form = document.querySelector('form'); 

    form.addEventListener('change',function(event){
     elms = document.querySelectorAll('input:not([type="submit"]');
      var count = 0; 
        Array.prototype.forEach.call(elms,function(elm){
             if (elm.value != ''){
                 count++; 
              }
        });
       
       Array.prototype.forEach.call(elms,function(elm){
             if (count >= 2 && elm.value === ''){
                 elm.disabled = true; 
               }
             else{
               elm.disabled = false;
               }
        });
      
    });
  <form>
       <input type="number" name="purchase_price">
       <input type="number" name="rent">
       <input type="number" name="yield">
       <input type="submit" value="Calculate">
    </form>