I have an html form, and I want to only show the last section of the form if the value of all the other inputs is <= 500. Here is some simple html, mine is slightly more complicated, but it should be the same idea:
<div id="addSection">
<input type="text" id="retire" />
<input type="text" id="child" />
<input type="text" id="military" />
<input type="text" id="nurse" />
<input type="text" id="other" />
</div>
<div id="random" class="hidden">
<input type="text">
</div>
And here my jQuery that doesn't get close to working :)
$('#addSection :input').keyup(function(){
$('#addSection').each(function(){
var totalAmt = 0;
$(this).find('input').each(function(i,n){
totalAmt += parseInt($(n).val(), 10)
});
});
});
//if totalAmt <= 500 then $('#random').show();
Any ideas on how to get it to add as the user goes through the form? Thanks for the help, if you ahve any questions, I will answer quickly.
I'd suggest (on reviewing and subsequently rewriting my previous attempt):
$('#addSection').on('keyup', function(){
var total = $(this).children().map(function(){
return parseInt(this.value,10) || 0;
}).get().reduce(
function(a, b){
return parseInt(a,10) + parseInt(b,10);
});
$('#random').toggle(total <= 500);
}).trigger('keyup');
JS Fiddle demo.
References:
Plain JavaScript:
Array.prototype.reduce().
parseInt().
jQuery:
children().
get().
on().
toggle().
This should do the trick:
$('#addSection :input').keyup(function(){
var totalAmt = 0
$('#addSection :input').each(function(){
totalAmt += parseInt($(this).val(), 10) || 0
});
$('#random').toggle(totalAmt <= 500);
});
Live example: http://jsfiddle.net/ZL3q4/2/
Try this:
<div id="addSection">
<input type="text" id="retire" />
<input type="text" id="child" />
<input type="text" id="military" />
<input type="text" id="nurse" />
<input type="text" id="other" />
</div>
<div id="random" style="display: none;">
<input type="text">
</div>
$('#addSection :input').keyup(function () {
var totalAmt = 0;
$('#addSection :input').each(function (i, n) {
if (parseInt($(n).val(), 10)) totalAmt += parseInt($(n).val(), 10);
});
if (totalAmt > 500) $("#random").show();
else $("#random").hide();
});
Related
I need the following output as shown in the gif below.
I created three inputs which I put in the box below. How can I have such output?
Please help with an example
NOTE:Suppose we have 50 inputs and the class is the same
I can't use it after Get ID
MY HTML code
<span class="pricing-heading">Your sale price:</span><div class="pricing-field"><input class="pricing-set-price" type="number" value="24.00"></div>
</div>
<div class="prt-pricing-detial">
<span class="pricing-heading">Product base Cost:</span><div class="pricing-field"><input class="pricing-base-price" type="number" value="10.00" disabled></div>
</div>
<div class="prt-pricing-detial">
<span class="pricing-heading">Your profit:</span><div class="pricing-field"><input class="pricing-profit" type="number" value="14.00" disabled></div>
</div>
JS code :
$(".pricing-set-price").change(function(){
var item_rrp = $(this).val();
var item_base = $(this).parent().parent().parent().find('.pricing-base-price').val();
var profit = item_rrp - item_base;
var profit_format = profit.toFixed(2);
$(this).parent().parent().parent().find('.pricing-profit').val(profit_format);
});
You may try like
$(".pricing-set-price").change(function(){
let currentValue = $(this).val();
var previousValue = this.defaultValue;
if(previousValue < currentValue){
this.defaultValue = currentValue;
console.log('Increment');
}else{
console.log('Decrement');
}
});
You can call the function that changes the value of Profit (input) on the onchange , oninput, or onClick events of the SalePrice(input)
function increment() { document.getElementById('salePrice').stepUp();
calculateProfit()
}
function decrement() {
document.getElementById('salePrice').stepDown();
calculateProfit()
}
function calculateProfit(){
let sp = document.getElementById("salePrice").value;
document.getElementById("profit").value = sp - 10;
}
<input id="salePrice" type=number value=10 min=10 max=110 />
<button onclick="increment()">+</button>
<button onclick="decrement()">-</button>
<br/>
Base Price :: <input type="text" id="basePrice" value=10
disabled >
<br/>
Profit :: <input type="text" id="profit" value=0 />
For more info about:
stepUp()
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/stepUp
stepDown()
https://www.w3schools.com/Jsref/met_week_stepdown.asp
Hi i think this might help. use id for your input fields.
function calculateProfit(val){
var baseCost = document.getElementById("baseCost").value;
document.getElementById("Profit").value = (val - baseCost).toFixed(2);
}
<div class="prt-pricing-heading">
<span class="pricing-heading">Your sale price:</span>
<div class="pricing-field"><input id="SalePrice" class="pricing-set-price" type="number" value="24.00" onchange="calculateProfit(this.value);" oninput="calculateProfit(this.value)"></div>
</div>
<div class="prt-pricing-detial">
<span class="pricing-heading">Product base Cost:</span>
<div class="pricing-field"><input id="baseCost" class="pricing-base-price" type="number" value="10.00" disabled></div>
</div>
<div class="prt-pricing-detial">
<span class="pricing-heading">Your profit:</span>
<div class="pricing-field"><input id="Profit" class="pricing-profit" type="number" value="14.00" disabled></div>
</div>
For More info regarding:
oninput() https://www.w3schools.com/tags/att_oninput.asp
onchange() https://www.w3schools.com/tags/ev_onchange.asp
Hi I want use this script to count char in form with many fields,
but not want duplicate code, I want use only one code for all fields,
how can pass to javascript name fields count and display this count...
As one counter for many fields input type...
thanks
Salvatore
<script>
function countChar(val) {
var len = val.value.length;
if (len >= 66) {
val.value = val.value.substring(0, 66);
} else {
$('#charNum').text(65 - len);
}
};
</script>
<div id="charNum"></div>
<input type="text" name="name_var1" value="" maxlength="66" onkeyup="countChar(this)" />
<div id="charNum"></div>
<input type="text" name="name_var2" value="" maxlength="66" onkeyup="countChar(this)" />
<div id="charNum"></div>
<input type="text" name="name_var3" value="" maxlength="66" onkeyup="countChar(this)" />
the problem is that you are using ids several times. Try to work with classes and generate the selectors from the class name of the element.
<script>
function countChar(val) {
var len = val.value.length;
if (len >= 66) {
val.value = val.value.substring(0, 66);
} else {
$('.' + val.className + '_charNum').text(65 - len);
}
};
</script>
<div class="name_var1_charNum"></div>
<input class="name_var1" type="text" name="name_var1" value="" maxlength="66" onkeyup="countChar(this)" />
<div class="name_var2_charNum"></div>
<input class="name_var2" type="text" name="name_var2" value="" maxlength="66" onkeyup="countChar(this)" />
<div class="name_var3_charNum"></div>
<input class="name_var3" type="text" name="name_var3" value="" maxlength="66" onkeyup="countChar(this)" />
As far as I understood you do need to display characters left value for each field (depending on max-length) and restrict user from adding extra characters (more than allowed limit). Probably that's what you need.
<div class="countable-item">
<div class="char-num"></div>
<input type="text" name="any" class="countable" max-length="66" />
</div>
<div class="countable-item">
<div class="char-num"></div>
<input type="text" name="any2" class="countable" max-length="66" />
</div>
<script>
(function($){
var restrictMaxLength = function () {
var maxLength = $(this).attr('max-length'),
currentValue = $(this).val(),
currentLength = currentValue.length;
if (currentLength >= maxLength) {
return false;
}
},
displayCountCharacters = function () {
var maxLength = $(this).attr('max-length'),
currentValue = $(this).val(),
currentLength = currentValue.length;
$(this).closest('.countable-item')
.find('.char-num')
.text(maxLength - currentLength);
};
$(document)
.on('keypress', '.countable', restrictMaxLength)
.on('keyup', '.countable', displayCountCharacters);
})(jQuery);
</script>
Hello I need to sum the values of same class input in one input with class name total.
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="total" value="" />
Possible?
A working fiddle here
$(document).on("change", "qty1", function() {
var sum = 0;
$("input[class *= 'qty1']").each(function(){
sum += +$(this).val();
});
$(".total").val(sum);
});
You pretty much had it, just needed to adjust your JQuery a little bit for the appropriate selectors
updated fiddle : http://jsfiddle.net/5gsBV/7/
$(document).on("change", ".qty1", function() {
var sum = 0;
$(".qty1").each(function(){
sum += +$(this).val();
});
$(".total").val(sum);
});
I suggest this solution:
html
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="total" value="" />
<div id="result"></div>
js
$(".qty1").on("blur", function(){
var sum=0;
$(".qty1").each(function(){
if($(this).val() !== "")
sum += parseInt($(this).val(), 10);
});
$("#result").html(sum);
});
fiddle
I think your issue is here:
$("#destination").val(sum);
change it to:
$(".total").val(sum);
And instead of change event i suggest you to use keyup instead.
$(document).on("keyup"
$(document).on("keyup", ".qty1", function() {
var sum = 0;
$(".qty1").each(function(){
sum += +$(this).val();
});
$(".total").val(sum);
});
We can use following own function
(function( $ ){
$.fn.sum=function () {
var sum=0;
$(this).each(function(index, element){
sum += parseFloat($(element).val());
});
return sum;
};
})( jQuery );
//Call $('.abcd').sum();
http://www.gleegrid.com/code-snippet/javascript/jquery-sum-input-values-by-class/?filter=bygroup&group=JQuery
$('.qty1').each(function(){
sum += parseFloat(this.value);
});
console.log(sum);
This will work with pure js
<input type="text" value=" " class="percent-input"> <br>
<input type="text" value=" " class="percent-input"> <br>
<input type="text" value=" " class="percent-input"> <br>
<p>Total Value :<span id="total">100%</span></p>
<p>Left Value :<span id="left">0.00%</span></p>
var percenInput = document.querySelectorAll('.percent-input');
for (let i = 0; i < percenInput.length; i++) {
percenInput[i].addEventListener('keyup', getPercentVal)
}
function getPercentVal() {
var total = 0;
var allPercentVal = document.querySelectorAll('.percent-input');
for (var i = 0; i < allPercentVal.length; i++) {
if (allPercentVal[i].value > 0) {
var ele = allPercentVal[i];
total += parseFloat(ele.value);
}
}
document.getElementById("total").innerHTML = total.toFixed(2) + '%';
document.getElementById("left").innerHTML = (100 - total).toFixed(2) + '%';
}
You almost had it:
$(document).on("change", ".qty1", function() {
var sum = 0;
$(".qty1").each(function(){
sum += +$(this).val();
});
$(".total").val(sum);
});
http://jsfiddle.net/DUKL6/1
The problem with all of the above answers is that they fail if you enter something other than a number. If you want something that is more friendly to users, you should do some validation, perhaps even give some feedback when a value other than a number is entered.
$('body').on('change', '.qty1', function() {
var total=0;
$(".qty1").each(function(){
quantity = parseInt($(this).val());
if (!isNaN(quantity)) {
total += quantity;
}
});
$('.total').val('Total: '+total);
});
<input type="text" class="price" placeholder="enter number one" />
<input type="text" class="price" placeholder="enter number two" />
<input type="text" class="price" placeholder="enter number three" />
<input type="text" class="price" placeholder="enter number four" />
<input type="text" id="total">
<script>
$(document).ready( function() {
$(document).on("keyup", ".price", function() {
var sum = 0;
$(".price").each(function(){
sum += +$(this).val();
});
$('#total').val(sum);
});
});
</script>
If say i am having a textbox input and a integer value A then how to check at time of typing the data itself that the value entered in textbox does not exceed A.
Textbox :
<input type="textbox" name="mynumber">
My script :
(According to answer by Felix)
<script type="text/javascript">
<%int n=(Integer)request.getAttribute("n");%>
var A=<%=n%>;
$('input[name^=txtDynamic_]').keyup(function () {
if (+this.value > A) {
$(this).next().html('Greater than Total shares');
flag=1;
}
else{
$(this).next().html('');
}
});
</script>
FORM :
<FORM METHOD=POST ACTION="stegnographyonshares" enctype="multipart/form-data">
<c:forEach var="i" begin="1" end="${myK}">
Enter The ${i} share number: <input type="text" name="txtDynamic_${i}" id="txtDynamic_${i}" /><span></span>
<br />
<br>
</br>
</c:forEach>
<br></br>
<INPUT TYPE="file" NAME="file" value="file">
<br></br>
<INPUT TYPE="submit" value="SAVE">
</form>
Whats problem in this ? the script code is not running and not printing the error message.Please help
You can use .keyup() event:
$('input[name=mynumber]').keyup(function() {
if(this.value.length > A) {
console.log('Toal characters exceed A')
}
});
Fiddle Demo
Based on your comment, you can do:
$('input[name=mynumber]').keyup(function() {
if(+this.value > A) {
console.log('Number exceed A');
}
});
Fiddle Demo
//length of text
var Count = 10;
//set id of your input mynumber
$("#mynumber").keyup(function(){
if($(this).val().length() > Count) {
$(this).val().subString(0,Count);
}
});
Do this:
var A = 10;
$('[name="mynumber"]').keyup(function () {
if (parseInt($(this).val(), 10) > A) {
alert("More than A");
} else {
alert("Less than A");
}
});
Demo
Can even be done using HTML5 output tag
<form oninput="x.value = parseInt(a.value) > 10 ? 'Greater than 10' : 'Less than 10' ">
<input type="range" id="a" value="">
<output name="x" for="a"></output>
</form>
Fiddle
Reference
I'm making an HTML form, and I'd like some fields to be under "Advanced Options". I want to make an "Advanced Options" link, maybe with a "plus" sign, so that when the user clicks on the link or the sign, those advanced fields show up. How can I do this in JavaScript? I've tried searching for something like "Hide/show advanced option" on Google, but can't find a solution.
<form ... />
<label>
Title
<input id="title" name="title" size="40" type="text" value="" />
</label>
<label>
Year
<input id="year" name="year" size="20" type="text" value="" />
</label>
<label>
Year
<input id="comment" name="comment" size="40" type="text" value="" />
</label>
</form>
For example, here I want the "comment" field to be advanced.
<a href='#' class='advanced'>Advanced Options</a>
<div id='advancedOptions'><!-- Form stuff here --></div>
<script type='text/javascript'>
$(document).ready(function () {
$('#advancedOptions').hide();
$('.advanced').click(function() {
if ($('#advancedOptions').is(':hidden')) {
$('#advancedOptions').slideDown();
} else {
$('#advancedOptions').slideUp();
}
});
});
</script>
It will hide the advancedOptions element on load, when you click the a tag it will check if the advancedOptions is hidden, if it is then it will show it if it isn't hidden it will hide it. You will need;
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
at the top of the page you're using, I know it's JQuery, but it would be useful to learn JQuery for future reference
You're looking for something like this (Pure JS):
function more(obj) {
var content = document.getElementById("showMore");
if (content.style.display == "none") {
content.style.display = "";
obj.innerHTML = "-";
} else {
content.style.display = "none";
obj.innerHTML = "+";
}
}
This function checks the visibility of your content, if it's hidden, shows it, and vice versa. It also changes the plus sign to a minus. Here's the revised HTML:
+
<br>
<label id="showMore" style="display: none;">
Year
<input id="comment" name="comment" size="40" type="text" value="" />
</label>
And a demo: http://jsfiddle.net/uSqcg/
create a div element, create a css rule to have it hidden by default, on your div element add onmouseover and onmouseout events, and have the following functions associated to those:
function showSomething(textToShow, container) {
var yourElement = $('#yourDivElement');
yourElement.removeClass('hidden');
var w = container.getClientRects()[0].width;
var h = container.getClientRects()[0].height;
var t = container.getClientRects()[0].top;
var l = container.getClientRects()[0].left;
var st = document.documentElement.scrollTop;
var sl = document.documentElement.scrollLeft;
if (st == 0 && document.body.scrollTop > st)
st = document.body.scrollTop;
if (sl == 0 && document.body.scrollLeft > sl)
sl = document.body.scrollLeft;
yourElement.css('top', t + st + h / 3 * 2);
yourElement.css('left', l + sl + w / 3 * 2);
yourElement.html(textToShow);
var lines = textToShow.length / 20;
yourElement.css('height', 20 + lines * 10);
}
function hideSomething() {
$('#yourDivElement').addClass('hidden');
}
just in case (a css rule to hide)
.hidden {
display: none;
}
and ... just in case
<div onmouseover="showSomething('show this', this);" onmouseout="hideSomething();" class="hidden"></div>
this will position the floating dialog (something like an alt) related to the parent object of your div (The one containing your div element)...
simple ;)
Try this code, here is the demo
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('.advanced').click(function()
{
$('#hide').toggleClass("hidden");
});
});
</script>
<style>
.hidden
{
display:none;
}
</style>
</head>
<body>
<form >
<label>
Title
<input id="title" name="title" size="40" type="text" value="" />
</label><br/>
<label>
Year
<input id="year" name="year" size="20" type="text" value="" />
</label><br/>
<label class="advanced">
+
</label><br/>
<label id="hide" class="hidden">
Year
<input id="comment" name="comment" size="40" type="text" value="" />
</label>
</form>
</body>
</html>