Extracting data from array after HTML form submission (keypress event) - javascript

So I have a HTML form with a keypress event listener recording the charCode of the key pressed and then convert that charCode to a String of the letter related to the key.
Each time a letter is entered to the form, a new entry is created in input_array[].
I have each letter in the alphabet stored as a SVG within JS variables in a different part of my main.js file and I would like to be able to read what letters have been stored in input_array[] and then display the SVG appropriate to that letter on a new page once the form has been submitted.
I've tried using the method below to extract the data from the array, but it fires on the first keypress and therefore I can't get all of the array data to then display the 4 letters. I also feel like there has to be a more efficient way.
var letter_one = input_array[0];
var letter_two = input_array[1];
var letter_three = input_array[2];
Here's a JSFiddle, to show a basic version of what I'm trying to do. If you open the console you will see how input_array[] is being created.
I'm still very new to this language, so any help would be greatly appreciated.

As you suspected, this is much simpler than you're making it :)
When the form is submitted you can just snag the value from the input:
function handleSubmit() {
var val = document.getElementById('user_input').value;
validate(val);
console.log(val);
var letter_one = val[0];
var letter_two = val[1];
var letter_three = val[2];
var letter_four = val[3];
return false; // stops POST for dev
}
https://jsfiddle.net/1htpm6ag/
That being said, if you are actually doing this on a POST then on the page you are POSTing to you'll have to snag this from the POSTed form data, which is entirely different. Are you trying to do this in client side JS or a POST handler?

If I am understanding you correctly is sound like you want to do the following.
On Page 1 user enters text into textfield.
On Submit send that text to page 2.
On Page 2 convert that text into an array of letters to associate with SVG paths to display.
If the above is the case you need a lot less javascript.
Page 1: Should only have your form with your text box and a submit button so the data is submitted to the next page using the GET method.
Page 2: Here is where you will need the Javascript to retrieve that data sent across and process it into your array of letters. I would also filter for non-letter characters as well.
I have created an example form in the code below that submits to itself and then the javascript script tag will pull the variable from the url and process it into an array of letters. In your case you would move the Javascript to page 2.
<script type="text/javascript">
(function(){
function getParamValue(param) {
var urlParamString = location.search.split(param + "=");
if (urlParamString.length <= 1) return "";
else {
var tmp = urlParamString[1].split("&");
return tmp[0];
}
}
function isLetter(c) {
return c.toLowerCase() != c.toUpperCase();
}
var user_input = getParamValue('user_input');
var char_array = null;
if(user_input !== ''){
char_array = user_input.split("");
char_array = char_array.filter(isLetter);
for(var i in char_array){
console.log('Char ' + i + ' = ' + char_array[i]);
}
}
})();
</script>
<body>
<form id="user_form" class="" action="?" method="GET">
<input type="text" name="user_input" />
<input type="submit" value="submit">
</form>
</body>

Related

How to read input box line by line in Javascript and return various values depending on input?

I am trying to create a function in Javascript which can read an input box line by line and return different values depending on the input.
For example, if someone enters several protein mutations on separate lines with the format Arg86Lys, I want the function to read the first three and last three letters to get Arg Lys. Then, if I have a value stored for Arg Lys (let's say 100), I want the output to be a textbox which prints out the value 100 (and prints out the rest of the values on separate lines).
I am stuck on how to read the input box value line by line, and only extract the first three and last three letters from each line. I also do not understand how I can store values (like Arg Lys = 100) and return said values when a certain input is found.
So far I have created a multiline textbox (in HTML) and tried to make a function that reads line by line:
<body>
<form action = "/cgi-bin/hello_get.cgi" method = "get">
Enter mutations on separate lines with format Arg86Lys
<br>
<textarea rows = "5" cols = "60" name = "description">
</textarea><br>
<input type = "submit" value = "submit" />
</form>
<script>
var lines = document.getElementById('textareaId').innerHTML.split('\n');
for(var i = 0;i < lines.length;i++){
\\
}
</script>
</body>
textarea is an input, so its value is going to be stored in its value property, and passed along with the form submission. Here is an answer I found that goes over how to intercept the submit event for the form:
Intercept a form submit in JavaScript and prevent normal submission
Once you've intercepted the form submission event, pull the value from the description input, and do with it what you want from there
let form = document.getElementById("form");
let data = {"Arg Lys":100}; // store data like this
form.addEventListener("submit",function(e){
e.preventDefault();
var lines = document.getElementById('textareaId').value.split('\n');
document.getElementById('textareaId').value = '';
for(var i = 0;i < lines.length;i++){
let val = lines[i].substring(0,3);
let lastval = lines[i].substring(lines[i].length - 3)
document.getElementById('textareaId').value += val+' '+lastval + ' - ' +data[val+' '+lastval]+'\n';
}
})
<body>
<form id="form" action = "/cgi-bin/hello_get.cgi" method = "get">
Enter mutations on separate lines with format Arg86Lys
<br>
<textarea id="textareaId" rows = "5" cols = "60" name = "description"></textarea><br>
<input type = "submit" value = "submit" />
</form>
</body>
Are you looking for something like that?

How can I make a text field for a JavaScript function?

I THINK i have managed to write a script. I just can not make a textfield in HMTL to enter the missing data. It it supposed to receive the keyword from a text field on submit click and navigate to the URL.
I have tried multiple ways of forms and everything. Should have installed VB.net and this would have been done in 5 min.
function urlMaker(keyword) {
var base = "https://www.example.com/list.php?q=";
var ending = "&dhd=1&hdd=low&dtt=list";
var url;
url = base + keyword + ending;
window.location.assign(url);
}
In short words:
I need to know how to create a HTML page with a textfield and a submit button. When I submit it takes the text from the field and run the function and feeds it with the keyword from the textfield. When function has ran it redirects browser.
I'm guessing you have a form like this.
Just attach a submit event-listener to it:
document.querySelector("#search").addEventListener("submit", urlMaker)
function urlMaker(event) {
let keyword = document.querySelector("#keyword").value;
let base = "https://www.example.com/list.php?q=";
let ending = "&dhd=1&hdd=low&dtt=list";
let url;
event.preventDefault();
url = base + keyword + ending;
window.location.href = url;
}
<form id="search">
<input type="text" id="keyword" />
<button type="submit">Search</button>
</form>

How to remember form data that has not been submitted?

How can you make the browser remember what the user typed in the form, which has not yet been submitted and make the page refreshing not affect the data entered?
I have a form in which the user enters a number. Initially the form has 0 by default. I am storing the data in localStorage, so the browser can remember the data. However, when the page is refreshed, the user-entered data disappears and 0 is displayed by default. (still the localStorage data exists for it)
I tried to use jQuery's
$(".formClassName").val(localStorage.getItem(key));
but it does not work. Can anyone give me a piece of advice on this?Thank you in advance.
Edited: My form looks like this:
<form>
<!--There are multiple forms, and the only difference among them is the "name" attribute -->
Enter a number <input type="text" value="0" class"dataEntered" name="****">
<!--The button below saves the data entered in the above form -->
<input type="button" class="savedata" value="Save Value" name="****">
</form>
And I am adding the data to localStorage like below:
//JavaScript
<script>
//Using on because the website retrieves the above form dynamically
$(document).on("click", ".saveData", function(e){
//retrieve the number entered in the form
var userNum = $(this).siblings(".dataEntered").val();
//retrieve the value in name attribute
var thisFormName = $(this).attr("name");
//store the data
localStorage.setItem(thisFormName, userNum);
//Now that the save button has been pressed (not submitted to the
//server yet), and the data is stored in localStorage, I want to
//the page to show the number in userNum even after you refresh the page
//but this does not work.
$(".dataEntered").val(localStorage.setItem(thisFormName));
});
</script>
use cookie:
function addCookie(sName,sValue,day) {
var expireDate = new Date();
expireDate.setDate(expireDate.getDate()+day);
document.cookie = escape(sName) + '=' + escape(sValue) +';expires=' + expireDate.toGMTString();
}
function getCookies() {
var showAllCookie = '';
if(!document.cookie == ''){
var arrCookie = document.cookie.split('; ');
var arrLength = arrCookie.length;
var targetcookie ={};
for(var i=0; i<arrLength; i++) {
targetcookie[unescape(arrCookie[i].split('=')[0])]= unescape(arrCookie[i].split('=')[1]);
}
return targetcookie;
}
addCookie('type','1',1024);
var cookiesample = getCookies();
$(".formClassName").val(cookiesample.type);
cookiesample.type could be remembered unless the cookie is deleted.
Checkout this codepen I have it shows a functional solution to the problem. Also you need to make sure jQuery script checks if the DOM is ready, you can do that by using $(function() { }) a short hand for .ready().
$(function() {
var input = $("[type=text]");
var thisFormName = input.attr("name");
if (localStorage.getItem(thisFormName)) {
var value = parseInt(localStorage.getItem(thisFormName));
input.val(value);
}
$(document).on("click", ".savedata", function(e) {
var userNum = input.val();
localStorage.setItem(thisFormName, userNum);
input.val(localStorage.getItem(thisFormName));
});
});

Send value in textarea

Hi I was just wondering how to persist the data to another page. So far I've found out that I need a form to send it in, Here's an example:
HTML:
<form action="Result.html" method="get">
<textarea id="test" autofocus></textarea>
<p id="demo"></p>
<button onclick="myFunction()"></button>
</form>
jQuery:
function myFunction() {
var x = document.getElementById("test").value;
document.getElementById("demo").innerHTML = x;
}
This file that I'm using it's called Exercise1.html, I don't know if it helps or not but just in case it does. I know HTML, CSS, jQuery and Javscript so I rather prefer that
Because loading a new page causes the JavaScript and HTML to be destroyed there is not way to preserve the value between page loads without some extra work. There are essentially three options.
Server Script
When the form sends data to a running server the server can take the value and inject it into the next page. Since this is a JavaScript question I will assume this is beyond the scope of the question.
Cookies / localStorage
Each page could look for a form of persistent storage on page load and populate the values. Usually you can save data to localStorage or possibly a cookie. Then on page load the JavaScript should load the value from storage and populate as needed.
Single Page App
In the case of a Single page app the value would be in memory and you manipulate the DOM to swap out views There are many frameworks that offer things like routing to make it look like a new page even though it is still the same page. Then you can populate values that way.
To explain in detail all options would be more then a single answer and more specific details should be searched and asked for.
In the exercise1.html:
<form id="form1" action="result.html" method="get">
<textarea id="aboutme" name="aboutme" rows="10" cols="30"></textarea>
<input type="submit" class="bottom" name="submit" id="submit" value="Sign up" >
</form>
In the result.html:
<script>
var queryString = decodeURIComponent(window.location.search);
queryString = queryString.substring(1);
var queries = queryString.split("&");
for (var i = 0; i < queries.length; i++)
{
var query = queries[i].split("=");
document.write(query[1] + "<br>");
}
</script>
If you like to persist your value to other pages on your webpage you can put the values in cookies:
// This saves your value
function saveField(){
value = $('#test').val();
document.cookie['myValue'] = value;
}
// This gets your value back on other pages
function loadField(){
return document.cookie['myValue'];
}
More on how cookies work here
Hi I just wanted to say that I found another way to do display what key that was pressed, if anyone else is interested.
Javascript:
document.onkeypress = function(e) {
e = e || window.event;
var charCode = e.charCode || e.keyCode,
character = String.fromCharCode(charCode);
console.log(charCode);
if(e.charCode == 98 || e.keyCode == 98) {
document.write("B = " + charCode + "<br>");
} else if(e.charcode == 114 || e.keyCode == 114) {
document.write("R = " + charCode + "<br>");
}
};
So when you press B or R it displays the keyCode or charCode and it works in Chrome, Explorer and in Firefox (but it's a little slow in firefox, but it works).

Javascript Form Validation referencing issue

Im trying to validate a form for an assignment and have hit a wall, apologies in advance if I miss the obvious Im quite new to programming.
Im trying to validate multiple form fields to check for erroneous data before the form is submitted. I have a separate function in an external file for each type of field that holds a regex and checks the input and acts on the result.
My problem is that I built the functions to need parameters to work.
At the moment I have the functions placed in the onblur section of each field to validate and provide feedback as the user progresses through the form. Now when I want to build a master function to call all the functions in the onsubmit section of the form my referencing wont work, I must be missing something trivial but I've gone over the code again and again.
Sample onblur code:
<tr><td>Any number</td>
<td><input type="text" id="anyNumber" name="anyNumber" size="10" maxlength="4"
onblur="validateNumber('anyNumberP', 'anyNumber', anyNumber.value);"/>
</td>
<td>
<p style="display:inline;" id='anyNumberP'> </p>
Sample External File Function:
function validateNumber(pId, id, value){
var inputCorrectMsg = "<--Input is Valid";
var inputIncorrectMsg = "<--Error: Please enter a number.";
var regEx = /\d\d\d\d/;
var trimValue = value.replace(/^\s+|\s+$/, '');
var trimValue1 = trimValue.replace(/^0+/g, '');
var result = regEx.test(trimValue1);
if (result == true){
feedbackColour(pId, id, result, inputCorrectMsg);
} else{
feedbackColour(pId, id, result, inputIncorrectMsg);
}
return result;
}
What I need to be able to do from the external file:
function lastCheck(){
var result1 = validateNumber('anyNumberP', 'anyNumber', anyNumber.value);
var result2 = validateOtherStuff('etc', 'etc', 'etc');
if(result1 && result2 = false){
return false;
}else{
return true;
}
}
I tried the referencing the function like above but it wont work in my master function. Wether its the reference to the function or the variables passed to the function im not sure. If anyone can help id REALLY appreciate it, thanks!

Categories