Using On Blur to Call a Function - javascript

I am trying to have a web page update a value when the text field loses focus. I have tried a number of different suggested variations for the onblur event but nothing seems to work as expected. Currently I have the onblur in the html code on line 59
<input name="qty1" id="qty1" size="8" value="0" onBlur="productCost()" />
and I have tried to make the correction in the script as well.
function productCosts()
{
var totalMap = document.getElementById("qty1").onblur();
totalMap.value = ("qty1") * ("price1");
//$("#cost1").html (totalMap.toFixed(2));
alert(totalMap)
//var totalPlanner = ('qty2') * ('price2');
//var totalHiker = ('qty3') * ('price3');
}
I have created a fiddle to show the entire program. http://jsfiddle.net/Jn6LQ/ Any help would be really greatly appreciated.

It's easy with jQuery
$('#qty1').bind('blur', productCosts)
or with JS
document.getElementById('qty1').addEventListener('blur', productCosts)

Note: In the below, $ is not jQuery, the OP is using it as a shortcut for getElementById.
The line
totalMap.value = ("qty1") * ("price1");
multiplies the string "qty1" with the string "price1". Perhaps you meant to look up the elements, and then get their values:
totalMap.value = $("qty1").value * $("price1").value;
Separately, using onXyz attributes is usually not best practice. Instead:
$("qty1").onblur = productCosts;
$("price1").onblur = productCosts;
function productCosts() {
var value = $("qty1").value * $("price1").value;
$("cost1").innerHTML = value.toFixed(2);
}
(There I'm assuming the price can be changed as well, but that may not be the case on your page.)
Looking at the fiddle, though, you have a much bigger problem: You want to do that for multiple lines. Using id values to do that is going to make for gainly, over-large code. Instead, use a class on each input, and then relate it to the other inputs in the row using the fact they're all in the same row.
function productCosts() {
var row = this.parentNode.parentNode,
qty = row.querySelector(".qty"),
price = row.querySelector(".price"),
cost = row.querySelector(".cost"),
value = qty.value * price.value;
cost.innerHTML = value.toFixed(2);
}
var list, i;
list = document.querySelectorAll(".qty, .price");
for (i = 0; i < list.length; ++i) {
list[i].onblur = productCosts;
}

jQuery.blur() looks like what you're looking for:
$('#qty1').blur(function(){
alert('here');
});

Related

Changing a dynamically created label's text with keyup() issue

I am creating a form dynamically and therefore edit the form elements’ properties. When attempting to change the label, assigning an auto-generated id works fine but when changing this label using the generated id, the function or keyup() from jQuery keeps calling all the previously created label id(s). this means when i want to edit one label, it ends up editing every label.
HTML
<input type="text" id="change-label"><br><br>
<button id="add-button">add label</button>
<div id="add-label"></div>
JavaScript/jQuery
$('#add-button').click(function(){
var div = document.createElement('div');
var textLabel = document.createElement('label');
var labelNode = document.createTextNode('untitled');
textLabel.appendChild(labelNode);
textLabel.id = autoIdClosure();
$('#change-label').val('untitled');
div.appendChild(textLabel);
$('#add-label').append(div);
});
var autoIdClosure = (function(){
var counter = 0;
var labelId = "textInputLabel";
return function(){
counter += 1;
var id = labelId + counter;
editLabelWrapper(id)
return id;
}
})();
function editLabelWrapper(id){
function editLabel(){
var value = $(this).val();
$("#"+id).text(value);
}
$("#change-label").keyup(editLabel).keyup();
}
I’ve already found an alternative using onkeyup="$('#'+globaID).text($(this).val());", but I need to understand what I was doing wrong so I can learn from it.
JSFiddle
I think you are overthinking the matter...
Instead of using an unique id, rather use classes, makes it easier to handle.
So change <div id="add-label"></div> to <div class="add-label"></div>
Then what you want to do is, when a value is given in #change-label you want it in the last div.add-label.
So the function will become this:
$("#change-label").on('keyup', function() {
$('.add-label:last').text( $(this).val() );
});
Next what you want to do is bind a function to #add-button. Once it gets clicked, we want to add a new div.add-label after the last one. And empty the #change-label. You can do that by using this function:
$('#add-button').on('click', function() {
$('.add-label:last').after('<div class="add-label"></div>');
$('#change-label').val('');
});
Updated Fiddle

Update total price?

I want a price to update when I click a button, that's all I want it to do, but everytime I try to call the value of my var, it returns "NotANumber/NaN" value, I've looked around for a little while but google get's a little bit confused and throws be tutorials about finding defined numbers, etc.
I am new to JavaScript, however. So it is probably me.
If anybody could help me out I'd be really grateful.
total price:
<span id="totalpriceex">0</span>
JavaScript:
<script type="text/javascript">
function incrementquan'.$row["pid"].'(){
var input = document.getElementById("quan'.$row["pid"].'");
input.value = parseInt(input.value) + 1;
var element = document.getElementById("price'.$row['pid'].'");
element.innerHTML = (" £" + (input.value * '.$row['pprice'].').toFixed(2));
var totalis = document.getElementById("totalprice");
totalis.value = parseInt(totalis.value);
totalis.innerHTML = (totalis.value + '.$row["pprice"].');
var totalpriceex = parseInt(totalpriceex.value);
totalpriceex.innerHTML = (totalis.value + '.$row["pprice"].'.toFixed(2))
var price=document.getElementById("totalpriceex");
price.value=price.value + '.$row["pprice"].'.toFixed(2);
}
I'm stuck! if you need anything else please leave a comment! Need this fixed as soon as I can, I'll keep trying in the mean time.
you can call value method on form elements only...other elements you need to get value using textContent method
for form elements
$("input").val();
for other elements
$("span").text()

In Javascript, when using an array.push method to add items to a list how do I get it to sort?

Edit: This is for use in PDF scripting. I use Acrobat pro but have been using Foxit as of late because it is much quicker than Acrobat.
Below is the exact script I have to add items to a dropdown list titled TalentList. The following is the script in a button titled "Add new Talent"
aray=[this.getField("TalentName").value];{aray.push(this.getField("TalentCost").value)}
var x = aray[0] + "," + aray[1];
this.getField("TalentList").insertItemAt(this.getField("TalentNa
me").value,x)
{this.getField("TalentName").value="";}
{this.getField("TalentCost").value="";}
{this.getField("TalentName1").value=" ";}
Where I have the fields TalentName and TalentCost and I input values into those then click the button to add them to the dropdown TalentList. The script works fine as is. But, the problem I am having is every time I add a new item it adds it to the top of the list and does not sort it when I want it to be sorted. Is there something I can add to the above script in the button to cause this to happen automatically every time?
Please note that I have the "Sort Items" box checked in the properties of the TalentList dropdown.
I believe I would use insertItemAt (as told by someone else) but I don't know the method or the correct parameter to use.
I think you are looking to sort the listbox on your PDF form? If so you could do it like this:
aray=[this.getField("TalentName").value];
aray.push(this.getField("TalentCost").value);
var x = aray[0] + "," + aray[1];
this.getField("TalentList").insertItemAt(this.getField("TalentName").value,x);
this.getField("TalentName").value="";
this.getField("TalentCost").value="";
count = this.getField("TalentList").numItems;
var l = this.getField("TalentList")
for (numsorted = 0; numsorted < count; numsorted ++){
max = l.getItemAt(numsorted, false)
maxindex = numsorted;
for (i=numsorted; i<count; i++){
item = l.getItemAt(i, false);
if (item > max) {
max = item;
maxindex = i;
}
}
item = l.getItemAt(maxindex, false);
l.deleteItemAt(maxindex);
l.insertItemAt(item, numsorted);
}

multiple conditions inside click function not working

With this code and chk1 and chk2 as 0, is impossible to me to guess what is wrong with this simple code function.
As i know, there are many js ways to use click, like ".click()", ".on('click')" or ".onClick" but none of them works at all. Take a look of this example:
regbtn.click(function() {
if(chk1 == 0){
if(chk2 == 1){
box2.reverse();
chk2 = 0;
}
box1.restart();
chk1 = 1;
}
});
logbtn.click(function() {
if(chk2 == 0){
if(chk1 == 1){
box1.reverse();
chk1 = 0;
}
box2.restart();
chk2 = 1;
}
});
Is there any reason why this doesnt work properly? and which way is the newest and best to use of this 3 ways of click js functions.
EDIT
regbtn and logbtn are 2 buttons that open 2 diferent boxes, box1 and box2 respectively, chk1 and chk2 is to check if the other box is open and reverse it first if so.
Alert doesnt work at all in any place.
This is the initial code variables to work with:
var regbox = document.getElementById("regbox"),
logbox = document.getElementById("logbox"),
regbtn = document.getElementById("regbtn"),
logbtn = document.getElementById("logbtn");
var chk1 = 0,
chk2 = 0;
You are trying to apply JQuery methods to DOM elements.
Try using JQuery selectors instead:
var regbox = $("#regbox"),
logbox = $("#logbox"),
regbtn = $("#regbtn"),
logbtn = $("#logbtn");
These return JQuery objects connected to the relevant DOM elements. The extensive (cross-browser) methods on JQuery object are what make it so powerful. If you find yourself using DOM elements directly that is often a sign of something that is less portable.

Sum a list of text boxes in jQuery

I have a form in which there are textbox(s) added dynamically using jquery.
The textbox ids is formed as an array, i.e. Quantity[0], Quantity[1], Quantity[2] ...
I want to add the numbers in these textbox(s) and display the value in another textbox named "total_quantity" preferably when the focus is shifted out of the array textbox.
How can I do it? I dont mind using jQuery or plain javascript, which ever is easier.
I would suggest giving a common class to your quantity fields such that:
<input type="text" class="quantity" onblur="calculateTotal();" />
Then you would be able to define the following function with jQuery:
function calculateTotal() {
var total = 0;
$(".quantity").each(function() {
if (!isNaN(this.value) && this.value.length != 0) {
total += parseFloat(this.value);
}
});
$("#total_quantity").val(total);
}
The onblur event will fire each time the focus is shifted from the quantity fields. In turn, this will call the calculateTotal() function.
If you prefer not to add a common class, you can use the $("input[id^='Quantity[']") selector, as Felix suggest in the comment below. This will match all the text boxes that have an id starting with: Quantity[
var Total = 0;
$("input[id^='Quantity[']").each(function() { Total += $(this).val()|0; });
$("#total_quantity").val(Total);
Use the following function, if one can't use document.getElementsByName(), as some MVC frameworks such as Struts and Spring MVC use the name attribute of a text to bind the element to a backend object.
function getInputTypesWithId(idValue) {
var inputs = document.getElementsByTagName("input");
var resultArray = new Array();
for ( var i = 0; i < inputs.length; i++) {
if(inputs[i].getAttribute("id") == idValue) {
resultArray.push(inputs[i]);
}
}
return resultArray;
}

Categories

Resources