how to have numbers output with commas - javascript

I am trying to create a simple mortgage calculator and I want to have the numbers print with commas when the outputted number is larger than 3 digits. I would appreciate any help or suggestions. Im not really good at JS so I'd appreciate an example of where I'd put the code to allow it to print a comma. Thank you guys!
JS Code
var results;
function clearResults() {
$(".form__error").html("");
$('.results').html("");
};
$(function(){
$('body').on('submit','form',{},function(e){
e.preventDefault();
// clear previous results
clearResults();
// get our inputs
var rawInputs = $(this).serializeArray();
// convert these to numbers and create our argument array
var args = {};
for(var i = 0; i < rawInputs.length; i++) {
args[rawInputs[i].name] = parseFloat(rawInputs[i].value);
}
// run the mortgage calculator
results = mortgageCalculators.monthlyMortgagePayments(args);
if(results.error) {
$(".form__error").html(results.error);
} else {
$('.results').html(results)
}
});
});
!function(){function e(e,t){var r={error:!1,data:e};for(var o in t){if(t[o].isRequired&&void 0==e[o]){r.error=o+" is required.";break}if(t[o].isNumber&&("number"!=typeof e[o]||isNaN(e[o]))){r.error=o+" must be a number.";break}if(t[o].isNotNegative&&e[o]<0){r.error=o+" must be a positive number.";break}if(t[o].isNotZero&&0==e[o]){r.error=o+" must be greater then 0.";break}if(t[o].isNotFloat&&e[o]%1!=0){r.error=o+" must be an integer value.";break}}return r}function t(e,t){return e*t}function r(e){var t=e.loanAmount,r=0==e.interestRate?0:e.interestRate/100,o=0==r?0:r/12,i=12*e.termInYears;return o*t*Math.pow(1+o,i)/(Math.pow(1+o,i)-1)}function o(e){var t=e.monthlyPrincipalPayment,r=0==e.interestRate?0:e.interestRate/100,o=0==r?0:r/12,i=12*e.termInYears;return t*(Math.pow(1+o,i)-1)/(o*Math.pow(1+o,i))}function i(e){return isNaN(parseFloat(e.toFixed(2)))?0:parseFloat(e.toFixed(2))}window.mortgageCalculators={},window.mortgageCalculators.monthlyMortgagePayments=function(t){var o=e(t,{loanAmount:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!0,isNotFloat:!1},interestRate:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1},termInYears:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!0,isNotFloat:!0}});return o.error?{error:o.error}:i(r(t))},window.mortgageCalculators.monthlyMortgagePaymentsWithExtraPayments=function(o){var a=e(o,{loanAmount:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!0,isNotFloat:!1},interestRate:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1},termInYears:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!0,isNotFloat:!0},extraPaymentAmount:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1}});if(a.error)return{error:a.error};for(var s=o.interestRate/100/12,n=12*o.termInYears,N=o.extraPaymentAmount,m=r({loanAmount:o.loanAmount,interestRate:o.interestRate,termInYears:o.termInYears}),u=o.loanAmount,l=0,g=m,R=0;R<=n;R++){u-(c=m-(v=t(s,u)))>=0?u>=g&&(u-=c):u-=g=u,u>0&&(l+=m)}var y=m+N;u=o.loanAmount;var d=[];for(R=0;R<=n;R++){var v,c;u-(c=m-(v=t(s,u))+N)>=0?u>=y&&(u-=c):u-=y=u,u>0&&d.push({monthlyPayment:i(m+N),principalPayment:i(c),interestPayment:i(v),balance:i(u)})}for(var b=[],f=0;f<=Math.ceil(d.length);f+=12)b.push(d.slice(f,f+12));for(var h=[],I=o.loanAmount,F=0;F<b.length;F++){for(var P=0,p=0,q=0;q<b[F].length;q++)P+=b[F][q].interestPayment,p+=b[F][q].principalPayment;I-p>=0?I>=p&&(I-=p):I-=p=I,h.push({annualInterestPayment:i(P),annualPrincipalPayment:i(p),balance:i(I),monthlyBreakdown:b[F]})}return{withExtraPayment:{totalMonthlyPayment:i(m+N),interestRate:o.interestRate,term:o.termInYears,totalCost:i(d.length*(m+N)),payments:h},withoutExtraPayment:{totalMonthlyPayment:i(m),interestRate:o.interestRate,term:o.termInYears,totalCost:i(l)}}},window.mortgageCalculators.howMuchCanIBorrow=function(t){var r=e(t,{interestRate:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1},termInYears:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!0,isNotFloat:!0},grossMonthlyIncome:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1},downPayment:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1},monthlyDebtPayment:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1},yearlyPropertyTax:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1},yearlyPropertyInsurance:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1}});if(r.error)return{error:r.error};var a=t.interestRate,s=t.termInYears,n=t.monthlyDebtPayment,N=t.grossMonthlyIncome,m=t.downPayment/100,u=t.yearlyPropertyTax/12+t.yearlyPropertyInsurance/12,l=.36,g=.43,R=o({termInYears:s,interestRate:a,monthlyPrincipalPayment:l*N-n-u}),y=o({termInYears:s,interestRate:a,monthlyPrincipalPayment:g*N-n-u});return{conservative:{priceOfHome:i(R+R*m),downPayment:i(R*m),loanAmount:i(R)},aggressive:{priceOfHome:i(y+y*m),downPayment:i(y*m),loanAmount:i(y)},futureMonthlyPayment:{conservative:{principalAndInterest:i(l*N-n),taxesAndInsurance:i(u),totalMonthlyPayment:i(l*N-n+u)},aggressive:{principalAndInterest:i(g*N-n),taxesAndInsurance:i(u),totalMonthlyPayment:i(g*N-n+u)}}}},window.mortgageCalculators.compareFifteenVsThirtyYearMortgages=function(t){var o=e(t,{loanAmount:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!0,isNotFloat:!1},interestRate1:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1},interestRate2:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1}});if(o.error)return{error:o.error};var a=t.loanAmount,s=t.interestRate1,n=t.interestRate2,N=r({loanAmount:a,interestRate:s,termInYears:15}),m=r({loanAmount:a,interestRate:n,termInYears:30});return{fifteenYearMortgage:{monthlyMortgagePayment:i(N),totalInterest:i(15*N*12-a),totalPayments:i(15*N*12)},thirtyYearMortgage:{monthlyMortgagePayment:i(m),totalInterest:i(30*m*12-a),totalPayments:i(30*m*12)}}},window.mortgageCalculators.refinanceMortgage=function(o){var a=e(o,{loanAmount:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!0,isNotFloat:!1},interestRate:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1},termInYears:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!0,isNotFloat:!0},newInterestRate:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1},newTermInYears:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!0,isNotFloat:!0},newTermInYears:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!0,isNotFloat:!0},paymentsMade:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!0}});if(a.error)return{error:a.error};for(var s=o.loanAmount,n=o.interestRate,N=o.termInYears,m=o.newInterestRate,u=o.newTermInYears,l=o.paymentsMade,g=r({loanAmount:s,interestRate:n,termInYears:N}),R=s,y=0,d=0;d<l;d++){var v=t(n/100/12,R),c=g-v;R-c>=0&&(R-=c),c,y+=v}var b=g*N*12-s-y,f=R,h=r({loanAmount:f,interestRate:m,termInYears:u}),I=h*u*12-R;return{interestSaved:i(b-I),oldMonthlyMortgage:{monthlyMortgagePayment:i(g),remainingInterest:i(b)},newMonthlyMortgage:{newMortgageTotal:i(f),monthlyMortgagePayment:i(h),remainingInterest:i(I)}}},window.mortgageCalculators.comparefixedRateVsARM=function(o){var a=e(o,{loanAmount:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!0,isNotFloat:!1},interestRate:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1},termInYears:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!0,isNotFloat:!0},monthsBeforeFirstAdjustment:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!0,isNotFloat:!0},monthsBetweenAdjustments:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!0,isNotFloat:!0},expectedAdjustmentRate:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1},initialInterestRate:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1},maximumInterestRate:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!0,isNotFloat:!1}});if(a.error)return{error:a.error};for(var s=o.interestRate,n=o.termInYears,N=o.loanAmount,m=o.initialInterestRate,u=o.expectedAdjustmentRate,l=o.monthsBeforeFirstAdjustment,g=o.monthsBetweenAdjustments,R=o.maximumInterestRate,y=r({loanAmount:N,interestRate:s,termInYears:n}),d=r({loanAmount:N,interestRate:m,termInYears:n}),v=N,c=0;c<l;c++){v-=d-t(m/100/12,v)}for(var b=m+u,f=r({loanAmount:v,interestRate:b,termInYears:n-l/12}),h=0;h<g;h++){v-=f-t(b/100/12,v)}for(var I,F=12*n-l-g,P=0;P<F;P+=g){b<R?b+=u:b=R,f=r({loanAmount:v,interestRate:b,termInYears:(F-P)/12});for(var p=0;p<g;p++){v-=f-t(b/100/12,v)}I=f}return response={fixedRate:{monthlyMortgagePaymentARM:i(y)},ARM:{initialMonthlyMortgagePayment:i(d),maxMonthlyMortgagePayment:i(I)}},response},window.mortgageCalculators.compareBuyVsRent=function(o){var a=e(o,{monthlyRent:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!0,isNotFloat:!1},purchasePrice:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!0,isNotFloat:!1},downPayment:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1},interestRate:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1},termInYears:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!0,isNotFloat:!0},howLongBeforeSelling:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!0,isNotFloat:!0},incomeTaxRate:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1},expectedAnnualRentIncrease:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1},closingCosts:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1},annualAppreciation:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1}});if(a.error)return{error:a.error};for(var s=o.monthlyRent,n=o.expectedAnnualRentIncrease,N=o.purchasePrice,m=o.downPayment/100*N,u=N-m,l=o.interestRate,g=o.termInYears,R=o.closingCosts/100*u,y=o.howLongBeforeSelling,d=o.incomeTaxRate,v=o.annualAppreciation,c=r({loanAmount:u,interestRate:l,termInYears:g}),b=0,f=0,h=0,I=N,F=0,P=m,p=0;p<y;p++){F+=12*s,s+=s*(n/100),I+=I*(v/100);for(var q=0;q<12;q++){var w=t(l/100/12,u),A=c-w;u-A>=0?u>=A&&(u-=A):u-=A=u,f+=A,b+=w,h+=w*(d/100)}}var Z=I-u,M=(P+=f+b-h+(u+R))-I;return{currentValueOfHome:i(I),totalOwedToBank:i(u),equityOnHome:i(Z),netCostOfBuying:i(M),netCostOfRenting:i(F),benefitOfBuying:i(F-M)}}}();
HTML
<div class="loan-calculator">
<div class="top">
<h2>Monthly Mortgage Payment Calculator</h2>
<br /><br/>
<form action="#">
<div class="group">
<div class="title">Loan Amount</div>
<input type="text" placeholder="0" name="loanAmount" id="loanAmount" >
</div>
<div class="group">
<div class="title" >Interest Rate</div>
<input type="text" placeholder="0" name="interestRate" id="interestRate">
</div>
<div class="group">
<div class="title">Term (Years)</div>
<input type="text" placeholder="0" name="termInYears" id="termInYears">
</div>
</div>
<div class="result">
<div class="left">
<br /><br />
<h3>Monthly mortgage payment of</h3>
<div class="results value"></div>
<button class="calculate-btn-mortgage" type="submit">Calculate </button>
<br />
<br />
</div>
</div>
</form>

you can write it with regex and replace number with string at show time:
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
or you can do this too:
var n = 34523453.345;
console.log(n.toLocaleString()); // "34,523,453.345"

Related

How do I make this conversion function work in both directions?

I'm new in JS and I have trouble to finish a converter only with inputs, I explain the problem !
We have two input, Meters and Feet. when I transmit a number to Feet I have the result in Meters. And I Want to do the same think with Meters . and vice versa
let metresEl = document.getElementById('inputMetres');
function LengthConverter(valNum) {
metresEl.value = valNum/3.2808;
}
<div class="container">
<div class="form-group">
<label>Feet</label>
<input type="number" id="inputFeet" placeholder="Feet" oninput="LengthConverter(this.value)" onchange="LengthConverter(this.value)" >
</div>
<div class="form-group">
<label>Metres</label>
<input type="number" id="inputMetres" placeholder="Metres">
</div>
</div>
You can add another parameter in the LengthConvertor function which will say the input unit (meter or feet) and convert it accordingly inside the function using if.
function LengthConverter(valNum, inputUnit) {
if(inputUnit === 'feet')
metresEl.value = valNum/3.2808;
if(inputUnit === 'meter')
feetsEL.value = valNum * 3.2808;
}
<div class="container">
<div class="form-group">
<label>Feet</label>
<input type="number" id="inputFeet" placeholder="Feet" oninput="LengthConverter(this.value,"feet")" onchange="LengthConverter(this.value,"feet")" >
</div>
<div class="form-group">
<label>Metres</label>
<input type="number" id="inputMetres" placeholder="Metres" oninput="LengthConverter(this.value,"meter")" onchange="LengthConverter(this.value,"meter")" >
</div>
</div>
Added inverse conversion:
let metresEl = document.getElementById('inputMetres');
let feetEl = document.getElementById('inputFeet');
function FeetToMetres(valNum) {
metresEl.value = valNum/3.2808;
}
function MetresToFeet(valNum) {
feetEl.value = 3.2808*valNum;
}
<div class="container">
<div class="form-group">
<label>Feet</label>
<input type="number" id="inputFeet" placeholder="Feet" oninput="FeetToMetres(this.value)" onchange="FeetToMetres(this.value)" >
</div>
<div class="form-group">
<label>Metres</label>
<input type="number" id="inputMetres" placeholder="Metres" oninput="MetresToFeet(this.value)" onchange="MetresToFeet(this.value)">
</div>
</div>
You can add a element.addEvenetListener to each input, and when it chances you get it's value, convert, and put in on the right input.
let metresEl = document.getElementById('inputMetres');
let feetsEl = document.getElementById('inputFeets');
metresEl.addEventListener('change', yourCode);
feetsEl.addEventListener('change', yourCode);
For exemple, if metres input changes, you convert to feets and add to feets input.

Calc two fields and set results in third

I have a problem with the script.
I am trying to count two input fields, and insert the result into the third field.
But it doesn't work, and unfortunately I can't figure out what's wrong.
function sum() {
var txtFirstNumberValue = document.querySelectorAll('#firstID > div > div > div > input').value;
var txtSecondNumberValue = document.querySelectorAll('#second > div > div > div > input').value;
if (txtFirstNumberValue == "")
txtFirstNumberValue = 0;
if (txtSecondNumberValue == "")
txtSecondNumberValue = 0;
var result = parseInt(txtFirstNumberValue) / parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.querySelectorAll('#third > div > div > div > input').value = result;
}
}
<div id="firstID"><div>
<label>first</label>
<div>
<div>
<input name="drts[field_first][0]" type="number" value="" maxlength="255">
</div>
</div>
</div></div>
<div id="second"><div>
<label>second</label>
<div>
<div>
<input name="drts[field_second][0]" type="number" maxlength="255">
</div>
</div>
</div></div>
<div id="third"><div>
<label>third</label>
<div>
<div>
<input name="drts[field_third][0]" type="number" value="" maxlength="255">
<div></div>
</div>
</div>
</div></div>
There are a few problems here.
Are you actually calling sum? I've added a call in the example code so you can run it.
Your query selectors are not right. There isn't actually anything in the divs with the IDs you query. I've moved the input boxes into the correct places. When debugging, you should check that you are actually finding elements in your querySelectorAll call before proceeding.
querySelectorAll doesn't have a value property. You would need to iterate over each element before getting the items. Given you specifically want one item, it would be better to use something more specific like getElementById. I've kept the original querySelectorAll but changed the IDs on the divs to classes so we can have more than one result for this example. Then, I iterate over them pulling out the value to add to result. I've moved the parseInt to the running calculation otherwise it would perform a string concatenation.
Even better than the above would be to access the input directly. There's probably no point accessing a div and drilling down to the input. I've included this example to output the result.
I've removed redundant html. It's not related to the answer but try to keep your markup clean.
function sum() {
var inputElements = document.querySelectorAll('.user-input > div > div > input');
var result = 0;
inputElements.forEach(element => {
result += element.value ? parseInt(element.value) : 0
})
document.getElementById('third').value = result
}
document.getElementById('run-button').addEventListener('click', sum)
<div class="user-input">
<label>first</label>
<div>
<div>
<input name="drts[field_first][0]" type="number" maxlength="255">
</div>
</div>
<div>
<div class="user-input">
<label>second</label>
<div>
<div>
<input name="drts[field_second][0]" type="number" maxlength="255">
</div>
</div>
<div>
<label>third</label>
<div>
<div>
<input id="third" name="drts[field_third][0]" type="number" value="" maxlength="255">
<div></div>
</div>
</div>
<div>
<button type="button" id="run-button">Run</button>
Try like this
function sum() {
let txtFirstNumberValue = document.querySelector('#firstID input').value;
let txtSecondNumberValue = document.querySelector('#second input').value;
let result = parseInt(txtFirstNumberValue) / parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.querySelector('#third input').value = result;
} else {
document.querySelector('#third input').value = '';
}
}
<div id="firstID"><div>
<label>first</label>
<div>
<div>
<input name="drts[field_first][0]" type="number" value="" maxlength="255">
</div>
</div>
</div></div>
<div id="second"><div>
<label>second</label>
<div>
<div>
<input name="drts[field_second][0]" type="number" maxlength="255">
</div>
</div>
</div></div>
<div id="third"><div>
<label>third</label>
<div>
<div>
<input name="drts[field_third][0]" type="number" value="" maxlength="255" disabled>
<div></div>
</div>
</div>
<div>
<button id="button" onclick="sum()">Calculate</button>
</div>
</div>
</div>
const input1 = document.querySelector('#input1');
const input2 = document.querySelector('#input2');
const input3 = document.querySelector('#input3');
const storeInputs = [input1, input2];
for(let i = 0; i < storeInputs.length; i++) {
storeInputs[i].addEventListener('input', function() {
// multiply input1 and input2 with 1 for converting there values from string to number
input3.value = input1.value * 1 + input2.value * 1;
});
};
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<label for="input1">First Input</label>
<input id="input1" type="number" value="0"></input>
<label for="input2">Second Input</label>
<input id="input2" type="number" value="0"></input>
<label for="input3">Third Input</label>
<input id="input3" type="number" value="0"></input>
</body>
</html>

Getting number from user input: string is empty on submit?

I'm stuck on a problem. I'm working on an exercise that generates a random integer between 1-10. The user will submit a number from 1-10 in the input box. If a match occurs, the user will get an alert notifying them of success.
I'm stuck on getting the number from the user input. I want to log to the console the form input, but for the life of me, I cannot figure this out. I've tried changing the form type="number", type="text" and tried using parseInt().
Anything glaring in my code?
function exerciseEight() {
let input = document.querySelector("#number").value;
let button = document.querySelector("#guess");
let valueInt = parseInt(input, 10);
let number = Math.ceil(Math.random() * 10);
console.log(number);
button.onclick = function() {
console.log(input);
};
}
exerciseEight();
<body>
<div class="container container-fluid">
<p><strong>Exercise Eight:</strong> Guess a Number between 1 and 10.</p>
<form>
<div class="form-group">
<label for="number">Choose Number:</label>
<input id="number" value="" type="text" name="number" />
</form>
<!-- Result will go here -->
<p id="result"></p>
</div>
<button class="btn btn-dark" id="guess" type="submit">SUBMIT</button>
</body>
You need to get the input value when the user clicks. You're setting input and all the other variables that depend on it when the page is first loaded.
function exerciseEight() {
let button = document.querySelector("#guess");
let number = Math.ceil(Math.random() * 10);
button.onclick = function() {
let input = document.querySelector("#number").value;
let valueInt = parseInt(input, 10);
console.log(number, input);
};
}
exerciseEight();
<body>
<div class="container container-fluid">
<p><strong>Exercise Eight:</strong> Guess a Number between 1 and 10.</p>
<form>
<div class="form-group">
<label for="number">Choose Number:</label>
<input id="number" value="" type="text" name="number" />
</form>
<!-- Result will go here -->
<p id="result"></p>
</div>
<button class="btn btn-dark" id="guess" type="submit">SUBMIT</button>
</body>
The problem is that you are calling the function when the page loads, so it gets the values from the start, and doesn't change them at runtime when user enters input. You should call the function when user clicks the button.
function exerciseEight() {
let input = document.querySelector("#number").value;
let valueInt = parseInt(input, 10);
let number = Math.ceil(Math.random() * 10);
console.log(number);
}
let button = document.querySelector("#guess");
button.onclick = exerciseEight;
<body>
<div class="container container-fluid">
<p><strong>Exercise Eight:</strong> Guess a Number between 1 and 10.</p>
<form>
<div class="form-group">
<label for="number">Choose Number:</label>
<input id="number" value="" type="text" name="number" />
</form>
<!-- Result will go here -->
<p id="result"></p>
</div>
<button class="btn btn-dark" id="guess" type="submit">SUBMIT</button>
</body>

compare and mark word in strings with JS

need help for this, i want to compare and mark the word like this pic
https://i.stack.imgur.com/Ffdml.png
i try using js for this but got no luck
<div class="form-group">
<div class="col-md-6">
<section class="form-group-vertical">
<input class="form-control" type="text" id="1">
</section>
</div>
<div class="col-md-6" id="notif">
<section class="form-group-vertical">
<input class="form-control" type="text" id="2" >
</section>
</div>
</div>
<script type="text/javascript">
$(document).ready(function()
{
var firstInput = $('#1');
var seconInput = $('#2');
var aa = $('#2');
aa.change(function() {
var n = firstInput.val().localeCompare(seconInput.val());
if ( n === 0 ) {
console.log('ok');
$('#notif').attr('class', 'col-md-6');
}
else{
console.log('ko');
$('#notif').attr('class', 'has-error col-md-6');
}
});
});
</script>
any suggestion guys?
The simple solution please using this kpdecker/jsdiff
online demo:
demo

Re-arrange Text Input fields based on Number entered by user

I have few inputs, and it comes with values from 1 to 100 in it, but user can alter those values. I have sorted my inputs in Ascending order. Now I want that each time user changes an input, they should be re-arranged in ascending order.
Here is my HTML template:
var sortedArray = $("div[class^='wrap_']").get().sort(function(a, b) {
var idx = parseInt($(a).find(".sort_by").val(),10);
var idx2 = parseInt($(b).find(".sort_by").val(),10);
return idx > idx2;
});
$(sortedArray).appendTo("body");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="wrap_0">
<input class="sort_by" value="10"/>
</div>
<div class="wrap_1">
<input class="sort_by" value="3"/>
</div>
<div class="wrap_2">
<input class="sort_by" value="7"/>
</div>
Right now they appear as:
3
7
10
if user changes 3 to 12, I want my output to be automatically changed to:
7 10 12.
I want Jquery solutions only. Thanks in advance.
$(document).ready(function(){
sort();
$(".sort_by").change(function(){
sort();
});
function sort(){
var sortedArray = $("div[class^='wrap_']").get().sort(function(a, b) {
var idx = parseInt($(a).find(".sort_by").val(),10);
var idx2 = parseInt($(b).find(".sort_by").val(),10);
return idx > idx2;
});
console.log(sortedArray);
$(sortedArray).appendTo("body");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="wrap_0">
<input class="sort_by" value="10"/>
</div>
<div class="wrap_1">
<input class="sort_by" value="3"/>
</div>
<div class="wrap_2">
<input class="sort_by" value="7"/>
</div>
There...you change a value and press enter...your sort code is executed.
You can use the input event and apply the sort method on the parent div jQuery collection. Please note that I added class wrap so the divs can be easily selected. The code .trigger('input') ensures that the input (actually parent div) elements are sorted when the page loads.
$(function() {
$('.sort_by').on('focusout', function() {
var arr = $('div.wrap');
arr = arr.sort(function(a,b) {
return +$(a).find('.sort_by').val() - +$(b).find('.sort_by').val();
});
$('body').append( arr );
})
.trigger('focusout');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap_0 wrap">
<input class="sort_by" value="10"/>
</div>
<div class="wrap_1 wrap">
<input class="sort_by" value="3"/>
</div>
<div class="wrap_2 wrap">
<input class="sort_by" value="7"/>
</div>

Categories