Write to textarea when enter key is pressed? - javascript

I have a textarea, which will handle output, and a textfield which will handle user input.
Focus will be entirely on the input field.
I can't make it so that the user input field will add text when the form is submitted (enter key is pressed). It will only work if there is a button and this is clicked. How do I solve this issue?
Below is the code i'm trying for the enter key submit.
<html>
<head>
<script type="text/javascript">
function addtxt(input) {
var obj=document.getElementById(input)
var txt=document.createTextNode("blah blah")
obj.appendChild(txt)
}
</script>
</head>
<body>
<textarea id="textarea1"></textarea>
<br><input type="text" onSubmit="addtxt('textarea1');">
</body>
</html>

This will do the job. Also, you should deal with the value property of the textarea rather than appending text nodes to it: if the user changes the textarea's value at all, changing its child nodes afterwards will have no effect. If you want the textarea to be read-only, add a readonly attribute: <textarea id="textarea1" readonly></textarea>.
<script type="text/javascript">
function inputKeyDown(evt, input) {
if (evt.keyCode == 13) {
var textarea = document.getElementById("textarea1");
textarea.value += "\n" + input.value;
input.value = ""; // I'm guessing you may want this
return false;
}
}
</script>
<input type="text" onkeydown="return inputKeyDown(event, this);">

Instead of submit, try using the keypress event. Detect when the enter key is pressed, copy the data, and cancel the event (to prevent form submission). If you allow the form to submit, it will simply replace the existing page with the result of the form post.
Modifying your current code:
<html>
<head>
<script type="text/javascript">
function addtxt(e,ctl,input) {
var key;
if (window.event) {
key = event.keyCode;
} else {
key = e.which;
}
if (key == 13) {
var obj=document.getElementById(input);
var txt=document.createTextNode("blah blah");
obj.appendChild(txt);
ctl.value = '';
return false;
}
return true;
}
</script>
</head>
<body>
<textarea id="textarea1"></textarea>
<br><input type="text" onkeypress="return addtxt(event,this,'textarea1');">
</body>
</html>
Note that there may be much better ways to achieve your ultimate goal, but since you don't state what that is, this is really the best I can do. Also, I'd would definitely look at using a framework like jQuery/Dojo/Prototype and add the handlers unobtrusively.

Use the form element
<form onsubmit="addtxt('textarea1')">
<textarea id="textarea1"></textarea>
<br><input type="text" />
</form>

You can use JQuery
$('textarea#textarea1').keypress(function(e) {
if (e.keyCode == 13) { // enter
//do some stuff
}
});

Related

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 :)

Jquery: How do I get the user's input as they type

I want to be able to get the user's input to be able to validate it and see if it is a key that I want to appear or use. I don't want the full value of what is in the input, just the specific key they are entering.
I have done it in Javascript by using this code but it does not work the same in Jquery. Thanks!
<input type="text" id="a">
$("#a").on('input', function(e){
var charval = String.fromCharCode(e.Keycode);
alert(charval);
});
The alert should show the key that was pressed.
DEMO:
$("#a").on('input', function(e){
var charval = String.fromCharCode(e.Keycode);
alert(charval);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="a">
Consider this:
document.getElementById('f').addEventListener('keyup', function(e) {
document.getElementById('out').textContent = e.keyCode;
})
<input type="text" id="f">
<p id="out">Hi</p>
You'll see keyCode of the last button pressed. You can also add an alert inside a listener if you wish so.
Change e.keycode to e.which
$("#a").on("keypress", function(e){
var charval = String.fromCharCode(e.which);
alert(charval);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="a">
Just fixed your code to work :
$("#a").on('keyup', function(e){
var charval = String.fromCharCode(e.which);
alert(charval);
});

I'm trying to make a specific input into a text area call a specific javascript function, but it won't work

So to give a little bit of detail, I'm trying to make an interactive fiction game or text adventure. I have a form where all the "commands" for the game will be typed. I'm working on the first command which is the string "start" to call a prompt. Just to test the code, I have the prompt say "success!" when done correctly. What's happening though, is as soon as I open the web browser to test, the prompt triggers before I even type a command. Here's the code.
<html>
<head>
<script type="text/javascript" src="scripts/engine.js"></script>
</head>
<body>
<form id="testForm"> <input type="text" name="">
</form>
</body>
</html>
And then here's the javascript.
var input = document.getElementById("testForm");
if (input = "start") {
prompt("Success!");
}
Try this:
<html>
<head>
<script type="text/javascript" src="scripts/engine.js"></script>
</head>
<body>
<form id="testForm">
<input type="text" id="myInput">
</form>
<script>
var myForm = document.getElementById("testForm");// get the form element.
var myInput = document.getElementById("myInput");// get the input element
myForm.onsubmit = function() { // when the form is submitted, execute this function.
if (myInput.value == "start") { // if the value of the input equals 'start', show prompt.
prompt("Success!");
}
return false; //return false, so the form doesn't get submitted.
};
</script>
</body>
</html>
Edit:
Added submit event handler, that returns false, so the form does not get submitted.
You need to check the value of the input like so
var input = document.getElementById("inputID");
var value = input.value;
The code will always be ran straight away because it has no event handler. You could add a button which triggers it
document.getElementById('button').addEventListener('click', function () {
var input = document.getElementById("inputID");
if (input.value === 'start') {
// Do something
}
});
Or if you prefer on the forms submit event:
document.getElementById('testForm').addEventListener('submit', function () {
var input = document.getElementById("inputID");
if (input.value === 'start') {
// Do something
}
});

Pressing 'enter' on a input type="text", how?

I am facing a problem I can not solve JQuery Javascript. Can you help me and help me understand.First here is my code :
(...)
<script type="text/javascript">
// Autocomplete suggestions
$(function () {
$("#autoCompInput").autocomplete({
source: "/Suggestions",
minLength: 3,
select: function (event, ui) {
if (ui.item) {
$("#autoCompInput").val(ui.item.value);
$("form").submit();
}
}
});
});
// Provide search results
$(function () {
$("#autoCompSearch").click(function () {
var searchParameters = $("#autoCompInput").val();
var jsonData = JSON.stringify(searchParameters, null, 2);
window.location = "/Search?criteria=" + searchParameters;
});
});
</script>
(...)
<input class="ui-autocomplete-input" id="autoCompInput" role="textbox" aria-haspopup="true" size="50" autocomplete="off" aria-autocomplete="list" value = "#ViewBag.SearchInfo"/>
<a id= "autoCompSearch" href = "#" ><img src="#Url.Content("~/Content/Menu/Images/magnifier.png")" alt="Search" /></a>
(...)
With this code I can't use the 'Enter' key to execute my search. When the user is in the input autoCompInput I would like to be able to detect if he press 'enter' and launch the submit. I read I must add a onkeyup="onKeyPressed(event)" event but I don't understand how to write the javascipt associated with the command. I tried but without success... Do you have a solution for me?
Thank you,
You should bind the keypress event to your input
$("#autoCompInput").bind("keypress", {}, keypressInBox);
function keypressInBox(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) { //Enter keycode
e.preventDefault();
$("yourFormId").submit();
}
};
With similar HTML:
<input type="text" id="myTxt" />
<input type="submit" id="mySubmit" />
This script (which uses the latest jQuery 1.7.2) should do it:
$('#mySubmit').click(function() {
alert('Submitted!');
return false;
});
$('#myTxt').on('keyup', function(e) {
if (e.keyCode === 13) {
$('#mySubmit').click();
}
});
Here's a working example.
To assign a keyup event in jquery
$("#autoCompInput").keyup(function(event) {
if (event.keyCode==13) {
alert('enter key');
}
});
I think there is a better and more standard solution to this type of problem.
you can have a GET form around those inputs and whenever you press enter on any input inside that form, it will be submitted to whatever is in the action attribute of the form. This is how it would look like (I took your code but I am removing the bits irrelevant for my answer):
<form id="idForJqueryOnly" action="/Search" method="GET">
<input type="text" name="criteria" value="someuserinput"/>
<button type="submit"><img src="...")" alt="Search" /></button>
</form>
This is standard browser behaviour. So, what the form does? when submitted the browser creates a URL like this:
http://yourserverguesedfromthecurrenturl/Search?criteria=someuserinput
What happened is that the browser took all the inputs with name and value (and not disabled) from the form and serialized them into url form.
Now, the submit event can be triggered by pressing enter on any of the inputs inside, including buttons as long as the buttons don't have the attribute type="button".
If you wanted to do more things with the data with javascript before going to the search page, you can do this with jquery:
$("#idForJqueryOnly").submit(function(){
// here you can do stuff like serialize the form, or sanitize the input of tue user.
var data = $("#idForJqueryOnly").serialize();
$("[name=criteria]").val($("[name=criteria]").val().customSanitizeMethod());
// if you return false, the form will not submit, say, for validation errors:
return customValidator.isFormValid("#idForJqueryOnly");
})

Make a link 'enter-clickable'

If you have a normal form:
<form method='post' action='#'>
<input type='text' name='#' />
<input type='submit' value='Submit />
</form>
Then you can fill in the input field, and press enter. However, I am using a link to do my work so:
<form method='post' action='#'>
<input type='text' name='#' />
<a href='#' class='button' onclick='get_form(this).submit();'>Submit</a>
</form>
That works like a charm, however, I want it to inherit the 'enter-clickable' that the normal submit field has. Is that possible through some javascript?
$('#your_input_textfeild_id').keypress(function(e) {
//check if enter is pressed
if(e.keyCode == 13) {
//click your link
$('#your_submit_link_id').click();
}
});
try this:
<script>
document.getElementById('TEXTBOXID').onkeypress = function(e){
var evt = e || window.event;
if(evt.keyCode == 13){
get_form(this).submit();
}
}
</script>
I think the correct way to do this is to actually include a
<input type="submit" >
which you can then style to be hidden. Alternatively, just style the submit element to look the way you want. My reason for this is that the browser looks for that submit element and that's how the enter key gets assigned to submit the form. And I somehow think it's better to let the browser handle matters like that rather than using JavaScript to capture a keypress event.
You may try this
document.getElementById('my_input').onkeypress = function(e)
{
var event = e || window.event;
if(event.keyCode == 13 && this.value!="")
{
form = this.parentNode;
if(form.tagName.toLowerCase() == "form")
{
form.submit();
}
}
}
You have to add an id to your text box and replace my_input with it.

Categories