Sending form text input to console.log for testing - javascript

I have a simple form with one text field for testing. I need to have the info the user types in sent to console.log for now. Is this possible and if so what would I write?
<form class="pure-form">
<input id="name" type="text" placeholder="Enter Name" />
<button type="submit"><i class="fa fa-chevron-circle-right"></i></button>
</form>

var nameInput = document.getElementById('name');
document.querySelector('form.pure-form').addEventListener('submit', function (e) {
//prevent the normal submission of the form
e.preventDefault();
console.log(nameInput.value);
});

Not sure why this question was down-voted. It's basic, but it's still a perfectly valid question.
The simplest way would be to grab the input by the ID then grab it's value and console.log it.
So, in a separate JavaScript file which you are included, or in a block, you would use:
console.log(document.getElementById('name').value);
You'll probably want to hook that to some event as well, so it prints each time they do something. The "change" event is probably the most appropriate. It fires every time the user types something and then changes focus (sometimes it'll also trigger when they stop typing, but not usually). If you want it to print every time a letter changes, you would want to use (one of) the "keydown", "keyup" or "keypress" events instead.
document.getElementById('name').addEventListener('input', function() {
console.log(this.value);
});

Sure
var input = document.getElementById('name');
console.log(input.value);

Here it is with an on change event as well as a keyup (in case you need to see it somewhat 'live').
<form class="pure-form">
<input id="name" type="text" placeholder="Enter Name" onChange="inputChange(event)" onKeyUp="inputChange(event)" />
<button type="submit"><i class="fa fa-chevron-circle-right"></i></button>
</form>
<script type="text/javascript">
function inputChange(e) {
console.log(document.getElementById("name").value);
}
</script>

you can create a function like this and get the value of text box by its id.
function getData() {enter code here
let search = document.getElementById("search").value;
console.log(search);
}

Related

How to attach button values to the input form inside? [duplicate]

This question has two parts. The first takes precedence. Note I am new to HTML and JS, so please be verbose in your explanation.
1.) I have a form tag, inside which I have an input tag and a button, like so. The idea - which one may or may not be stylistically inclined to, is to have the user enter text, but bind it when clicking the button. This work:
<script>
var text;
</script>
<div>
<form>
<p>
<label>Text goes below</label>
<input id="in" type="text" placeholder="type stuff here">
</p>
<p>
<button id = "aButton" onclick="text=document.getElementById('in').value"></button>
</p>
</form>
</div>
The problem is, onclick also just feels like refreshing the page, meaning the user can no longer see what they have written down.
So question one is: how to stop this behavior (e.g. onclick only binds to the value and does not refresh the page so the text stays in the input field)
note: autocomplete="off" doesn't work
question two is how one would do this via event listening?
This code is working...
You were using button... that was causing the form to get posted... You need to use <input type="button">
I have placed your code to be called after click in a function and called that function.
<script>
var text;
function clickme() {
text=document.getElementById('in').value;
console.log(text);
}
</script>
<div>
<form>
<p>
<label>Text goes below</label>
<input id="in" type="text" placeholder="type stuff here">
</p>
<p>
<input type="button" value="Click Me" onclick="clickme()"></input>
</p>
</form>
</div>
Second part : Doing it via event listening
To do that via event listening you need to add following piece of code.
I'm using jQuery for that. Even if you don't know jQuery, i would say it's pretty much self explantory.
$('#id_of_your_button').click(function () {
//the code which you want to execute
});
//Consider using jquery... it handles cross browser issues well and makes things simpler
//or without jquery
var btn = document.getElementById("myBtn");
btn.addEventListener("click", function () {
});
Note
If you are adding event handler's via listening to event, you need to remember that you are adding the event handler code after the window load event.
$(window).load(function () {
$('#id_of_your_button').click(function () {
//the code which you want to execute
});
});
This is done to ensure that before attaching any handler to element, that particular element is present in DOM and loaded.
You should change your code as follows:
<button id = "aButton" onclick="return funcText()"></button>
<script>
var text;
function funcText() {
text = document.getElementById('in').value;
return false;
}
</script>
This will prevent the page refresh but I don't know how to do this via event listening...

I can't get form submit to work in html / JavaScript

I have tried a bunch of different things as well as searching and googling but I just can't see how to make some very basic code work.Trying to let the user submit text input.
This code below should just change the first paragraph to say working.
<HTML>
<CENTER>
<BR>
<H1>Test</H1>
<BR>
<p id="ParaOne"></p>
<BR>
<input type="text" id="TextInput" Value="" onsubmit="Test">
<script>
var CharOne = ["name"]
function Test() {
document.getElementById("ParaOne").innerHTML = "Working";
}
document.getElementById("ParaOne").innerHTML = "Enter Name:";
</script>
</HTML>
Ideally I would able to save whatever they entered into a variable and then display the entered name but as of now I can't get anything to work. not even a basic function to update the paragraph to sy working.
There is no onsubmit event for the textbox. You can use that event on the form (which I don't see in your question). Although not required, I would also add a submit button, because that's a better design.
Also it's wasteful to assign an initial value to ParaOne in JavaScript, simply type the value inside the element.
<form onsubmit="Test();">
<p id="ParaOne">Enter Name:</p>
<input type="text" id="TextInput">
</form>
<script>
function Test() {
document.getElementById("ParaOne").innerHTML = "Working";
}
</script>
Important note: Although the code above is how you should do it, I don't really see the point. The form will be submitted immediately after changing the text of ParaOne which will reload the page and you will see the initial value again (and probably think it didn't work). It will work but very fast so nobody will really see it, so what's the point?
You can use the javascript methods onchange or onkeydown to trigger input from the input field, you don't need to submit a form. But in case you needed just that I added the example. I used jQuery instead of plain javascript to write the functions because now they practically become one-line functions.
onchange will wait for the user to press enter or for the input element to loose focus to call the function.
onkeydown will call the function on every key press.
e.preventDefault() cancels the default action of the element, which in this case is a submit action, and lets us make the decision through code whether to submit or not.
Below are some javascript/jQuery test functions and a sample HTML file so you can test out what works best for you.
EDIT: I added some examples on how to store the current value of an input field into a variable
// get the Value of input element directly into a variable
var myVariable = $('#theInput_1').val();
// myVariable will return empty string since the input element is empty
console.log('This is the starting value of the 1st input element: ' + myVariable);
// Function for onkeydown test
function testKeyDown()
{
// stored in a variable which is not available outside the function
var myVariable = $('#theInput_1').val();
$('#paraOne').text(myVariable);
// test output - $('#theInput_1').val() will return empty
console.log('This is the changed value of the 1st input element: ' + myVariable);
}
// Function for onchange test
function testOnChange()
{
$('#paraTwo').text($('#theInput_2').val());
}
// Function for submit test
$( "#submit" ).on( "click", function(e)
{
e.preventDefault(); // Prevents default action of submit
$('#paraThree').text($('#theInput_3').val());
});
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<p id="paraOne">This text will be replaced on success.</p>
<input type="text" id="theInput_1" onkeydown="testKeyDown();" size="50" value="" placeholder="onkeydown test" />
<p id="paraTwo">This text will be replaced on success.</p>
<input type="text" id="theInput_2" onchange="testOnChange();" size="50" value="" placeholder="onchange test" />
<p id="paraThree">This text will be replaced on success.</p>
<form>
<input type="text" id="theInput_3" size="50" value="" placeholder="form submit test" />
<input type="submit" id="submit" value="Submit me" />
</form>
</body>
</html>

Multi Scenario Form Action (Background, Multiple Actions, Timer)

I have tried using methods that may work for one scenario or another in AJAX, Javascript, JQuery and PHP, but I have not found a way to achieve the correct results for my scenarios.
I have a search box text input field as :
<input id="field" name="q" maxlength="2048" autocomplete="off" title="Search" type="text" value="" spellcheck="false" autofocus>
There are three scenarios in which different actions need to occur:
On page load, send the input to search-api.php as POST every 5 seconds in the background, and get results back from the action and set the response equal to $url. (Must not only show response for first submit, but also for all changes in input when updated every 5 seconds).
When enter button is pressed, send the input as GET to https://externalaction.com/search in foreground.
When button <input class="button default" name="BtnX" type="submit" value="Search"> is pressed, send the input as GET to https://externalaction.com/search in foreground.
I know this is complicated but I have yet to find a solution that works for all three scenarios without interfering with each other, and no one online seems to have any information or questions quite like this situation.
Thank you to anyone who has any help, tips, or answers / code!
This doesn't seem too complicated, although I'm not sure why you'd want to send search queries every 5 seconds instead of on keypress? In any case it should just be using $.post() and setTimeout.
<form action="https://externalaction.com/search" method="get">
<input id="field" name="q" maxlength="2048" autocomplete="off" title="Search" type="text" value="" spellcheck="false" autofocus>
<input class="button default" name="BtnX" type="submit" value="Search">
</form>
<div id="results"></div>
<script>
$(function() {
search();
});
function search() {
$.post(
"search-api.php",
{ field: $('#field').val() },
function (data) {
$('#results').html(data); // or whatever format you want data in
}
);
setTimeout(search, 5000);
}
</script>
If you're interested in using keypress instead of every 5 seconds, it would be something like this for the JS:
<script>
$(function() {
$('#field').on('keyup change', 'search');
});
function search() {
$.post(
"search-api.php",
{ field: $('#field').val() },
function (data) {
$('#results').html(data); // or whatever format you want data in
}
);
}
</script>
Although in this case you don't need a named function, you could just make the search() function the keypress callback.
You also mentioned wanting to set the AJAX response to $url, however that looks like a PHP variable, so you wouldn't be able to modify that if it's in the page with the form unless you reloaded it. That's easy enough to do if you wanted to programmatically do a redirect, but would get pretty tricky and into weird loops. So it would be better to know what $url is being used for in the page, and then use JS to replace it with the value from the callback the same way I'm replacing the HTML of the results div in my current example.
The search form field will submit automatically on an 'enter' keypress as long as it has focus (i.e. after someone is finished typing in it and hits 'enter'), but if you want to send results whenever enter is pressed regardless of which input has focus this answer will help.
As an aside, typically you don't want to recursively keep searching with a timeout without some kind of end condition which clears the timeout, as in some cases it can lead to memory issues.
first of all you should search input is a form and need form tag even if it's only one input. lets consider it like this:
as you set set button type to submit. the 2 and 3 options would work.
<form id="search-form" action="https://externalaction.com/search" method="GET">
<input id="field" name="q" maxlength="2048" autocomplete="off" title="Search" type="text" value="" spellcheck="false" autofocus>
<input class="button default" name="BtnX" type="submit" value="Search">
</form>
second of all in case if in some situations (really rare) some browsers didn't work properly with type="submit" for enter button you should use jQuery like this one:
$(function() {
$("#search-form input").keypress(function (e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
$('#search-form button[type=submit] .default').click();
return false;
} else {
return true;
}
});
});
for autocomplete search you can use many exist libraries or write it yourself I recommend to read this article for an example:
http://ianlunn.co.uk/articles/ajax-search-suggest-wearehunted/
actually if you use a standard form element the only thing you are looking for is just a autocomplete search input which i believe users used to see result by typing each word instead every 5 second. but its up to you.
Edited according to your last comment:
if you have a single action for search you should at least use two different view.
to use autocomplete feature you should use ajax and if you want to have only one action or page just send an extra parameter and make a partial-view which echo result back in Json instead of a complete view which contains header and footer and ...
Function searchData() handle the AJAX request. setInterval(function(){searchData()}, 5000) section handle request search content every 5 second. If click on Enter key, then that request handle on keydown event, finally click function handle the request come through the search button.
search.php
<!--- Search field and button -->
<input id="field" name="q" maxlength="2048" autocomplete="off" title="Search" type="text" value="" spellcheck="false" autofocus>
<input type="button" name="search" id="search" value="Search"/>
<!--- Display result -->
<span id="res"></span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(e){
// function used for AJAX call
function searchData(){
var txt = $("#field").val();
$.get("searchData.php", {search: txt}, function(result){
$("#res").html(result);
});
}
// search every 5 second
setInterval(function(){searchData()}, 5000);
// if press enter button search
$('#field').on('keydown', function(e) {
if (e.which == 13) {
e.preventDefault();
searchData();
}
});
// if search button press
$("#search").click(function(){
searchData();
});
});
</script>
searchData.php - Page used to handle the request
<?php
// testing purpose
echo $_GET['search'];
?>

Clearing my form inputs after submission

I've tried it a few different ways based on searches I've done on the subject and for some reason I can't get it to work. I just want my text inputs and textarea to clear after I hit the submit button.
Here's the code.
<div id="sidebar-info">
<form name="contact-form" action="formprocess.php" method="post" target="ninja-frame">
<h1>By Phone</h1>
<p id="by-phone">XXX-XXX-XXXX</p>
<h1>By Email</h1>
<p id="form-row">Name</p>
<input name="name" id="name" type="text" class="user-input" value="">
<p id="form-row">Email</p>
<input name="email" id="email" type="text" class="user-input" value="">
<p id="form-row">Message</p>
<textarea name="message" id="message" class="user-input" rows="10" maxlength="1500"></textarea>
<p>*Please fill out every field</p>
<input type="submit" value="Submit" id="submit" onclick="submitForm()">
<script>
function submitForm() {
document.contact-form.submit();
document.contact-form.reset();
}
</script>
</form>
</div>
Your form is being submitted already as your button is type submit. Which in most browsers would result in a form submission and loading of the server response rather than executing javascript on the page.
Change the type of the submit button to a button. Also, as this button is given the id submit, it will cause a conflict with Javascript's submit function. Change the id of this button. Try something like
<input type="button" value="Submit" id="btnsubmit" onclick="submitForm()">
Another issue in this instance is that the name of the form contains a - dash. However, Javascript translates - as a minus.
You will need to either use array based notation or use document.getElementById() / document.getElementsByName(). The getElementById() function returns the element instance directly as Id is unique (but it requires an Id to be set). The getElementsByName() returns an array of values that have the same name. In this instance as we have not set an id, we can use the getElementsByName with index 0.
Try the following
function submitForm() {
// Get the first form with the name
// Usually the form name is not repeated
// but duplicate names are possible in HTML
// Therefore to work around the issue, enforce the correct index
var frm = document.getElementsByName('contact-form')[0];
frm.submit(); // Submit the form
frm.reset(); // Reset all form data
return false; // Prevent page refresh
}
since you are using jquery library, i would advise you utilize the reset() method.
Firstly, add an id attribute to the form tag
<form id='myForm'>
Then on completion, clear your input fields as:
$('#myForm')[0].reset();
You can use HTMLFormElement.prototype.reset according to MDN
document.getElementById("myForm").reset();
You can try this:
function submitForm() {
$('form[name="contact-form"]').submit();
$('input[type="text"], textarea').val('');
}
This script needs jquery to be added on the page.
The easiest way would be to set the value of the form element. If you're using jQuery (which I would highly recommend) you can do this easily with
$('#element-id').val('')
For all input elements in the form this may work (i've never tried it)
$('#form-id').children('input').val('')
Note that .children will only find input elements one level down. If you need to find grandchildren or such .find() should work.
There may be a better way however this should work for you.
You can assign to the onsubmit property:
document.querySelector('form').onsubmit = e => {
e.target.submit();
e.target.reset();
return false;
};
https://developer.mozilla.org/docs/Web/API/GlobalEventHandlers/onsubmit
$('#contact-form input[type="text"]').val('');
$('#contact-form textarea').val('');
var btnClear = document.querySelector('button');
var inputs = document.querySelectorAll('input');
btnClear.addEventListener('click', () => {
inputs.forEach(input => input.value = '');
});
btnSave.addEventListener("click", () => {
inputs.forEach((input) => (input.value = ""));
});
**Use the button you want to clear the inputs after clicking on it instead of the btnSave **
Just include this line at the end of function:
document.getElementById("btnsubmit").value = "";
I used the following with jQuery:
$("#submitForm").val("");
where submitForm is the id for the input element in the html. I ran it AFTER my function to extract the value from the input field. That extractValue function below:
function extractValue() {
var value = $("#submitForm").val().trim();
console.log(value);
};
Also don't forget to include preventDefault(); method to stop the submit type form from refreshing your page!

How not to lose focus on a login page

I have a simple login form with 2 input fields: "username" and "password".
"username" field is focused by default. The problem is that when user clicks outside "username" or "password" fields, the focus is gone (it is neither on "username" nor on "password" fields"). How can I force the focus to be on these 2 fields only ?
In my case, this is a really annoying behavior, so I really want to do this :)
Can I do something like:
$("*").focus(function() {
if (!$(this).hasClass("my_inputs_class")) {
// How to stop the focusing process here ?
}
});
?
It sounds like you always want one of your inputs to be focused, fair enough. The way I would do this is to bind each of your inputs blur() events so that if it occurs, it goes to the next element.
Here's the markup:
<body>
<form method="POST" action=".">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" name="submit" />
</form>
</body>
And here's the jQuery:
$(document).ready(function() {
// what are the named fields the user may focus on?
var allowed = ['username', 'password', 'submit'];
$.each(allowed, function(i, val) {
var next = (i + 1) % allowed.length;
$('input[name='+val+']').bind('blur', function(){
$('input[name='+allowed[next]+']').focus();
});
});
$('input[name='+allowed[0]+']').focus();
});
You could use javascript to set the focus on focusout, but you really shoudn't. Forcing focus on those fields would break the normal interaction of the page. It would mean a user couldn't do something as simple as clicking on a link on the page, because focus would always be on those inputs.
Please don't do it :)
If you really really want to do this (and you shouldn't) use delegate() instead of setting a separate event handler on every single HTML element:
$('body').delegate('*', 'focus', function() {
if (!$(this).hasClass("my_inputs_class")) {
$('#username').focus();
return false;
}
});
But consider that this will make unacessible all elements except the two input fields via keyboard navigation (including the submit button, any links on the page etc.)
Set blur event handler so it brings back focus to one of your inputs.
You could do like this (in psuedo code):
if user || pass blured
if user.len > 0
pass.setFocus
else
user.setFocus
Hope you get it.
Install an onClick handler on the body element (or a div that covers most of the page). Clicking on the div should then set the focus on the username/password field.
I also suggest to bind Return in the "username" to "Set focus on password" and Return in the "password" field to "Submit form".
You could enable the click on links by re-focusing on you inputs after a minimum time interval.
Every time an object gains the focus you check if it has the required class: if not set the focus to the first of the form inputs; this way:
<html>
<head>
<title>Example</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js" />
<script type="text/javascript" >
$(function() {
$('*').focus(function() { var obj = this; setTimeout(function () {checkFocus(obj)}, 1)});
})
function checkFocus(obj) {
if (!$(obj).hasClass('force_focus')){
$('input.force_focus:first').focus()
}
}
</script>
</head>
<body>
Extrnal link
<form><div>
User: <input type="text" name="user" class="force_focus"/><br/>
Password: <input type="password" name="password" class="force_focus"/><br/>
Other: <input type="text" name="other" class=""/><br/>
<input type="submit" name="submit" value="Login" />
</div></form>
</body>
</html>
this is only an idea, you can use a setInterval function to put the focus in the username field, and you can interrupt it when you want with clearInterval function.
var A = setInterval(function(){ $('#username').focus();}, 100);
... and for interrumpt it, you can do something like this
$('#password').focus(function(){ clearInterval(A);});

Categories