Change textbox value in javascript - javascript

I want to update the value of text box from where I'm getting initial value to add product to cart.
Now I'm applying round function & I want to update the value of text box that is because I'm using ajax & if I'm applying round function, user must know how system calculated everything.
Here's my simple code:
<script>
$(document).ready(function(){
$(document).delegate('.purchasenow','click', function(e){
var buynow=this;
var productid = $(this).attr('id');
var quantity = $('.quo_'+productid).val();
var quantity = Math.round(quantity);
alert(quantity); //This gives the value
$('.quo_'+productid).value = quantity; //This is not working
});
});
Can anyone tell why it's not working? It's very simple but I'm not able to find out the cause.

Have you tried
$('.quo_'+productid).val(quantity);
The jQuery selector returns a wrapped object, not the actual DOM element. I don't think wrapped object has the .value property

you are almost correct the only thing why it is not working because your syntax is wrong
this is the correct syntax for jQuery
$('.quo_'+productid).val(quantity);
if you want it in javascript
var txt = document.getElementById("quo_"+productid);
txt.value = quantity;

Related

JS Function calling displaying odd text & not working more than once

I have a problem, when I run my function "addMoney(amount)" (shown below) it works and shows the following: 100[object HTMLButtonElement]
My question is this, is there a way to get rid of the [object HTMLButtonElement] while keeping the number from moneyAmount when the function is called? And additionally, is there a way to call the function multiple times and add the money accordingly? As it only works the first time I call it, calling it more than once with the same or different amounts of moneyAmount displays no more or no less than what displays the first time.
My HTML:
<li class="item_shown" id="money">Shrill: <button class="moneyButton" id="moneyAmount">0</button></li>
Calling the function in HTML:
<a class="button" onclick="javascript:addMoney('100');">Add 100 Money</a>
My JS Function:
function addMoney(amount) {
document.getElementById('moneyAmount')
var newBalance = amount + moneyAmount;
document.getElementById('moneyAmount').innerHTML = newBalance;
}
The text inside an element is considered to be a text node and since the button node has no other children, is the button node's first child. The text node's value (in this case "0") is the value of its nodeValue property. Assigning a new value to the nodeValue will change the text displayed. So in your case the following code should work:
function addMoney(amount) {
var node = document.getElementById('moneyAmount');
var textNode = node.childNodes[0];
var moneyAmount = parseInt(textNode.nodeValue, 10);
textNode.nodeValue = amount + moneyAmount;}
In your JavaScript, + moneyAmount; does not do anything. It returns what you see: [object HTMLButtonElement].
I think you want to add some numbers but it's not yet completely clear to me what you're trying to achieve. Could you elaborate?
Chris
EDIT:
Thank you for clarifying your question.
Try updating your function like this:
function addMoney(amount) {
var oldBalance = document.getElementById('moneyAmount').value;
var newBalance = amount + oldBalance;
document.getElementById('moneyAmount').innerHTML = newBalance;
}
Try to find value by document.getElementById('moneyAmount').innerHTML and use some global variable say total_value to store retrieved value and then for each function call try to add the retrieved value to the previously stored value.

Adding "values" to a texfield in jquery/js

When writing a new email, I've got a modal(pop-up window in boostrap) that shows a list of contacts. When I select (through checkboxes) a couple of contacts, the selected ones are written into a checkbox. Problem is I'm just writing the lastone I select instead of all of the selected ones.
If you need further explanation please ask. (Sorry for my english)
$("#tblContacto").on("click", ".ck", function(event){
if($(".ck").is(':checked')) {
selected_index = parseInt($(this).attr("alt").replace("Check", ""));
var contacto = JSON.parse(tbContactos[selected_index]);
$("#txtDestinatarios").val(contacto.Email);
} else {
$("#txtDestinatarios").val("");
}
});
Assuming that you want to add all E-Mails into a textfield with id txtDestinatariosthe cause of your Problem is the usage of the $("#txtDestinatarios").val(); function.
Calling val() with an argument sets (and thus overwrites) the value within the textfield. (See demo at http://api.jquery.com/val/#val2)
You would have to first retrieve the value of the textfield using code like var currentValue = $("#txtDestinatarios").val() and then add/remove the E-Mail from/to the string before setting the resulting string back as the value.
If you want to set all selected items in the checkboxes into Textfiled you can use the following line of code :-
$("#txtDestinatarios").val( $("#txtDestinatarios").val()+ ","+contacto.Email);

How can I use Javascript to get the value of an element that was populated by a POST request?

I'm building an HTML page that receives data from another page with the below code
$arrayPosition = $_POST['arrayPosition'];
echo '<span id = "arrayPosition">'.$arrayPosition.'</span>';
I'm then trying to use javascript to get the value of the element and pass it to a function with the below code
var initialPosition = document.getElementById('arrayPosition').value;
function displayWork(position){
$("#displayArtwork").detach()
.append(holdImages[position])
.hide()
.fadeIn("fast");
}
When I alert the value of initial position to the screen it informs me that null is its value, however, when I inspect the element it looks like this
<span id="arrayPosition">4</span>
Am I making some really stupid error, or misunderstanding the way to access this posted data?
Thanks for your help!
Since arrayPosition is a span, it has no value. You can get its innerHTML:
var initialPosition = document.getElementById('arrayPosition').innerHTML;
Or using jQuery:
var initialPosition = $('#arrayPosition').text();
A span-element has no value. Only form-elements can contain the value-attribute. To get the text inside your span you can use the innerHTML-porperty:
var initialPosition = document.getElementById('arrayPosition').innerHTML;
Demo
As you are already using jQuery you can also use it's text()-function:
var initialPosition = $('#arrayPosition').text();
here you can also use:
$(document.getElementById('arrayPosition')).text();
Harder to maintain and more difficult to read but faster than the jQuery-Selector. (see here)
Demo 2
Reference
.innerHTML
.text()

Trying to use Jquery/javascript to calculate form fields

Im having a terrible time trying to calculate the value of two form fields. I'm constantly getting "NAN" which would indicate non-numeric input, this is despite the fact that the form fields are only populated with numbers.
In response I tried to use ParseInt to get a numeric value. This also fails to yield a successful result.
This is what I have so far. Any help is appreciated.
$('#value-calc input').change(function () {
var valueINT = parseInt($('#value'),10);
var quantINT = parseInt($('#quantity'), 10);
var math = ((valueINT/quantINT)*1000);
$('#cpm').val(math);
});
http://jsfiddle.net/greyoxide/YRWAA/1/
You need to add the .val() method after your selectors to get the value they hold
working fiddle
You're not passing in strings when you refer to elements by ID with that jQuery.
Perhaps try $('#value').val() in the parseInt methods instead.
Try this:
$('#value-calc input').keyup(function () {
var valueINT = $('#value').val();
var quantINT = $('#quantity').val();
var math = ((valueINT/quantINT)*1000);
$('#cpm').val(math);
});

Cloned row requesting same function [duplicate]

This question already exists:
Closed 10 years ago.
Possible Duplicate:
Call same function by a cloned list row
I am trying to make a simple calculation to work.
I have the following running:
http://jsfiddle.net/vSyK6/41/
Basically, the way it works now is this:
When you select an option on the drop down list it will display the content based on the option selected. Then when you select the same option again it will add, basically clone the same row.
Now, when the second option is selected "Option2" it will display an empty textbox. When you enter a number it will or should call the a function where we make a basic calculation. The function is already in the script.
However, when we have two empty textboxes it should call the same calculation function but calculate seperately and puts it in a different div. The div# where we display the amount is a called "amount"
Basically, it should work like this:
First Empty textbox -> 100 -> 100 * 22.38 = display result in div#1
Second Empty textbox -> 230 -> 230 * 22.38 = display in div#2
any idea on how to accomplish that ?
When cloning elements the id is cloned as well. It is best practice to create a new ID for the cloned elements, which will also help in accomplishing what you want. The same goes for the name attribute as well.
With a few modification to your code, http://jsfiddle.net/dNQVQ/3/, I was able to get what you were after. Let me first say that this might not be the ideal way to go, but it is a start. Like I said earlier the key is going to be setting unique ids for the cloned elements. What I did in this example was use a index as part of the list element id that is cloned with a matching index in an 'amount' div. This way when an input is updated the index is retrieved and then used to update the appropriate div. Additionally, I moved the function that did the calculation and updates to an anonymous function in the settimeout call. This makes it easy to use a reference to the updated input in the function call.
Joining the party quite late here :) Here is one vernon: http://jsfiddle.net/KVPwm/
ALso if its assignment bruv, put an assignment homework tag!
People around SO community are awesome folks so be truthful, guys will help man!
Use .on instead of live - recommendation. i.e. upgrade your JQ source if keen read this - What's wrong with the jQuery live method?
you have 2 document.ready functions also I chained few things for you.
Also think of using isNan check as well.
Rest you can read the code and play around a bit to make it more concise.
I have added 2 divs and using the id number to populate the stuff accordingly.
This should fit the cause :)
code
$("document").ready(function() {
/////////////////////////////////CALUCATIONS/////////////////////////////////
//setup before functions
var typingTimer; //timer identifier
var doneTypingInterval = 0; //time in ms, 5 second for example
$('input[name=Input2], input[name=Input1]').live('keyup', function() {
var str = $(this).prop("id");
var pattern = /[0-9]+/g;
var matches = str.match(pattern);
amount = parseFloat($(this).val()) * 22.38;
typingTimer = setTimeout(doneTyping(matches), doneTypingInterval);
});
$('#Input2').keydown(function() {
clearTimeout(typingTimer);
});
function doneTyping(matches) {
$('#amount'+matches).text(amount.toFixed(2) + " lbs");
}
$("#List-Option1,#List-Option2").hide();
$('#category').change(function() {
var str = $('#category').val();
if (str == 'Option1') {
var option1 = $("#List-Option1:first").clone().show();
$('#box li:last').after(option1);
}
if (str == 'Option2') {
var option2 = $("#List-Option2:first").clone().show();
$('#box li:last').after(option2);
}
});
});​

Categories

Resources