Manipulate value dynamically (onchange) from span to input? - javascript

I am developing a form which has an input called "net worth" and I have an embedded widget below this input which you can choose your currency and insert your budget and it would convert it to your desired currency. it looks like this:
You can check online the widget here.
So I want whenever the result changes (onChange) my input field value changes too. The result is in the span with #result-fit ID and my input box is #netWorthValue ,
I have searched a lot and try some best practice but still, I can not figure it out. The most relevent question in Stackoverflow was this question but it couldn't help me unfortunately, I have tested this code and it didn't retrieve the value from span (maybe because it is inside an embedded form?)
var value = $("#result-fit").text();
var lower = $("#netWorthValue").val(value);
alert(lower.val());
var value = $("#result-fit").text();
var lower = $("#netWorthValue").val(value);
alert(lower.val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<p>Your personal net worth</p>
<div class="input-group">
<label>Amount in CDN (Canadian dollar):</label> <input type="number" class="form-control" name="netWorth" title="networth" id="netWorthValue">
<!-- START CODE Attention! Do not modify this code; -->
<script>
var fm = "EUR";
var to = "CAD";
var tz = "timezone";
var sz = "1x1";
var lg = "en";
var st = "info";
var lr = "0";
var rd = "0";
</script>
<a href="https://currencyrate.today/converter-widget" title="Currency Converter">
<script src="//currencyrate.today/converter"></script>
</a>
</div>

Listen for changes to the input and write to the '#result-fit' span.
$(document).ready(function(){
$("#result-fit").on("change", function(e){
$("#netWorthValue").text($(this).val());
})
})

Related

update a HTML input field with the data coming from a external Javascript Websocket

I am new to JavaScript, not sure if this very basic question. I've created a Bitcoin Price update dashboard using the data fetched from the external WebSocket. I managed to get the data from the WebSocket and display it on the console tab and display the data in a h1 tag. The price updates every seconds. Now i need to show the price in a html field. i tried but it's kinda hard for me.
I have provided the code snippets below as well as external Websocket from where I am pulling the data.
Please let me know how should I insert the row dynamically into a HTML input field. Thank you so much in advance
<input type="text" class="form-control" id="btcpricenow" readonly>
<script>
var priceSocket = new WebSocket("wss://stream.binance.com:9443/ws/btcusdt#trade"),
liveprice = document.getElementById("btcpricenow");
priceSocket.onmessage = function (event) {
var liveprice = JSON.parse(event.data);
liveprice.innerText = parseFloat(liveprice.p).toFixed(2);
}
</script>
You set liveprice to be the HTML element, and then reset it inside your function to be the parsed event.data. Don't reset the variable like that, just set a new variable instead. Also, when you are putting a value inside an input element use value, not innerHTML
<input type="text" class="form-control" id="btcpricenow" readonly>
<script>
let priceSocket = new WebSocket("wss://stream.binance.com:9443/ws/btcusdt#trade"),
liveprice = document.getElementById("btcpricenow");
priceSocket.onmessage = function(event) {
let data = JSON.parse(event.data);
liveprice.value = parseFloat(data.p).toFixed(2);
}
</script>
use this :
const data= JSON.parse(event.data);
let liveprice = document.getElementById("btcpricenow");
liveprice.value = parseFloat(data.p).toFixed(2) || "";

JS - Calculate values depending on selected dropdowns

So I have this calculator for money that shows you the amount you enter but in a different money value. (Example dollar to euro)
Here is the HTML:
<b> Exchange money </b> <br> <br>
Enter amount for RSD: <input type="number" name="nbsAmount" id="nbsAmount" size="5"> <br>
<button class="dugme">Calculate</button> <br> <br>
Evro value is: <div class="konacnaEvroVrednost"></div>
Dolar value is: <div class="konacnaDolarVrednost"></div>
Swiss value is: <div class="konacnaSwissrednost"></div>
And here is the JS:
$('.dugme').click(function(){
var broj = document.getElementById('nbsAmount').value;
var evro = broj * 0.0085;
var dolar = broj * 0.0095;
var frank = broj * 0.0096;
$('.konacnaEvroVrednost').text(evro + ' €');
$('.konacnaDolarVrednost').text(dolar + ' $');
$('.konacnaSwissrednost').text(frank + ' Fr');
});
And this works fine. As you can see:
Here is the fiddle:
http://jsfiddle.net/5zvdwtpL/1/
But now I want to change this to work a bit more dynamically.
I want there to be two dropdowns that lets you select the value you want to change from to. Like this:
This is what I got so far: https://jsfiddle.net/7s8g9kLt/2/
The problem is that one input value should be copied to the other input value but with the added value of the currency.
So If I select RSD and set 1200, the other USD, then the other input should display 11.4.
So I am stuck a bit here as to how I can achieve this.
First of all, you have bound myFunction to button onClick Event but you have not defined function with this name. You can see following error in console after clicking button
Uncaught ReferenceError: myFunction is not defined
You will have to define this function:
window.myFunction = function() {...}
or event better, add event listener to button click:
document.getElementById('buttonId').addEventListener('click', function() {...})
To calculate dynamic rates, i would first convert input amount to single currency (for example RSD) and then multiply that value by correct rate.
I've modified your jsFiddle (https://jsfiddle.net/rhj4dgz7/3/) to reflect those changes.
You can create a dictionary with the pair of "id" of dropdown and the conversion rate, also you can give the same id to both drop downs. then you gonna just multiply the value by the rate and add the result to the second input.
var rsd = 1;
var evro = 0.0085;
var dolar = 0.0095;
var frank = 0.0096;
var dict = {
"4":rsd,
"1":evro,
"3":dolar,
"2":frank
}
function myFunction(){
var mvs = document.getElementById('mojaVrednostSelect').value;
var nvs = document.getElementById('novaVrednostSelect').value;
var mv = document.getElementById('mojaVrednost').value;
var nv = document.getElementById('novaVrednost').value;
novaVrednost.value = parseInt(mojaVrednost.value) * dict[nvs]
console.log("Yoooo"+ dict[nvs])
console.log("mvs je" + mvs);
console.log("nvs je" + nvs);
console.log("======");
console.log("mojaVrednost je" + mojaVrednost.value);
console.log("novaVrednost je" + novaVrednost.value);
}
document.getElementById('button').onclick = myFunction
check this fiddle
Hope this helps you

How to access html form values from nested inputs

I'm trying to validate input from this form:
<form id = "mpath" name = "mpath" action = './../cgitest.cgi' method="POST" onsubmit = "return validateForm(this)">
Total Time (in ms): <input type = "text" name = "ttime">
Number of Cars (1-10): <input type = "text" name = "carnum">
Initial Speed (fps): <input type = "text" name = "initspeed"><br>
<!--extraRowTemplate will be repeated for every change in the accleration of the
head car -->
<p class = "extraRowTemplate" name = "extraRowTemplate">
Change:
<select name="change">
<option value="acc">Acceleration</option>
<option value="dec">Deceleration</option>
</select>
Start time: <input type = "text" name="starttime">
End time: <input type = "text" name="endtime">
Amount (in fps): <input type = "text" name="amount"><br>
</p>
<div id = 'container'></div>
<i class="icon-plus-sign"></i>Add Change<br>
<input type="submit" value="Load Head Car">
</form>
Using this function (I haven't written any of the actual validation):
<script type="text/javascript">
function validateForm(form){
var tt = document.forms[0].ttime.value;
var cn = document.forms[0].carnum.value;
var is = document.forms[0].initspeed.value;
var sta = form.elements[4].value;
console.log(tt);
console.log(cn);
console.log(is);
console.log(sta);
if(tt == ""){
alert("starttime must be filled out");
return false;
}
//return false;
}
</script>
But when I try to submit values, it only finds the values for ttime, carnum, and initspeed, and not the value of starttime, endtime, or amount. Also, the value of change is always "acc", even if I set it to "deceleration".
For those wondering why I don't simply remove extraRowTemplate, I need to have those input options in a nested section because I have an option to duplicate them.
I've tried to pass the form as an argument to the function (as shown) as well as just use document.forms[0] to access it. Neither produce the correct result.
Also, when I remove the .value from the form.elements[4].value and set:
var sta = form.elements[4];
The console prints out:
<input type = "text" name = "starttime">
Does anyone know how I can access the value of the nested inputs?
I suppose I should also say that the form works correctly in every other way, and when I send it to the cgitest.cgi, I can access all inputs. I just don't want to validate the inputs on the server side.
EDIT:
If instead of using an onsubmit function (validateForm in my case), I use an event listener:
<script type="text/javascript">
var button = document.querySelector('input[type=submit]')
button.addEventListener('click', function onClick(event) {
var ttime = document.querySelector('input[name=ttime]')
var carnum = document.querySelector('input[name=carnum]')
var initspeed = document.querySelector('input[name=initspeed]')
var change = document.querySelector('select[name=change]')
var starttime = document.querySelector('input[name=starttime]')
var endtime = document.querySelector('input[name=endtime]')
var amount = document.querySelector('input[name=amount]')
console.info('ttime', ttime.value)
console.info('carnum', carnum.value)
console.info('initspeed', initspeed.value)
console.info('change', change.value)
console.info('starttime', starttime.value)
console.info('endtime', endtime.value)
console.info('amount', amount.value)
event.preventDefault()
})
</script>
With the input ttime = 1, carnum = 2, initspeed = 3, change = "acc", starttime = 4, endtime = 5, amount = 6, I get the following console output:
(index):70 ttime 1
(index):71 carnum 2
(index):72 initspeed 3
(index):73 change acc
(index):74 starttime
(index):75 endtime
(index):76 amount
As can be seen, all values beyond initspeed (everything inside extraRowTemplate) are empty. Like I said before, they are not empty when sent to the form action url.
Can you try removing the extraRowTemplate and submit. If it's working, than you can try generating the elements inside with the different ids, because now you have duplicated items with no distinction.
You are currently accessing the elements in a bit of a roundabout way, using document.forms[0]. Also I don't see any code to get the value of the starttime input. You are testing tt in the if, but that was assigned the value of ttime.
document.querySelector
Might I suggest accessing the form elements by name directly, using document.querySelector? This method accepts a CSS selector and returns the first element that matches. Using a simple CSS3 selector we can select elements by name and assuming those names are unique on the page, we will get the right inputs. You could also use form.querySelector if the names are only unique within the form.
Example
var myInput = document.querySelector('input[name=ttime]')
I find document.querySelector and document.querySelectorAll (which gets all elements matching the CSS selector) very useful and use them all the time.
Runnable code snippet
Run this snippet and press the form submit button to print the values of the inputs. Try it and see how it works.
var button = document.querySelector('input[type=submit]')
button.addEventListener('click', function onClick(event) {
var ttime = document.querySelector('input[name=ttime]')
var carnum = document.querySelector('input[name=carnum]')
var initspeed = document.querySelector('input[name=initspeed]')
var change = document.querySelector('select[name=change]')
var starttime = document.querySelector('input[name=starttime]')
var endtime = document.querySelector('input[name=endtime]')
var amount = document.querySelector('input[name=amount]')
console.info('ttime', ttime.value)
console.info('carnum', carnum.value)
console.info('initspeed', initspeed.value)
console.info('change', change.value)
console.info('starttime', starttime.value)
console.info('endtime', endtime.value)
console.info('amount', amount.value)
event.preventDefault()
})
<form id = "mpath" name = "mpath" action = './../cgitest.cgi' method="POST" onsubmit = "return validateForm(this)">
Total Time (in ms): <input type = "text" name = "ttime">
Number of Cars (1-10): <input type = "text" name = "carnum">
Initial Speed (fps): <input type = "text" name = "initspeed"><br>
<!--extraRowTemplate will be repeated for every change in the accleration of the
head car -->
<p class = "extraRowTemplate" name = "extraRowTemplate">
Change:
<select name="change">
<option value="acc">Acceleration</option>
<option value="dec">Deceleration</option>
</select>
Start time: <input type = "text" name="starttime">
End time: <input type = "text" name="endtime">
Amount (in fps): <input type = "text" name="amount"><br>
</p>
<div id = 'container'></div>
<i class="icon-plus-sign"></i>Add Change<br>
<input type="submit" value="Load Head Car">
</form>
I can access the value of your "starttime" field in Firefox/Chrome/Opera using either
var sta = document.forms[0][4].value
or
var sta = document.forms[0].starttime.value
I was able to figure out what was going wrong. In my css I set:
.extraRowTemplate {
display: none;
}
which was preventing the input values from being sent. Once I removed this my problems went away. Setting "visibility : hidden" is a good alternative that allowed the values to be submitted and the template not visible.

How do I pass HTML input text into a JS variable?

So I have been working on a game where you have a input that prompts the actions you make. So I need to be able to put in it a JS var so I can print the input text on the page and have the computer respond and manipulate it if needed. Does anyone have a way I can do this? I hope you can help.
here is what I have so far
<p style="font-size:33px; color:red;"> Trapped in a Room</p>
<hr/><br/><br/><br/><br/><br/>
<p id="comtxt">You wake up trapped in a room and need to find a way out.<br/>Use the input bar below as a action prompt.</p>
<p id="usertxt"></p>
<form script="answer();">
<input id="prompt" width="60" type="text">
<input id="sub" type="submit">
</form>
and then the javascript
var prompt = getElementById("prompt");
var comtxt = getElementById("comtxt");
var sub = getElementById("sub");
var usertxt = getElementById("usertxt");
var answer = function() {
usertxt = prompt;
}
sorry if the JS is hard to read...
var sender = document.getElementById("sub");
sender.addEventListener("click", setInputText, false);
function setInputText (){
var inpTxt = document.getElementById("prompt").value;
document.getElementById("usertxt").innerHTML = inpTxt;
};
Here the fiddle http://fiddle.jshell.net/7d8fH/8/

How to dynamically turn a text field into dropdown?

The name says all. I want to change a text field element into combo box using javascript. It will be nice if it's cross-browser.
EDIT: I may use jQuery
The trick is to create the dropdown element and add it to the form, as well as remove the text field. You can have HTML like this:
<form id='myform'>
...
<span id='textelement'>text goes here</span>
<input type='button' value='change text to dropdown' onclick='change()'/>
...
</form>
Then your change() function could be something like this:
function change() {
var _form = document.getElementById('myform');
var _text = document.getElementById('textelement');
_form.removeChild(_text);
var _combo = document.createElement('select');
_combo.setAttribute('size', '1');
_combo.setAttribute('id', 'dropdownelement');
_form.appendChild(_combo);
_combo = document.getElementById('dropdownelement');
//add first value to the dropdown
var _opt = document.createElement('option');
_opt.text = 'New option 1';
_opt.value = '1';
_combo.add(_opt);
//add second value to the dropdown
_opt = document.createElement('option');
_opt.text = 'New option 2';
_opt.value = '2';
_combo.add(_opt);
...
}
Note that I haven't tested this code - use it as a starting point only.
Are you wanting to change it client side or server side. If client side there really is not way without using javascript of some sort.
You can use InnerHTML but it isn't compatible with all browsers (Not compatible with: NN4 , OP5, OP6)

Categories