How to use data value to refer back to another variable - javascript

I'm trying to use create a converter by using the data attribute to refer back to a previous value.
I cannot seem to get:
data-my_currency to refer back to 301.46
data-this to refer back to 4259.00
$('input').keyup(function() {
var BTC = 4259.00
var ETH = 301.46
var LTC = 67.72
var USD = 1
var EUR = 0.83
var CNY = 6.46
var convertFrom = $('.js').data('my_currency');
//Should refer back to EUR var
var convertTO = $('.js').data('this');
//Should refer back to BTC var
var amount = $('input').val();
var result = convertFrom * convertTO * amount;
var newresult = result.toFixed(2);
$('.output').html(newresult);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="js" data-my_currency="EUR"></div>
<div class="js" data-this="BTC"></div>
<input type="text" class="input" />
<div class="output">Me</div>

Alternatively and without changing your existing code much, you can declare your variables at global scope (which you should avoid) and use window object to get the value of the variable.
var BTC = 4259.00
var ETH = 301.46
var LTC = 67.72
var USD = 1
var EUR = 0.83
var CNY = 6.46
$(document).ready(function () {
$('input').keyup(function () {
var convertFrom = $('[data-my_currency]').data('my_currency');
var convertTO = $('[data-this]').data('this');
var amount = $('input').val(); //Assuming user enters only numbers
var result = window[convertFrom] * window[convertTO] * amount;
var newresult = result.toFixed(2);
$('.output').html(newresult);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="js" data-my_currency="EUR"></div>
<div class="js" data-this="BTC"></div>
<input type="text" class="input" />
<div class="output">Me</div>

If you are attempting to make them refer back to the JavaScript variables, why not simply use those JavaScript variables directly?
If, however, you have your Bitcoin and currency prices written as an element in the page (which is what I assume is the case), you're looking for $('.js[data-my_currency]')[0].innerHTML and $('.js[data-this]')[0].innerHTML respectively.
Breaking this down:
.js targets the class js
[data-my_currency] targets the attribute data-my_currency
$('.js[data-my_currency]') returns a nodeList
[0] grabs the first node
.innerHTML grabs the content inside of that node.
$('input').keyup(function() {
var convertFrom = $('.js[data-my_currency]')[0].innerHTML;
var convertTO = $('.js[data-this]')[0].innerHTML;
var amount = $('input').val();
var result = convertFrom * convertTO * amount;
var newresult = result.toFixed(2);
$('.output').html(newresult);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="js" data-my_currency="EUR">0.83</div>
<div class="js" data-this="BTC">4259.00</div>
<input type="text" class="input" />
<div class="output">Me</div>
Hope this helps! :)

Related

How can i insert javascript variable in value dynamically?

this is the value in my input field
value="CODES-{{ date("Ym_M") }}-PRJ-PONUMBER-SHORTTEXT"
i have this variable in javascript
var codes = PC123; this is dynamic
var ponumber = 4124;this is dynamic
var shorttext = 001; this is dynamic
I want a result of:
//PC123-202105_May-PRJ-4124-001
thanks in advance guys.
Keep the date in a data-* attribute and then use javascript to set the input.
<input id="myInput" type="text" data-date="{{ date('Ym_M') }}">
var input = document.getElementById('myInput'); // or $('#myInput'); in JQuery
var codes = 'PC123';
var date = input.dataset.date; // or $('#myInput').data('date'); in JQuery
var ponumber = '4124';
var shorttext = '001';
input.value = `${codes}-${date}-PRJ-${ponumber}-${shorttext}`; // or $('#myInput').val(`${codes} .... `); in JQuery

Jquery append Concatenation onclick

I am trying to pass two variables one is having integer and other is having some string,say i want to pass id,name
<div class='redstatus' onclick='redStatus("+Id+","+name+")'><span class='countspan''>"+red_count+"</span></div>
In the above code in onclick function if i pass only id <div class='redstatus' onclick='redStatus("+Id+")'><span class='countspan''>"+red_count+"</span></div> it is working fine.
I want to send one more parameter name along with id separated by comma
<div class='redstatus' onclick='redStatus("+Id+","+name+")'><span class='countspan''>"+red_count+"</span></div>
it is not working.I need help on this.
for(var i in appData ){
console.log("Data"+JSON.stringify(appData));
for(j in appData.LOB){
var LOBId = appData.LOB[j].LOBID;
LOBName = appData.LOB[j].LOBName;
var LOBRef = appData.LOB[j].LOBRef;
var LOBNameRef = appData.LOB[j].LOBNameRef;
//console.log("LOBId"+LOBId+"LOBName"+LOBName);
$(".left_div").append("<div class='left_lob_name'>"+LOBName+"</div>");
streamInRed = [];
streamInAmber = [];
streamInGreen = [];
currentItemRed = [LOBId];
currentItemAmber = [LOBId];
currentItemGreen = [LOBId];
//$("."+LOBNameRef+"").append("<div id="+LOBId+" style='height:74vh;overflow-y:auto;'><table class='table table-bordered' ><thead><tr><th>StreamName</th><th>BusinessSLA Description</th><th>Status</th><th>Business SLA</th><th>Forecast Completion Time</th><th>Actual Completion Time</th><th>JobName</th></tr></thead><tbody class='"+LOBRef+"'></tbody></table></div>");
for(var k in appData.LOB[j].Streams.Stream){
//console.log("Streams"+JSON.stringify(appData.LOB[j].Streams.Stream));
var streamId = appData.LOB[j].Streams.Stream[k].streamId;
var streamName = appData.LOB[j].Streams.Stream[k].streamName;
var Status = appData.LOB[j].Streams.Stream[k].Status;
var jobName = appData.LOB[j].Streams.Stream[k].JobName;
var BSD= appData.LOB[j].Streams.Stream[k].BusinessSLADescrition;
var BSLA = appData.LOB[j].Streams.Stream[k].BusinessSLA;
var FCT = appData.LOB[j].Streams.Stream[k].ForecastCompletionTime;
var ACT = appData.LOB[j].Streams.Stream[k].ActualCompletionTime;
var RAGStatus = appData.LOB[j].Streams.Stream[k].RAGStatus;
if(Status == "red"){
//$("."+LOBName+"").append("<div class='streamcolor_red test' data-name='1'>"+streamName+"</div>");
//$("."+LOBRef+"").append("<tr class='test' data-name='1'><td style='background-color:#f3180d;color:#fff;'>"+streamName+"</td><td>"+BSD+"</td><td>"+RAGStatus+"</td><td>"+BSLA+"</td><td>"+FCT+"</td><td>"+ACT+"</td><td>"+jobName+"</td></tr>");
red_count = red_count+1;
currentItemRed = [streamName,BSD,RAGStatus,BSLA,FCT,ACT,jobName];
streamInRed.push(currentItemRed);
//redStatus();
//console.log("streamInRed"+streamInRed);
}else if(Status == "amber"){
//$("."+LOBRef+"").append("<tr class='test' data-name='2'><td style='background-color:rgba(243, 168, 15, 0.9215686274509803);color:#fff;'>"+streamName+"</td><td>"+BSD+"</td><td>"+RAGStatus+"</td><td>"+BSLA+"</td><td>"+FCT+"</td><td>"+ACT+"</td><td>"+jobName+"</td></tr>");
//$("."+LOBName+"").append("<div class='streamcolor_amber test' data-name='2'>"+streamName+"</div>");
amber_count = amber_count+1;
currentItemAmber = [streamName,BSD,RAGStatus,BSLA,FCT,ACT,jobName];
streamInAmber.push(currentItemAmber);
}else {
//$("."+LOBRef+"").append("<tr class='test' data-name='3'><td style='background-color:green;color:#fff;'>"+streamName+"</td><td>"+BSD+"</td><td>"+RAGStatus+"</td><td>"+BSLA+"</td><td>"+FCT+"</td><td>"+ACT+"</td><td>"+jobName+"</td></tr>");
//$("."+LOBName+"").append("<div class='streamcolor_green test' data-name='3'>"+streamName+"</div>");
green_count = green_count+1;
currentItemGreen=[streamName,BSD,RAGStatus,BSLA,FCT,ACT,jobName];
streamInGreen.push(currentItemGreen);
}
//console.log("streamId"+streamId+"streamName"+streamName+"Status"+Status);
}
console.log("LOBId",LOBId);
console.log("sep_symbol",sep_symbol);
console.log("syb",syb);
console.log("LOBNameRef",LOBNameRef);
var tempvar = "'"+LOBNameRef+"'";
console.log("tempvar"+LOBId +sep_symbol +tempvar);
$("<div style='text-align:center;height:5vh;margin:2vw;'> <div class='redstatus' onclick='redStatus("+LOBId+","+LOBNameRef+")'><span class='countspan''>"+red_count+"</span></div> <div class='amberstatus' onclick='amberStatus("+LOBId+")'><span class='countspan'>"+amber_count+"</span></div> <div class='greenstatus' onclick='greenStatus("+LOBId+")'><span class='countspan'>"+green_count+"</span></div></div>").appendTo(".right_div");
red_count = 0;
amber_count = 0;
green_count = 0;
//var Streams = appData.LOB[j].Streams;
//console.log("Before"+$wrapper);
//var $wrapper = $('.'+LOBRef+'');
//console.log("after"+$wrapper);
//$wrapper.find('.test').sort(function (a, b) {
/// return +a.dataset.name - +b.dataset.name;
//})
//.appendTo( $wrapper );
}
}
i have added the code for your reference
The problem is with the line
$("<div style='text-align:center;height:5vh;margin:2vw;'> <div class='redstatus' onclick='redStatus("+LOBId+","+LOBNameRef+")'><span class='countspan''>"+red_count+"</span></div> <div class='amberstatus' onclick='amberStatus("+LOBId+")'><span class='countspan'>"+amber_count+"</span></div> <div class='greenstatus' onclick='greenStatus("+LOBId+")'><span class='countspan'>"+green_count+"</span></div></div>").appendTo(".right_div");
which, more prettily, and without the inline handlers, can be constructed like:
const htmlStr = `
<div style='text-align:center;height:5vh;margin:2vw;'>
<div class='redstatus'><span class='countspan'>${red_count}</span></div>
<div class='amberstatus'><span class='countspan'>${amber_count}</span></div>
<div class='greenstatus'><span class='countspan'>${green_count}</span></div>
</div>
`;
You can pass the HTML string to jQuery to get a jQuery collection, then select the inner divs and add a listener to each:
const $row = $(htmlStr);
$row.find('.redstatus').on('click', () => redStatus(LOBId, LOBNameRef));
$row.find('.amberstatus').on('click', () => amberStatus(LOBId, LOBNameRef));
$row.find('.greenstatus').on('click', () => greenStatus(LOBId, LOBNameRef));
$row.appendTo(".right_div");
(or pass whatever parameters you want to the status functions - no quote escaping required!)
Make sure the LOBIds and LOBNameRefs don't reassign themselves in other iterations of the loop - declare them with const, eg:
const LOBId = appData.LOB[j].LOBID;
const LOBName = appData.LOB[j].LOBName;
const LOBRef = appData.LOB[j].LOBRef;
so they're scoped to the block, not to the function.
(It would also probably be good to have just a single <color>Status function, rather than three separate standalone functions (which probably all do something somewhat similar) - too much repetition should be avoided)
You want to concatenate two parameters passed to a function, do not enclose variables in single or double quotes, it should be as :onclick="redStatus(Id,name)"
function redStatus(Id,name){
var result = Id+'_'+name;
document.getElementsByClassName('countspan')[0].innerText = result;
}
<!DOCTYPE html>
<html>
<head>
<title>Append Two Params</title>
</head>
<body>
<div onclick="redStatus(1,'name')">Append Two Params</div>
<span class='countspan'></span>
</body>
</html>

Issues with javascript using html inputs as variables (Beginner!)

Hello Everyone!
Im having some issues with a simple calculator type website. My issue involves using a javascript function to calculate an equation using variables from an HTML input form.
Below is my javascript function, which is placed above the form in the HTML file.
var userName = document.getElementsByName("userName")[0].value;
var userMmr = document.getElementsByName("userMmr")[0].value;
var userDesmmr = document.getElementsByName("userDesmmr")[0].value;
var userWinrate = document.getElementsByName("userWinrate")[0].value;
function findshit(){
alert(userMmr.value);
var LR = 1.0 - userWinrate.value;
var GP = 1;
while (1){
var GW = GP * userWinrate.value;
var GL = GP * LR;
var MMRG = GW * 25;
var MMRL = GL * 25;
var TMG = MMRG - MMRL;
if (TMG + userMmr.value >= userDesmmr.value) {
alert("Congrats! it will take you " + String(GP));
} else {
GP += 1;
}
}
}
<h2>Enter your information below</h2>
</br>
<form>
What's your name?:<br>
<input type="text" name="userName" onkeyup="findshit();" onchange="findshit();"/><br>
</br>
What's your current mmr?:<br>
<input type="text" name="userMmr" onkeyup="findshit();" onchange="findshit();"/><br>
</br>
What's your desired mmr?:<br>
<input type="text" name="userDesmmr" onkeyup="findshit();" onchange="findshit();"/><br>
</br>
What's your current win rate?<br>(put in decimal form eg. 50% = .50):<br>
<input type="text" name="userWinrate" onkeyup="findshit();" onchange="findshit();"/"><br>
<br>
<button onclick="findshit();">Try it</button>
Don't use .value when you set all the variables at the top. The code in the function expects those variables to just be the elements, because it uses .value to get their updated values. So it should just be:
var userName = document.getElementsByName("userName")[0];
var userMmr = document.getElementsByName("userMmr")[0];
var userDesmmr = document.getElementsByName("userDesmmr")[0];
var userWinrate = document.getElementsByName("userWinrate")[0];
You also need to put the script after the HTML, or put all the code inside the window.onload function. If you run the script before the HTML is loaded, none of the document.getElementsByName() calls will find the elements.
You should remove or modify while (1) loop. Because it is an infinite loop. I think you should use If loop in the scenario.

how do i output a variable from js for html

Please I want to output a variable from js to an html tag so i can see the results in a specific place on my page. here is the code:
<script type="text/javascript">
function doMath()
{
// Capture the entered values of two input boxes
var my_input1 = document.getElementById('my_input1').value;
var my_input2 = document.getElementById('my_input2').value;
var my_input3 = document.getElementById("my_input3").value;
var my_input4 = document.getElementById("my_input4").value;
//alert(form.elements["my_input2"].value);
//var my_input3 = document.getElementById('my_input3').value;
// Add them together and display
var sum = parseInt(my_input1) / parseInt(my_input2) * parseInt(my_input3) * parseInt(my_input4);
document.write(sum);
}
Let us say you want to display the response in a div with id sum
<div id="sum"></div>
To do so, update
document.write(sum);
to
document.getElementById("sum").innerHTML = sum;

Getting values from list<String> , split them and then slice them by parts, using JavaScript

I have List<String> from Spring MVC which i want to split, slice and print on browser. The problem is that i need to enter a start and end argument of slice() method as a variable from text-field. This is my code, but it doesn't work. Can someone helps me with that? This is my code:
<body>
<form>First value:
<br/>
<input type="text" id="firstvalue" />Last value:
<br/>
<input type="text" id="lastvalue" />
<button onclick="myFunction()">Press</button>
<p id="demos"></p>
</form>
<script>
function myFunction() {
var str = "${first}";
var arr = str.split(",");
var first = document.getElementById('firstvalue');
var second = document.getElementById('lastvalue');
document.getElementById("demos").innerHTML = arr.slice('first', 'second');
}
</script>
</body>
Thank you in advance!
you got some issues in your code.
if ${first} is List<String>, then you need to convert it to a concatenated single comma separated String. Because by ${first} you are just printing list object.
slice expects index which is number, you are passing String
You are not doing .value after document.getElementById
You are not passing the user input variables first and second to slice, Instead you are passing hardcoded strings 'first' and 'second'.
Below is the fixed code
HTML
<form>First value:
<br/>
<input type="text" id="firstvalue" />Last value:
<br/>
<input type="text" id="lastvalue" />
<button onclick="myFunction(event)">Press</button>
<p id="demos"></p>
</form>
JS
var myFunction = function (e) {
var str = "${first}" // assuming this contains string like "1,2,3,4,5,6,7,8,9,10"; and not the List obect
var arr = str.split(",");
var first = document.getElementById('firstvalue').value;
var second = document.getElementById('lastvalue').value;
document.getElementById("demos").innerHTML = arr.slice(parseInt(first, 10), parseInt(second, 10)).toString();
e.preventDefault();
};
What do we want to achieve?
We have two input textfields: one holding a start value and one holding an end value. On a click we want to create a range from the start to the end value and output it into a container.
Solution
The solution is more simple than expected and we do not require split, slice and part. Also we do not really require a predefined list holding all values.
Example
<html>
<head>
<script>
function evalRange(){
var tS = parseInt(document.querySelector('#inFrom').value); //Our start value;
var tE = parseInt(document.querySelector('#inTo').value); //Our end value;
var tR = document.querySelector('#demos'); //Our output div
if (tE >= tS){
//We are using the Array.apply prototype to create a range
var tL = Array.apply(null, Array(tE - tS + 1)).map(function (a, i){return tS + i});
//We output the range into the demos div
tR.innerHTML = tL.join(',')
}
else tR.innerHTML = 'To has to be higher than from';
//Returning the range list
return tL
}
</script>
</head>
<body>
<input type = 'text' id = 'inFrom' value = '10' />
<input type = 'text' id = 'inTo' value = '20' />
<b onclick = 'evalRange()'>Range</b>
<div id = 'demos'></div>
</body>
</html>
And here is a fiddle for it: https://jsfiddle.net/91v3jg66/

Categories

Resources