Javascript output as value of hidden input - javascript

How can I set the ouput of this javascript function as the value for a hidden input on a html form?
document.write(states[i][1]);
works fine but I cannot get it to fill in the value with the code as shown below.
if (to == 'abbr'){
input = input.replace(/\w\S*/g, function(txt){return
txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
for(i = 0; i < states.length; i++){
if(states[i][0] == input){
document.getElementById("sid").value = (states[i][1]);
}
}
}
}
</script>
<form action="we2.php" method="post">
<input type="text" id="sid" name="s1"/>
<input type="submit" value="Verify">
</form>
What is wrong with this code / what is the right way to do this?
Thanks!

This should do it.
HTML:
<input type="hidden" id="HiddenInput" />
JavaScript:
document.getElementById("HiddenInput").value = someFunction();

Have you checked if states[i][0] == input evaluates to true?

Write JavaScript code after html code end in your page or at the end of page.

I found a easier solution by just turning the entire function into a variable then the variable into the DOM:
var response = abbrState('<?php echo $_GET['state']; ?>', 'abbr');
document.getElementById("sid").value = response;

The following should work.
HTML:
<div style="display:none" id="example"></div>
Javascript:
function addTextNode(text) {
var newtext = document.createTextNode(text),
element = document.getElementById('example');
element.appendChild(newtext);
}
function yourFunctionDataHere(){
return 'test1234';
}
addTextNode(yourFunctionDataHere());
Just make sure, that the return type of your function is of type string. If you want to see the output simply remove the style="display:none" from the div in the above example.
Try it online on jsfiddle.

Related

Im learning JS and i have a task to make the numbers that i input reverse and pop up in an alert

i made the script that reverses the numbers but i dont know how to make the alert pop up the result of the reversed numbers
I need help to figure this out it probably has a simple solution but i dont know
The code added to snippet is below:
function okreni () { // removed "s" parameter
var a = ' ';
// s = s.toString();
const s = document.getElementById("broj").value.toString();
for (var i = s.length - 1; i>=0; i--) {
a += s[i];
}
window.alert (a);
};
<body>
<label for="broj">Unesite Broj:</label>
<input type="number" name="broj" id="broj" value="">
<div>
<button value="okreni" onclick="okreni()">Okreni</button>
</div>
</body>
EDIT -
The s = s.toString() has been changed to get the information from the input-value.
alert doesn't display if there's no value to display. in your case you have to passe a value to "okreni()" function.
<button value="okreni" onclick="okreni(**value**)">Okreni</button>
Apparently, you suppose to get the input value as s in okreni(s). However, this is not possible. You have to get the value programatically from the input. Following the working code. I've also created this CodeSandbox for you to try it out:
<!DOCTYPE html>
<html>
<head>`enter code here`
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<label for="broj">Unesite Broj:</label>
<input type="number" name="broj" id="broj" value="" />
<div>
<button value="okreni" onclick="okreni()">Okreni</button>
</div>
<script type="text/javascript">
function okreni() {
var a = " ";
let inputValue = document.querySelector("#broj").value;
const s = inputValue.toString();
for (var i = s.length - 1; i >= 0; i--) {
a += s[i];
}
window.alert(a);
}
</script>
</body>
</html>
You could also try something like this to reverse your string. In looks much cleaner in my opinion and can even be condensed to a single line if needed.
Apart from that, the reason you are getting an error is because of what alexanderdavide mentioned in his answer. To elaborate further, the okreni function does not require a parameter to be passed. Instead, within the fucntion we look for the value in the input element with the id of broj. So, when you click on the button, the function checks the string in that input, reverses it and then performs an alert.
function okreni() {
let s = document.getElementById('broj').value
s = s.split("").reverse().join("")
window.alert(s)
}
<label for="broj">Unesite Broj:</label>
<input type="text" name="broj" id="broj" value="">
<div>
<button value="okreni" onclick="okreni()">Okreni</button>
</div>

Javascript getElementByID from form input

I am providing a form where the user shall enter an arithmetic calculation. Further down the result shall appear, once the user hits enter. It might just be a problem of syntax, but I couldn't find the mistake. Here is what I did so far:
<!DOCTYPE html>
<html>
<body>
<p>What do you want to calculate?</p>
<form method="post"><span>Type here:</span><input type="text" id="calc"></input>
</form>
<script>
num_field = document.getElementById("calc");
num_field.onsubmit=function ()
{
document.getElementById("display_result").innerHTML = num_field;
}
</script>
<p id="display_result"></p>
</body>
</html>
So, the user shall enter for instance "1+2". The result shall appear below.
Any idea where is my mistake?
Best regards
Here is how you can achieve that.
eval is the best way for doing that but eval is risky to use so make sure to sanitize the value of input before using eval.
I am using this regex /(^[-+/*0-9]+)/g to extract only numbers and few operators (-+/*) and doing eval on that value.
remove the <form> that is not required use keypress event listener and check for enter key. keycode of enter key is 13
num_field = document.getElementById("calc");
num_field.onkeypress = function(e) {
if(e.which==13)
{
var value = num_field.value.match(/(^[-+/*0-9]+)/g);
if(!value) return;
else value = value[0];
var res = eval(value);
document.getElementById("display_result").innerText = res;
}
}
<p>What do you want to calculate?</p>
<span>Type here:</span>
<input type="text" id="calc" />
<p id="display_result"></p>
You were nearly there, your code just needed a bit of tweaking - see below (comments in code as what I have done and why)
The following seems to be an alternate and safer way to do this without using eval (function taken from the second answer in this post):
<!DOCTYPE html>
<html>
<body>
<p>What do you want to calculate?</p>
<form method="post" id="form">
<span>Type here:</span>
<input type="text" id="calc"> <!-- inputs are self closing no need for closing tag -->
<input type="submit" value="submit"> <!-- added a submit button -->
</form>
<script>
form = document.getElementById("form");
num_field = document.getElementById("calc");
form.onsubmit = function() { // attach this event to the form
document.getElementById("display_result").innerHTML = evalAlternate(num_field.value); // add .value here to get the value of the textbox
return false; // return false so form is not actually submitted and you stay on same page (otherwise your display result will not be updated as the page is reloaded
}
function evalAlternate(fn) { // function safer alternate to eval taken from here: https://stackoverflow.com/questions/6479236/calculate-string-value-in-javascript-not-using-eval
fn = fn.replace(/ /g, "");
fn = fn.replace(/(\d+)\^(\d+)/g, "Math.pow($1, $2)");
return new Function('return ' + fn)();
}
</script>
<p id="display_result"></p>
</body>
</html>
see the below fiddle
https://jsfiddle.net/ponmudi/13y9edve/
num_field = document.getElementById("calc");
num_field.onkeydown = (event) => {
if (event.keyCode === 13) {
document.getElementById("display_result").innerHTML = eval(num_field.value);
return false;
}
}
This should work:
calc = document.getElementById("calc");
formula = document.getElementById("formula");
calc.addEventListener('click', function() {
document.getElementById("display_result").innerHTML = eval(formula.value);
});
<p>What do you want to calculate?</p>
<span>Type here:</span>
<input type="text" id="formula" />
<button id="calc" type="submit">calc</button>
<p id="display_result"></p>
eval() JavaScript Method
Try this:
var calculation_input = document.getElementById('calculation_input');
calculation_input.onkeydown = function(event) {
if (event.keyCode == 13) { // Enter key.
// Sanitize before using eval()
var calculation = calculation_input.value.replace(/[^-()\d/*+.]/g, '');
document.getElementById("display_result").innerHTML = eval(calculation);
}
}
<p>What do you want to calculate?</p>
<span>Type here:</span>
<input type="text" id="calculation_input" />
<p id="display_result"></p>
You don't need to submit the calculation in a form, you can just use native javascript to calculate the result. And don't forget to always sanitize before using eval :)

Get value from hidden field - JavaScript

I have a <input type="hidden" class="Key" value="1m2.123.mds.34g" />
How can I get the value without using jQuery?
With jQuery i just only write:
var parse = $('.Key').attr("value")
alert(parse);
I need this in pure JavaScript, maybe use RegEx? I will execute this script on txt file which will contain such line.
check this
window.onload=function(){
var hidden=document.getElementsByClassName("Key");
alert(hidden[0].value);
}
<input type="hidden" class="Key" value="1m2.123.mds.34g" />
var inputs = getElementsByClassName('Key');
for(var i=0; i<inputs.length;i++) {
console.log(inputs[i].value);
}
Easy! Just use getElementsByClassName. E.g:
document.getElementsByClassName('Key')[0].value
Or if you had to get the value by id you can use getElementById
document.getElementById('idHere').value
Here's 4 ways to get the value of .Key. Also I added a better way to do it in jQuery as well using the method val().
SNIPPET
var k = document.querySelector('.Key').value;
console.log(k);
// This works if .Key is inside a <form>
var e = document.forms[0].elements[0].value;
console.log(e);
var y = document.getElementsByTagName('input')[0].value;
console.log(y);
var s = document.getElementsByClassName('Key')[0].value;
console.log(s);
//BTW there's a better way of finding value with jQuery
var $Key = $('.Key').val();
console.log($Key);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id='f1'>
<input type="hidden" class="Key" value="1m2.123.mds.34g" />
</form>
Thank you all. I resolve this problem as follow:
var regEx = /class="Name"+ value="(.*?)"/;
newName = result.match(regEx)[1];
var regEx2 = /class="Key"+ value="(.*?)"/;
var key = result.match(regEx2)[1];
Alert(key + ' ' + newName );

Return Output in an HTML Element onkeyup

I'm working on html editor but this part is giving me a problem is there anyway to archive this? when i type in the text filed it will display an output in the div element.
<script type="javascript/text">
function ColorText(){
T = Rep(document.getElementById("text").value);
document.getElementById("wcode").innerHTML=T;
setTimeout("ColorText()",10);
}
</script>
HERE IS HTML PART
<input type="text" id="text" onkeypress="ColorText()"/>
<div type="text" id="wcode"></div>
A more elegant solution, without setTimeout:
function Rep(value){
//Do your thing...
return value;
}
var wcode = document.getElementById("wcode");
var text = document.getElementById("text");
text.addEventListener("input", function(){
wcode.innerHTML = Rep(this.value);
});
<input type="text" id="text"/>
<div id="wcode"></div>
Codesoft, your code may not be working for 2 things:
<script type="javascript/text">
change it for:
<script>
or
<script type="text/javascript">
And the other possible problem:
T = Rep(document.getElementById("text").value);
Maybe you hadn't defined the function Rep(). You have to define it and return a string value, or just don't use it, like this:
T = document.getElementById("text").value;
Besides of that, Marcos Casagrande gave you a better solution to your problem, please, take a look to that code.

javascript link not working

This is driving me a bit nutty. Javascript link should fire function to fill in div. But not working.
js
function showNotes(notes,id) {
var notes = '<form action="editnotes.php" method="post"><textarea>'+notes+'</textarea><input type="hidden" name="id" value="'+id+'"><input type="submit" name="submit" value="Save Notes"></form>';
var target = 'notebox';
alert(id);
document.getElementById(target).innerHTML = notes;
return false;
}
html
<a href='#' onclick='showNotes('hi there','143');'><small>Show Notes</small></a>
<div id="notebox"></div>
Enclose the onclick attribute value in double quotes, so the single quotes specify a string within your string.
onclick="showNotes('hi there','143');"
http://jsfiddle.net/77CKx/
Shredder got to the heart of the issue. You have nested quotes. However, inline JS is so not cool. Do it with script and the problem goes away. http://robertnyman.com/2008/11/20/why-inline-css-and-javascript-code-is-such-a-bad-thing/
HTML
<small>Show Notes</small>
JS
document.getElementById('shownotes').onclick = function() {
showNotes('hi there', '143');
return false;
}
It seems like you are breaking the onclick by using the single apostrophe for your function arguments.
Try
<small>Show Notes</small>
Working code:
showNotes = function (notes,id) {
var notes = '<form action="editnotes.php" method="post"><textarea>'+notes+'</textarea><input type="hidden" name="id" value="'+id+'"><input type="submit" name="submit" value="Save Notes"></form>';
var target = 'notebox';
alert(id);
document.getElementById(target).innerHTML = notes;
return false;
}​
<small>Show Notes</small>
<div id="notebox"></div>​
You can also view it working here:
http://jsfiddle.net/ZMZGk/13/

Categories