Return value from function and use it - javascript

I'm trying to get a value from a function and then use it in other function but I'm not being able to do it...
the first function unidadesTotalCalculate fetches values from two inputs and then multiply them and prints it to an element.
This same function runs 3 times with different elements and then I need to to SUM the result of those three and print it to another element. This is second function, totalBarUpdateStandard().
Can you help me figuring out what is happening? I can't get the value from each function and use it.
function unidadesTotalCalculate(unidadeID, rangeID, print) {
var value = unidadeID.val();
var rangevalue = rangeID.val();
var valueSUM = value * rangevalue;
jQuery(print).text(valueSUM + '€');
return valueSUM;
}
function totalBarUpdateStandard() {
var value1 = unidadesTotalCalculate(jQuery('#doenteagudo-standard-dialise-unidades'), jQuery('#doenteagudo-standard-dialise-range'), '#doenteagudo-standard-dialise-total');
var value2 = unidadesTotalCalculate(jQuery('#doenteagudo-standard-plasma-unidades'), jQuery('#doenteagudo-standard-plasma-range'), '#doenteagudo-standard-plasma-total');
var value3 = unidadesTotalCalculate(jQuery('#doenteagudo-standard-plasmaferese-unidades'), jQuery('#doenteagudo-standard-plasmaferese-range'), '#doenteagudo-standard-plasmaferese-total');
var valueTotal = value1 + value2 + value3;
jQuery('#demo').text(valueTotal + '€');
}

Below is a your solution to your scenario, hope it helps you, I think jQuery(print).text(valueSUM + '€'); was the cause of your problem ... it should be jQuery(print).val(valueSUM + '€') .. just put it an static HTML and test it
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<input id="doenteagudo-standard-dialise-unidades" value="2" />
<input id="doenteagudo-standard-dialise-range" value="2"/>
<input id="doenteagudo-standard-dialise-total" />
<input id="doenteagudo-standard-plasma-unidades" value="2" />
<input id="doenteagudo-standard-plasma-range" value="2"/>
<input id="doenteagudo-standard-plasma-total" />
<input id="doenteagudo-standard-plasmaferese-unidades" value="2" />
<input id="doenteagudo-standard-plasmaferese-range" value="2" />
<input id="doenteagudo-standard-plasmaferese-total" />
<div id="demo"></div>
<button id="t"></button>
<script>
function unidadesTotalCalculate(unidadeID, rangeID, print) {
var value = unidadeID.val();
var rangevalue = rangeID.val();
var valueSUM = value * rangevalue;
jQuery(print).val(valueSUM + '€');
return valueSUM;
}
function totalBarUpdateStandard() {
var value1 = unidadesTotalCalculate(jQuery('#doenteagudo-standard-dialise-unidades'), jQuery('#doenteagudo-standard-dialise-range'), '#doenteagudo-standard-dialise-total');
var value2 = unidadesTotalCalculate(jQuery('#doenteagudo-standard-plasma-unidades'), jQuery('#doenteagudo-standard-plasma-range'), '#doenteagudo-standard-plasma-total');
var value3 = unidadesTotalCalculate(jQuery('#doenteagudo-standard-plasmaferese-unidades'), jQuery('#doenteagudo-standard-plasmaferese-range'), '#doenteagudo-standard-plasmaferese-total');
//console.log(value1);
//console.log(value2);
//console.log(value3);
var valueTotal = value1 + value2 + value3;
jQuery('#demo').text(valueTotal + '€');
}
</script>
</body>
</html>

you should use val() method of jQuery to get the value of the field.
Thanks

Related

I cannot connect javascript function with html <input> tags and onclick doesn't work

Hi I am working on a website and i stumbbled across an annoying thing. I cannot, for the love of anything, get to work my form to be able to do some maths and insert them into tag.
P.S nothing works for me, even GetElementsById... or other callouts :(
<script type="text/javascript">
function price(this.form){
var amount = form.elements[1].value;
var gold_price = 0.17;
var price_calc = 0;
price_calc = (amount/gold_price) + " M";
window.alert("price_calc");
form.elements[5].value = price_calc;
}
</script>
//this is input that i would like to get a number to work with in the function
<div>
<input type="text" id="amount" value="10" onchange="price(this.form)" onclick="price(this.form)" maxlength="4" required/>
</div>
//this is input I would like to write in in after function is done functioning :)
<input type="text" id="total_price" placeholder="Total:"/>
thanks for any help in advance.
thanks again,...
Declare your price function to receive an input parameter. Actually this.form as parameter is an invalid statement and leads to an error.
Instead pass this (inside your on* property) and select the input value.
// select #total_price
const totalPrice = document.getElementById( 'total_price' );
function price( input ) {
// Convert value to a number
var amount = +input.value;
var gold_price = 0.17;
var price_calc = 0;
price_calc = ( amount / gold_price ) + " M";
totalPrice.value = price_calc;
}
<input type="text" id="amount" value="10" oninput="price( this )" onclick="price( this )" maxlength="4" required/>
<br>
<input type="text" id="total_price" placeholder="Total:" />
This code working:
<input type="text" value="10" oninput="price(this)" maxlength="4" />
<input type="text" id="total_price" placeholder="Total:" />
<script>
function price(el){
var amount = parseInt(el.value);
var gold_price = 0.17;
var price_calc = (amount / gold_price) + " M";
window.alert("Total: " + price_calc);
document.getElementById('total_price').value = "Total: " + price_calc;
}
</script>

sum string with number onclick

I have a global variable :
var a;
I put my onclick function into my html div in concatenation PHP :
$number =' <div onclick="select(this,'."'250000'".');" > ';
$number .= ...etc... //php function
$number .='</div>';
to insert string into div value onclick (button) :
function select (price){
if ($(id).attr('class') == "table2") { //unselect button
$(id).attr('class', 'table1');
var price2=document.getElementById("price").value.split(",");
var removePrice = price;;
var price3 = jQuery.grep(price2, function (value) { return value != removePrice;});
document.getElementById("price").value = price3;
if (n.length == 0) i = 0;
} else {
$(id).attr('class', 'table2'); //select button
if (i == 0) {
document.getElementById("price").value = price;
a = Number(document.getElementById("price").value); //assign the value into a
i = 1;
} else {
$(id).attr('class','table3');
}
}
From there, I have checkbox HTML :
<div id="CourseMenu"><input type="checkbox" value="50000" />&nbsp Ekstra Bed <input type="checkbox" value="50000" />&nbsp Breakfast</div>
After that I have another function to sum 2 div value (checkbox) :
$(function($) {
var sum = 0;
$('#CourseMenu :checkbox').click(function() { sum = 0;
$('#CourseMenu :checkbox:checked').each(function(idx, elm) {
sum += parseInt(elm.value, 10);
});
var b = parseInt(a||0, 10) + parseInt(sum||0, 10);
$('#sum').html(b); //<--resulted NaN when sum with button
document.getElementById("price").value=b; //<-- assign b as div value
});
});
The purpose is to sum the total price (button & checkbox) into div value
<input type="hidden" id="price" name="price" value="" />
it works fine when the function sum only the checkbox, but when I try to show the sum with the button (global variable) it resulted in NaN
I think I already convert the string into number there, is there something wrong with my code?
I think you have a problem in passing the arguments in onclick event:
onclick="select(this,'250000');" => passing this as first argument try changing to onclick="select('250000')";
but your select function is expecting string as the first argument:
function select(price){ //<-- simplified
document.getElementById("price").value=price;
a = Number(document.getElementById("price").value);
}
Here is an actual solution for your X/Y problem.
The code will initialise the field and clicking buttons or checking checkboxes work independently.
function calc() {
var sum = parseInt($("#price").text(), 10);
$('#CourseMenu :checkbox:checked').each(function() {
sum += parseInt(this.value, 10);
});
$('#sum').val(sum);
}
$(function() {
$("#CourseMenu .btn").on("click", function() {
$("#price").text($(this).data("price")); // using the data attribute
calc();
});
$('#CourseMenu input:checkbox').on("click",function() {
calc(); //
});
calc(); // initialise in case the page is reloaded.
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="CourseMenu">
<button type="button" class="btn" data-price="25000">25000</button>
<button type="button" class="btn" data-price="35000">35000</button>
<div id="price">0</div>
<br/>
<label>
<input type="checkbox" value="200" />200</label>
<label>
<input type="checkbox" value="300" />300</label>
<label>
<input type="checkbox" value="400" />400</label>
<br/>
<input type="text" id="sum" value="" />
</form>
PS: If you do nothing else on click of checkboxes, you can write
$('#CourseMenu input:checkbox').on("click",calc);

Putting values into dynamically generated input types with JavaScript

I have Range/Number type inputs that are synchronized and dynamically generate input fields as much as their values.
Then I have a button that will fill the generated input fields with an arbitrary value.
The dynamically generated input fields each have unique IDs, but the document.getElementById() function fails to find any of the IDs and returns null.
Is there a way to change the value of the generated fields within the randomizeItemTypes() function?
function randomizeItemTypes(textbox) {
var rackNum = textbox.replace("itemSlider", "").replace("numOfTypes", "");
var numOfTypes = document.getElementById("numOfTypes1").value;
for (var i = 0; i < numOfTypes; i++) {
document.getElementById("rack" + rackNum + "." + i).value = 4;
}
}
The following link is the CodePen to my code:
http://codepen.io/cnc4ever/pen/LGNMEp
Thanks guys!
Your rackNum is giving some string instead of numbers
Your id for textbox is something like rack1.0 , rack1.1
use document.getElementById("rack1" + "." + i).value = 4; instead
<html>
<head>
<title></title>
</head>
<body>
<div class="itemsTypes1">
<input id="itemSlider1" type="range" value="" min="1" max="10" step="1" onchange="printValue(this.value);drawItemTypes('itemSlider1');" />
<input id="numOfTypes1" type="number" value="" min="1" max="10" onchange="printValue(this.value);drawItemTypes('numOfTypes1');" />
<p id="itemTypes1Area"></p>
<button id="randomize1" onclick="randomizeItemTypes()">Randomize</button>
</div>
<script type="text/javascript">
function printValue(data) {
var x = document.getElementById("itemSlider1").value = data;
var y = document.getElementById("numOfTypes1").value = data;
}
function randomizeItemTypes() {
var randomValue= Math.ceil(Math.random()*10);
printValue(randomValue);
}
</script>
</body>
</html>

How to get input value using class in prototype?

I did try but something is wrong I don't know what?
I'm trying to get value from input using a class
<script>
function showResult()
{
var val = $$(".qty")[0];
var val2 = val.innerHTML;
alert("Hey " +val2 );
}
</script>
<input class='qty' value="3"><br />
<input class='qty2' value="3">
<input type="button" value="Toggle" onclick="showResult();"/>
There is my example
I can get this value if I use div but for input doesn't work.
You have to change var val2 = val.innerHTML; to
var val2 = val.value;
DEMO
Use .value instead of .innerHTML.
var value = $$(".qty")[0].value;
alert("Hey " + value);
You're using jQuery, right? If so, try this:
<script>
function showResult(){
var val=$(".qty").val();
alert("Hey "+val);
}
function showTheSameResult(val){
alert("Hey "+val);
}
</script>
On the page:
<div class="qty" onclick="showTheSameResult(value);">
<!--- stuff -->
</div>

What's the best way to update the input names when dynamically adding them to a form?

I'm trynig to come up with a clean and efficient way of handling form input names when dynamically adding more to the POST array.
For example, if I have the following form:
<fieldset>
<input type="text" name="users-0.firstname" />
<input type="text" name="users-0.lastname" />
</fieldset>
I then click an 'addmore' button which duplicates that HTML and adds it back into the document. Resulting in:
<fieldset>
<input type="text" name="users-0.firstname" />
<input type="text" name="users-0.lastname" />
</fieldset>
I'm trying to find the best way to increment that name index so I can use the data on the server. So far, I've been using the following code:
$('.addmore').click(function()
{
var $button = $(this);
var $fieldset = $button.prev('fieldset');
var $newset = $('<div class="new">' + $fieldset[0].innerHTML + '</div>');
$newset.insertBefore($button);
updatenames($newset, $('fieldset').length + 1);
});
function updatenames($set, newIndex)
{
/*
updates input names in the form of
set-index.name
set-index
*/
var findnametype = function(inputname)
{
if (inputname.indexOf('-') != -1 && inputname.indexOf('.') != -1)
{
var data1 = inputname.split('-');
var data2 = data1[1].split('.');
// [type, set, index]
return [1, data1[0], parseInt(data2[0])]
}
if (inputname.indexOf('-') != -1 && inputname.indexOf('.') == -1)
{
var data = inputname.split('-');
return [2, data[0], data[1]];
}
return false;
};
var type = findnametype($set.find('input:eq(0)')[0].name);
$set.find('input, select').each(function()
{
var $input = $(this);
var oldname = $input[0].name;
var newname = false;
switch (type[0])
{
case 1: newname = oldname.replace('-' + type[2], '-' + newIndex);
break;
case 2: newname = oldname.replace('-' + type[2], '-' + newIndex);
break;
}
$input[0].name = newname;
});
return type;
}
That updatenames function is a variation of what I've been using lately. In this case, I check to find the format of the input name. I then increment the index.
The incrementing, as you've probably noticed, happens in the DOM. As a 'part 2' to my question, I'd like to learn how to have that object returned for me to then insert into the DOM.
Something like:
$newset = updatenames($newset, $('fieldset').length +1);
$newset.insertBefore($button);
Your help is appreciated. Cheers.
Have you considered using array-based field names? You wouldn't have to alter those at all:
<input type="text" name="users.firstname[]" />
<input type="text" name="users.lastname[]" />
whether this works for you will of course depend on what you're going to do with the fields.
<script type="text/javascript">
$(document).ready(function () {
$('.addmore').click(function () {
var fieldset = $(this).prev('fieldset');
var newFieldset = fieldset.clone();
incrementFieldset(newFieldset);
newFieldset.insertBefore($(this));
});
});
function incrementFieldset(set) {
$(set).find('input').each(function () {
var oldName = $(this).attr('name');
var regex = /^(.*)-([0-9]+)\.(.*)$/;
var match = regex.exec(oldName);
var newName = match[1] + '-' + (parseInt(match[2]) + 1) + '.' + match[3];
$(this).attr('name', newName);
});
}
</script>
<fieldset>
<input type="text" name="users-0.firstname" />
<input type="text" name="users-0.lastname" />
</fieldset>
<input type="button" class="addmore" value="Add" />
<fieldset>
<input index=1 var=user prop=firstname />
<input index=1 var=user prop=lastname />
</fieldset>
<fieldset>
<input index=2 var=user prop=firstname />
<input index=2 var=user prop=lastname />
</fieldset>
before you submit your form
get the custom attributes and construct your 'name' attribute
[update]
its jsp but shouldn't be hard for u to convert to php
<%
for (int i = 0; i < 1000; i++) {
%>
<fieldset>
<input index=<%=i%> var=user prop=firstname />
<input index=<%=i%> var=user prop=lastname />
</fieldset>
<%
}
%>
for the js code
$('button').click(function(){
$('input').each(function(i, node){
var $node = $(node);
$node.attr('name', $node.attr('var') + $node.attr('index') + "."+ $node.attr('prop'))
});
});

Categories

Resources