compare and mark word in strings with JS - javascript
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
Related
Jquery clone name attribute increase
I'm looking to clone addDriverContent (working fine) and increment the numbers for the name attribute on name="description" to name="description2", name="description3" on the clones Also if anyone know how to also clone the add button so it works as it should on the clones would be extra points :) Some fiddles would be awesome :) <div id="addDriverContent" style="display:none;"> <div class="content"> <div class="row"> <div class="col-md-12"> <label for="description" class="form-label font-weight-bold">Item Description:</label> <input type="text" class="form-control" id="description" name="description" placeholder="Enter the items description"/> </div> </div> </div> </div> <button type="button" class="add_field_button" id="clone_button">Add another item</button> <div id="clone_wrapper"></div> <script type="text/javascript"> $(function($) { var max_fields = 4; // origin selector would select all the first div ancestors. var $content = $("#addDriverContent > .content"); var $clone_wrapper = $("#clone_wrapper") ; var $add_button = $(".add_field_button"); //Add button ID $add_button.click(function(e) { e.preventDefault(); var counter = 0; // jquery object is array liked object. Length mean how many elements is selected. if ( $clone_wrapper.children(".content").length < max_fields ) $content.clone().appendTo($clone_wrapper); }); $clone_wrapper.on("click",".remove_field", function(e){ e.preventDefault(); // this would be more specific. $(this).parent(".content").remove(); }) }); </script>
As I have no idea what you intend to do with it, I will provide you with my dirty solution for it: <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="addDriverContent" style="display:none;"> <div class="content"> <div class="row"> <div class="col-md-12"> <label for="description" class="form-label font-weight-bold">Item Description:</label> <input type="text" class="description form-control" id="description" name="description" placeholder="Enter the items description"/> <input type="text" class="fname form-control" id="fname" name="fname"/> Remove<button type="button" class="add_field_button" id="clone_button">Add another item</button> </div> </div> </div> </div> <button type="button" class="add_field_button" id="clone_button">Add another item</button> <div id="clone_wrapper"></div> <script type="text/javascript"> $(function($) { var max_fields = 4; // origin selector would select all the first div ancestors. var $content = $("#addDriverContent > .content"); var $clone_wrapper = $("#clone_wrapper") ; var $add_button = $(".add_field_button"); //Add button ID $(".add_field_button").click(function() { //e.preventDefault(); //var counter = 0; // jquery object is array liked object. Length mean how many elements is selected. if ( $clone_wrapper.children(".content").length < max_fields ) { $content.clone().appendTo($clone_wrapper); //$add_button.clone().appendTo($clone_wrapper);// mine $(".description").each(function(index) { $( this ).attr('name', 'description'+index) }); $(".fname").each(function(index) { $( this ).attr('name', 'fname'+index) }); } }); $(document).on('click', "#clone_wrapper .add_field_button", function () { $('#addDriverContent + .add_field_button').trigger('click'); }) $(document).on('click', ".remove_field", function () { //e.preventDefault(); // this would be more specific. $(this).closest(".content").remove(); }); }); </script>
how to have numbers output with commas
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"
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>
duplicate and clone div
sorry i do not speak english well, i want to create a tool that allows to duplicate a div thanks to an "input number" and a button and then I also want to clone this tool by reinitializing it to be able to use the tool again , Here is a piece of code: $(function() { $('#btn_dupliquate').on('click', function() { var numDuplication = $('#num-duplication').val(); if (numDuplication > -1) { var div = $('.common_preview'); $('.result').html(''); for (var i = 0; i < numDuplication; i++) { $('.result').append(div.clone()); } } }); }); $(function() { $(".heading").keyup(function() { var heading=$(this).val(); $(".common_preview").html("<div class='bloc'><p class='model'>"+heading+"</p></div>"); return false; }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="toNumDuplicate"> <input type="text" class="heading" /> <br/> <br/> <input id="num-duplication" type="number" > <br/> <br/> <button id="btn_dupliquate"> dupliquate </button> </div> <div id="toDuplicate"> <div class="common_preview" > <div class="bloc"> <p class="model">test</p> </div> </div> </div> <div class="result"></div> <button id="btn_clone">clone</button>
You could abstract your function to take dynamic selector strings for the duplicate button, duplicate number input, preview div and result div.