The problem is that when i change the option it keeps summing, and i would like for it to only sum one time the value of 10.00, and subtract only once if the value is AR .
LIVE LINK: http://jsfiddle.net/A3qLG/1/
JQUERY:
$(document).ready( function() {
$('#country').on('keyup change', function(e){
var subt_value = $('#subt0').text();
if($(this).val() == 'AR' || $(this).val() == ''){
if(subt_value != '0.00' ){$('#subt0').text(parseFloat(subt_value-10).toFixed(2));}
}else{
var add_sub = parseFloat(subt_value)+parseFloat('10.00');
$('#subt0').text(parseFloat(add_sub).toFixed(2));
}
});
});
HTML:
<label id="subt0">8.90</label>
<select id="country">
<option value="US">USA</option>
<option value="BR">Brasil</option>
<option value="AR">Argentina</option>
<option value="CU">Cuba</option>
</select>
I would change the HTML to this to store the original value:
<label id="subt0" data-original="8.90">8.90</label>
And then adjust the Javascript to this:
$(document).ready( function() {
$('#country').on('keyup change', function(e){
//Changed the following line to get the original value
var subt_value = $('#subt0').attr('data-original');
//Changed this to say, NOT AR and has a choice per the comments.
if($(this).val() != 'AR' && $(this).val().length > 0) {
var add_sub = parseFloat(subt_value)+parseFloat('10.00');
$('#subt0').text(parseFloat(add_sub).toFixed(2));
} else {
//Otherwise put it back to the original value
$('#subt0').text(subt_value);
}
});
});
try this code
$(document).ready( function() {
$('#country').on('keypress change', function(e){
var subt_value = $('#subt0').text();
if($(this).val() == 'AR' || $(this).val() == ''){
if(subt_value != '0.00' ){$('#subt0').text(parseFloat(subt_value-10).toFixed(2));}
}else{
var add_sub = parseFloat(subt_value)+parseFloat('10.00');
$('#subt0').text(parseFloat(add_sub).toFixed(2));
}
});
});
You need to remember previous #country select value, and use it when making decision:
$(document).ready(function () {
var prevValue = '';
$('#country').on('keyup change', function (e) {
var newValue = $(this).val();
var subt_value = parseFloat($('#subt0').text());
if ((newValue == 'AR' || newValue == '')) {
if (prevValue != '' && prevValue != 'AR') {
$('#subt0').text((subt_value - 10).toFixed(2));
}
} else {
if (prevValue == 'AR' || prevValue == '') {
$('#subt0').text((subt_value + 10).toFixed(2));
}
}
prevValue = newValue;
});
});
http://jsfiddle.net/A3qLG/5/
Simply remove the onkeyup and onchange event handler functions after they have done their work.
$('#country').off('keyup change');
Jquery provide a .change() specifically for <select>
You want to sum only one time and substract only one time base on the condition of the selected value AR. Therefore you only need to check the selected value if there is change and do the math within the if-else statement. Finally attach the result with .toFixed(2)
var subt_value = $('#subt0').text();
var add_sub = 0, f=10.00;
$('#country').change(function(){
if ($(this).val() != 'AR'){
add_sub = parseFloat(subt_value)+f;
}else{
add_sub = parseFloat(subt_value)-f;
}
$('#subt0').text(add_sub.toFixed(2));
});
JSFiddle Demo
Related
I have a fiddle which checks for any duplicate entry entered in html input boxes.
It works in a way that if any duplicate entry is entered in a newly added row or the rows which are already there then the alert message "duplicate" is displayed.
I have used the following script in order to make that happen.
$('input[name*="code"]').each(function() {
$(this).change(function(){
let value = $(this).val();
let count = 0;
$('input[name*="code"]').each(function() {
if ($(this).val() != '' && $(this).val() == value) {
count++;
if (count > 1) { alert('duplicate'); }
}
});
});
$(this).addClass('e');
});
$('#addRow').on('click', function(){
$('input[name*="code"]:not(.e').each(function() {
$(this).change(function(){
let value = $(this).val();
let count = 0;
$('input[name*="code"]').each(function() {
if ($(this).val() != '' && $(this).val() == value) {
count++;
if (count > 1) alert('duplicate');
}
});
});
$(this).addClass('e');
});
});
What I am trying to achieve now is when any duplicate entry is entered in html input boxes then it should get disappeared automatically and the text "Please enter different text" left to the row should be displayed, something like this
http://jsfiddle.net/zHJSF/
This is what I have tried but it doesn't seem to work.
$('input[name*="code"]').each(function() {
$(this).change(function(){
let value = $(this).val();
let count = 0;
$('input[name*="code"]').each(function() {
if ($(this).val() != '' && $(this).val() == value) {
count++;
if (count > 1) {
alert('duplicate');
($(this).val()).stop(false,true).after(' <span style="color:red;" class="error">Please enter different text</span>');
$('.error').delay(600).fadeOut();
$(this).val('');
}
}
});
});
$(this).addClass('e');
});
$('#addRow').on('click', function(){
$('input[name*="code"]:not(.e').each(function() {
$(this).change(function(){
let value = $(this).val();
let count = 0;
$('input[name*="code"]').each(function() {
if ($(this).val() != '' && $(this).val() == value) {
count++;
if (count > 1) {
alert('duplicate');
($(this).val()).stop(false,true).after(' <span style="color:red;" class="error">Please enter different text</span>');
$('.error').delay(600).fadeOut();
$(this).val('');
}
}
});
});
$(this).addClass('e');
});
});
Problem Statement:
I am wondering what changes I should make in the script above so that it get rid of any duplicate entry entered in the html input boxes.
EDIT
This should work. It will get the input values and put them into an array, then check if the value exists in the array.
javascript
$('input[name*="code"]').each(function() {
$(this).change(function(){
let element = this;
var array = $('input[name*="code"]').map(function() {
if (this != element)
return $(this).val()
return null;
}).get();
if (array.includes($(this).val())) {
$(this).val("");
$(this).attr("placeholder", "Please enter different text");
$(this).addClass("error");
} else if ($(this).hasClass("error")) {
$(this).removeClass("error");
}
});
$(this).addClass('e');
});
css
.error {
border: 1px solid red;
}
I have a situation having a textbox having 15 as a max length property. That field works as a amount field. it is working correctly in normal cases.
lets say if i enter 11234567890.99 this amount in textbox it displays it as 112,34,567,890.99 which is expected.
But, if i copy & paste 112,34,567,890.99 amount in textbox last two digits gets truncated because the length gets out of bound.
Is there any ways to change this without modifying the exact behavior? allowing to paste whole 112,34,567,890.99 amount.
$(document).on("focusout","#txtformate1",(function () {
if (this.value != null && this.value != "") {
$((this.parentElement).nextElementSibling).hide()
}
else{
$((this.parentElement).nextElementSibling).show()
}
}));
$(document).on('keyup', '.Amt', function () {
var val = $(this).val();
val = val.replace(/([~!#$%^&*()_+=`{}\[\]\|\\:;'<>,\/? ])+/g, '');
if(isNaN(val) && val!="-")
{
val="";
}
$(this).val(val);
/*if (isNaN(val)) {
val = val.replace(/(?!^)-/g, '');
if(val.indexOf("-")>-1)
{
val = val.replace(/[`*\/]/g, '');
}
else{val = val.replace(/[^0-9\.]/g, '');}
if (val.split('.').length > 2)
{
val = val.replace(/\.+$/, "");
}
else if(val==".")
{
val ="";
}
}*/
});
$(document).on('focusout', '.Amt', function () {
var val = $(this).val();
val = val.replace(/(?!^)-/g, '');
if(isNaN(val) && val.indexOf(',')>-1){
val=$(this).val();
}
if (val == "0.00"){
val="";
}
$(this).val(val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control Amt" id="txtformate1" maxlength="15" />`
I have a lot of labels as shown on a page. I want to sum the values and store them in final_cpa.
HTML :
<label class="tmpcpa">32.1</label>
JS :
function calculate_final_cpa() {
var final_cpa = 0;
var allfilled = false;
$('.tmpcpa').each(function () {
if ($(this).val() != 0) {
final_cpa += parseInt($(this).text()) || 0;
allfilled = true;
} else {
allfilled = false;
}
});
console.log(final_cpa);
console.log(allfilled);
}
var run = setInterval(calculate_final_cpa, 500);
However final_cpa is always 0 and allfilled remains false.
That because label don't have a value attribute so the .val() function will always return an empty string, you have to use .text() instead to get the text content inside the label element :
if ($(this).val() != 0) {
Should be :
if ($(this).text() != 0) {
NOTE : as Rayon mentioned in the comment below text() will always return string so better to change the zero in condition to string '0'.
Hope this helps.
function calculate_final_cpa() {
var final_cpa = 0;
var allfilled = false;
$('.tmpcpa').each(function () {
if ($(this).text() != '0') {
final_cpa += parseInt($(this).text()) || 0;
allfilled = true;
} else {
allfilled = false;
}
});
console.log(final_cpa);
console.log(allfilled);
}
calculate_final_cpa();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="tmpcpa">32.1</label>
Check $(this).text() != "" instead of $(this).val() != 0 as You can not use .val() for getting label text. .text() will give you text of label
if ($(this).text() != "" && $(this).text() != "0") {
....
}
First thing, you need to use .text() instead of .val() to get the text inside a label. Also, if you are expecting your result to contain decimal digits, you need to use parseFloat():
function calculate_final_cpa() {
var final_cpa = 0;
var allfilled = false;
$('.tmpcpa').each(function () {
if ($(this).text() != 0) {
final_cpa += parseFloat($(this).text()) || 0;
allfilled = true;
} else {
allfilled = false;
}
});
console.log(final_cpa);
console.log(allfilled);
}
calculate_final_cpa();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<label class="tmpcpa">32.1</label>
<br />
<label class="tmpcpa">32.1</label>
Change
if ($(this).val() != 0)
to
if (parseInt($(this).text()) != 0)
Beside your code had an error, you should check the content of the table before parsing them. And because you use decimals in your example, you should switch from parseInt to parseFloat too.
And your allfilled varibale makes no sense, because if the last element of .tmpcpa was empty, it will be false again. So i removed it.
function calculate_final_cpa() {
var final_cpa = 0;
$('.tmpcpa').each(function () {
var content = $(this).text();
final_cpa += IsNumeric(content) ? parseFloat(content) : 0;
});
console.log(final_cpa);
}
Test it with .text instead of val() as label has no value property
Use Unary plus(+)/Number operator instead of parseInt as parseInt will ignore floating point
Use length of lable-elements to test whether all the label has values !== 0
function calculate_final_cpa() {
var final_cpa = 0;
var countOfFilled = 0;
$('.tmpcpa').each(function() {
if ($(this).text() !== '0') {
final_cpa += +($(this).text()) || 0;
++countOfFilled;
}
});
console.log('Total: ' + final_cpa);
console.log('All filled ' + $('.tmpcpa').length === countOfFilled);
}
calculate_final_cpa();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<label class="tmpcpa">32.1</label>
<label class="tmpcpa">32.1</label>
<label class="tmpcpa">0</label>
I'm having a problem in disabling textbox and combo box by using another combo box here is my javascript so far:
category.onchange = function () {
var val = this.options[this.selectedIndex].value;
document.getElementById("bos").disabled = (val == "Military","Civilian") ? true : false;
document.getElementById("afpsn").disabled = (val == "Dependent","Civilian") ? true : false;
};
and here's my html:
<select name="category" size="1" id="category">
<option selected="selected">Choose...</option>
<option value="Civilian">Civilian</option>
<option value="Military">Military</option>
<option value="Dependent">Dependent</option>
</select>
<select name="bos" id="bos" >
<option value="">Branch of Service</option>
<option value="PAF">PAF</option>
<option value="PA">PA</option>
<option value="PN">PN</option>
<option value="TAS">TAS</option>
</select>
<input id = "afpsn" name="afpsn" type="text" id="afpsn" size="38" placeholder="AFPSN" />
it should be whenever I select dependent or civilian the other combo box and text field will be disabled and will be enable when I select military. please help!
This fiddle will be help you. you can edit logic , too.
category.onchange = function () {
var val = this.options[this.selectedIndex].value;
// alert(val);
document.getElementById("bos").disabled = (val === "Military") ? false : true;
document.getElementById("afpsn").disabled = (val === "Military") ? false : true;
document.getElementById("afpsn").disabled = (val === "Dependent" || val === "Civilian" ) ? true : false;
document.getElementById("bos").disabled = (val === "Dependent" || val === "Civilian" ) ? true : false;
};
I dont think there is anything like (val == "Military","Civilian")
You can try this Fiddle
Try below code:
/*Function to check if value is in an array*/
function isInArray(value, array) {
return array.indexOf(value) > -1;
}
/*******************************************/
var s=document.getElementById("elementId");
s.disabled = isInArray(s.value,["Military","Civilian"]); //Function automatically returns "true" or "false" depending on value
Demo Fiddle
Try this instead:
Your condition (comparison with strings) is incorrect.
example
category.onchange = function () {
var val = this.options[this.selectedIndex].value;
document.getElementById("bos").disabled = (val === "Military" || val === "Civilian") ? true : false;
document.getElementById("afpsn").disabled = (val === "Dependent" || val === "Civilian") ? true : false;
};
EDIT:
To attach the event on page load (assuming you are not using jQuery), one way is to attach it on pageload like:
function init() {
category.onchange = function () {
var val = this.options[this.selectedIndex].value;
document.getElementById("bos").disabled = (val === "Military" || val === "Civilian") ? true : false;
document.getElementById("afpsn").disabled = (val === "Dependent" || val === "Civilian") ? true : false;
};
}
and something like this on your <body>
<body onload="init();">
...
</body>
The reason why the example worked is that jsfiddle.net loads the functions in the js box on load by default. But in your case, you have to do that manually.
With the code below, the value of .srch-inpt is changing according to the selected option's class.
I need to remove the value of the .srch-inpt on focus and have it back on blur.
The code I've written does not work properly.
//Changing search value on select-box option change
$(function(){
$('.srchopts').change(function () {
var optclass = "";
$("select option:selected").each(function () {
optclass += $(this).attr('class');
});
if (optclass == 'bookopt' || 'thesisopt' ) {
$('.srch-inpt').val('Title/ Author/ Keyword/ ISBN');
}
if (optclass == 'articleopt' ) {
$('.srch-inpt').val('Title/ Author/ Keyword/ Doi');
}
if (optclass == 'journalopt' ) {
$('.srch-inpt').val('Title/ ISSN');
}
});
$('.srch-inpt').focus(function() {
if ($(this).val() == $(this).attr('defaultValue'))
$(this).val('');
}).blur(function() {
if ($(this).val() == '')
$(this).val( $(this).attr('defaultValue') );
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<select class="srchopts">
<option class="bookopt">Book Option</option>
<option class="articleopt">Article Option</option>
<option class="thesisopt">Thesis Option</option>
<option class="journalopt">Journal Option</option>
</select>
<input type="text" name="" class="srch-inpt" value="Title / Author / Keywords / ISBN" defaultValue="" />
JSFiddle Demo
$('.srch-inpt').data('defaultValue','My default value').focus(function () {
if (this.value === $(this).data('defaultValue')) this.value = "";
}).blur(function () {
if (!this.value.length) this.value = $(this).data('defaultValue');
}).blur();
DEMO
I got the answer with the point A. Wolff mentioned.
As we don't have "DefaultValue" attribute in new jQuery, I have to create it by myself, and update it's value each time I change .srch-inpt value.
So, this is my new jQuery piece of code :
//Changing search value on select-box option change
$(function(){
$('.srchopts').change(function () {
var optclass = "";
$("select option:selected").each(function () {
optclass += $(this).attr('class');
});
if (optclass == 'bookopt' || 'thesisopt' ) {
$('.srch-inpt').val('Title/ Author/ Keyword/ ISBN');
}
if (optclass == 'articleopt' ) {
$('.srch-inpt').val('Title/ Author/ Keyword/ Doi');
}
if (optclass == 'journalopt' ) {
$('.srch-inpt').val('Title/ ISSN');
}
$('.srch-inpt').attr('defaultValue', $('.srch-inpt').val());
});
$('.srch-inpt').focus(function() {
if ($(this).attr('defaultValue') == '')
$(this).attr('defaultValue', $(this).get(0).defaultValue);
if ($(this).val() == $(this).attr('defaultValue'))
$(this).val('');
}).blur(function() {
if ($(this).val() == '')
$(this).val( $(this).attr('defaultValue') );
});
});
DEMO