jQuery blur behaving strangely - javascript

I want to listen blur event of every input field in the form, but when I reset the form after calculation, the again when i get focus of the input field it fires blur event two times, one with empty value and one with input value.
<form id="form">
Total Ore to be Mined:
<input type="number" name="TOmined" value="0" autofocus> Tons
<br> Total Waste to be Mined:
<input type="number" name="TWmined" value="0"> Tons
<br> Number of Operating Days/Year:
<input type="number" name="OperatingDays" value="0"> Days
<br> Number of Operating Years:
<input type="number" name="OperatingYrs" value="0"> Years
<br>
</form>
<script>
var arr = {};
// {"TOmined": inputValue}
$(document).ready(function() {
$(":input").blur(function(e) {
var k = e.target.name;
var v = e.target.value;
arr[k] = v;
console.log(k, v); // **runs two times one with empty string**
// one with original value
})
});
function calculate() {
var sum = 0;
// your logic
console.log(arr);
// end logic
if (!jQuery.isEmptyObject(arr)) {
for (v in arr)
sum += parseInt(arr[v]);
console.log(sum);
}
$('#form').trigger("reset");
// $('#result').html(value to be displayed + ' tons/day');
arr = {};
}
</script>

Quickest way to spot the problem would be to add this line to your blur callback:
console.log(e.target);
... which will show you the element that was blurred. In this case, it's your <button/> element that is triggering a blur event. You're binding the blur callback to all :input elements, and :input is a jQuery extension that includes input, textarea, select, and button elements (see documentation).
To fix this, you'll just want to bind to real input elements, not the :input selector.
$('input').blur(function (e) {
// ...
});

Related

Javascript - prevent onclick event from being attached to all elements with same class

I'm working on a simple form that includes an input field where the user will fill in the required amount by clicking the incrementor/decrementor. The form is created based on data pulled dynamically from the database
Below is the problematic part: html and the jquery handling it:
The incrementor, decrementor and the input field:
-
<input type="text" id="purchase_quantity" class = "purchase_quantity" min="1" max="6" delta="0" style = "width: 32px;" value="1">
+
and the jquery handling the above:
jQuery(function ($) {
$('.addItem').on('click', function () {
var inputval = $(this).siblings('.purchase_quantity').val();
var num = +inputval;
num++;
if(num>6)num=6;
console.log(num);
$(".purchase_quantity").val(num);
return false;
});
$('.removeItem').on('click', function () {
var inputval = $(this).siblings('.purchase_quantity').val();
var num = +inputval;
num--;
if(num<1)num=1;
console.log(num);
$(".purchase_quantity").val(num);
return false;
});
});
Now, what's happening is: onclick of the incrementor/decrementor (+ and -) the value on the input field changes across all the fields in the page instead of the one clicked only. Have spent quite some time on this with no success and will appreciate some help
The line
$(".purchase_quantity").val(num);
says, literally, to change the value on all the fields. Earlier you used
$(this).siblings('.purchase_quantity').val()
to get the value, so why not also use
$(this).siblings('.purchase_quantity').val(num)
to set it?
That's because siblings will get you all items on the same level.
Get the siblings of each element in the set of matched elements,
optionally filtered by a selector.
Place them in separate div elements, and adjust your setter to actually only update the siblings inside that div.
jQuery(function ($) {
$('.addItem').on('click', function () {
var inputval = $(this).siblings('.purchase_quantity').val();
var num = +inputval;
num++;
if(num>6)num=6;
console.log(num);
$(this).siblings('.purchase_quantity').val(num);
return false;
});
$('.removeItem').on('click', function () {
var inputval = $(this).siblings('.purchase_quantity').val();
var num = +inputval;
num--;
if(num<1)num=1;
console.log(num);
$(this).siblings('.purchase_quantity').val(num);
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
-
<input type="text" id="purchase_quantity2" class = "purchase_quantity" min="1" max="6" delta="0" style = "width: 32px;" value="1">
+
</div>
<div>
-
<input type="text" id="purchase_quantity1" class = "purchase_quantity" min="1" max="6" delta="0" style = "width: 32px;" value="1">
+
</div>
you should change $(".purchase_quantity").val(num) to $("#purchase_quantity").val(num)

Sum up all text boxes with a particular class name?

I have a grid, with one of the columns containing a textbox, where a user can type in a dollar amount. The text boxes are declared as:
<input class="change-handled" sub-category-id="83" data-id="" style="text-align: right; width: 100%" type="number" value="">
Some are all decorated with the class "change-handled".
What I need to do, is, using javascript/jquery, sum up all the boxes which are using that class, and display the total elsewhere on the screen.
How can I have a global event, that would allow this to occur when ever I exit one of the boxes (i.e: Tab out, or ENTER out).
At the moment, I have an event which doesn't do much at the moment, which will be used:
$('body').on('change', 'input.change-handled', SaveData);
function SaveData() {
var dataId = $(this).attr('data-id');
var categoryId = $(this).attr('sub-category-id');
var value = $(this).val();
}
How can I use that SaveData event, to find all the editboxes with the 'change-handled' class, sum up their values, and display it somewhere?
In plain JavaScript:
var changeHandled = [].slice.call(document.querySelectorAll('.change-handled'));
var total = document.querySelector('.total');
function calc() {
total.textContent = changeHandled.reduce(function(total, el) {
return total += Number(el.value);
}, 0);
}
changeHandled.forEach(function(el) {
el.onblur = calc;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="change-handled">
<input type="number" class="change-handled">
<input type="number" class="change-handled">
Total: $<span class="total">0</span>
I think what you're looking for is the blur event.
$('body').on('blur', 'input.change-handled', UpdateTotal);
function UpdateTotal() {
var total = 0;
var $changeInputs = $('input.change-handled');
$changeInputs.each(function(idx, el) {
total += Number($(el).val());
});
$('.total').text(total);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="change-handled">
<input type="number" class="change-handled">
<input type="number" class="change-handled">
Total: $<span class="total">0</span>
Here's how you can sum up the values:
var total = 0;
$(".change-handled").each(function(index, box) {
total += parseInt($(box).val(), 10);
});
You would then display them by using the text or html functions provided by jQuery on elements.
This can be used from anywhere in your code, including the event handler.

updating values of an array through <input> tags

I have the following three tag:
<input class="forLoopIndex" id="typicalElement" type="text" name="k" size="1" placeholder="10">
<input class="forLoopIndex" type="text" name="n" size="1" placeholder="n">
<input class="forLoopIndex" type="text" name="i" size="1" placeholder="i">
Now I have an event listener that checks when a value comes in, and then stores it in an array. I want the array to be kept at 3 values only. Cause I need to use the third and the second for something, but I need to see when they change. Here is the JS for that:
forloops.keyup(function () {
if (forLoopIndex.length < 2 && forLoopIndex >= 0) {
forloops.each(function () {
forLoopIndex.push($(this).val());
appendingToSigmaLimit();
console.log(sigmaLimit.val());
console.log(forLoopIndex);
});
} else if (forLoopIndex.length > 2) {
forLoopIndex = [];
}
});
Now, the problem is that, the values will only update until I have changed the values of the three inputs again. I have a feeling that the way of the logic is in my JS is making it do that. I just need to update the values every time that I change a value on one of my inputs. Any ideas?
Thanks,
M
Not sure what you expected, something like this will update each input separatly
var forloops= $('.forLoopIndex');
var forLoopIndex = [];
forloops.keyup(function () {
forloops.each(function (i, e) {
forLoopIndex[i] = $(this).val();
console.log(i);
console.log(forLoopIndex);
});
});
FIDDLE
Edit without loop:
var forloops= $('.forLoopIndex');
var forLoopIndex = [];
forloops.keyup(function () {
forLoopIndex[$(this).index('.forLoopIndex')] = $(this).val();
console.log(forLoopIndex);
});
FIDDLE

press button and value increases in text box

So when the page loads the text box will contain a stored value. I want the user to press the '+' button and the value in the text box will increase by one. Im guessing this is done with JQuery...Any ideas on where to get started so far I have...
<input type="text" name="BoqTextBox" id="BoqTextBox" value="0" />
<input type="Button" value="+" onclick="AddOne(document.getElementById('BoqTextBox').value)" />
<script>
function Add(data) {
//so the current digit is passed to here, where I need to do some funky code
//where it increments the current digit by one and stores it in BoqTextBox - replacing the old digit.
//Also to note if the text box contains 124.54 for example and + is pressed
//then new value will be 125.54
}
</script>
Any assistance with this would be great.
Thank you
...something like data = data + 1, but then how do I return the value into the text box?
You can use jQuery's val() to fetch and set a value. In this case the code you need could look like this (demo):
<input type="text" name="BoqTextBox" id="BoqTextBox" value="0" />
<input type="Button" id='AddButton' value="+" />
<script>
$('#AddButton').on('click', function () {
var input = $('#BoqTextBox');
input.val(parseFloat(input.val()) + 1);
})
</script>
$('input[type="button"]').on('click', function() { // bind click event to button
$('#BoqTextBox').val(function() { // change input value using callback
return ++parseFloat( this.value, 10); // make value integer and increment 1
})
});
you are callin Addone function inline so that means your function should be AddOne()
try this
function AddOne(obj){
var value=parseFloat(obj) + 1;
$('#BoqTextBox').val(value);
}
$("#buttonId").click(function()
{
var txtBox = $("#boqtextbox");
if(!isNaN(txtBox.val()))
{
txtBox.val(parsFloat(txtBox.val())+1) ;
}else
{
//do validation or set it to 0
txtBox.val(0);
}|
});

How to use onchange in HTML

I have two text box in html ie:
<input type="text" value="" id="a" name="a" />
<input type="text" value="" readonly="true" id="b" name="b" />
Now if i enter only a number in element id "a" then the product of inserted number by 2 will be appear in element id "b".
Like:
While i m typing a number let say 11 in element "a"
then on the same time 11*2 ie: 22 will appear in element "b"
and if enter backspace or delete any number on the same time change will appear in element "b".
To get my required result i create a function like
onchange = function totalAmount()
{
var value = $("#a").val();
if ( (value > 0) && (value != "") )
{
$("input:text[name=b]").val(2 * value);
}
else
{
$("input:text[name=getCredit]").val("");
}
};
It fulfill 80% of my requirement as it will make change in element "b" if i click on any were after insert a number.
I see that you are using jQuery. You could bind to the change event of the textbox:
$('input:text[name=a]').change(function() {
// invoked when the value of input name="a" changes
// get the new value
var value = $(this).val();
// update the value of input name="b"
$('input:text[name=b]').val(2 * value);
});
This event will be raised when the input loses focus. You could also take a look at keypress and keyup events.
i think using the onkeyup event might help
<input type="text" value="" id="a" name="a" onkeyup="calcTotalAmount()" />
<input type="text" value="" readonly="true" id="b" name="b" />
<script>
function calcTotalAmount() {
var a = document.getElementById("a");
var b = document.getElementById("b");
if (!isNaN(a.value)) {
b.value = a.value * 2;
}
}
</script>
Why onkeyup?
Onkeydown event fires when key is pressed, onkeyup event fires when key is released and the event onkeypress fires if the onkeydown is followed by onkeyup,
and in the time of onkeydown the input field does not containt the value yet.
If you want a call back on every key press you can use the onKeyPress attribute.
(If you are using a library like JQuery/prototype/etc there is probably a nice way of observing a field using the library)

Categories

Resources