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

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...

Related

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>

How to create an HTML <input> submit button that saves all data to JS variables?

I know I can create several types of options, questions, checkboxes, and buttons using in HTML. How can I save the response a user enters and assign it to a variable? Here's the code I'm using right now:
HTML:
<input type="text" value="Hotel Name" id="questionOne"><h1 display="block">WHAT IS THE NAME OF THE HOTEL</h1><br>
<input type="button" value="HELLO" onclick="testFunction()">
JS:
function testFunction() {
prompt(document.getElementById("questionOne").value;);
}
Shouldn't it activate the function when the HELLO button is clicked, and then it identifies the response through the ID "questionOne" and creates a prompt with the variablev value? I don't understand why it's not working.
I'm new to JS and HTML so please don't go crazy if it's a simple answer. Thank you.
I think your problem is to do with where things are defined. Rather than using onclick, add an event listener in your js. e.g.
document.getElementById ("bar").addEventListener ("click", foo);
function foo() {
prompt(document.getElementById("questionOne").value);
}
and just change the button to have an id and get rid of the onclick:
<input type="button" id="bar" value="HELLO">
Well you can just add event Listener to your input.
Like
document.getElementById('questionOne').addEventListener('input',function(){
var somevariable = prompt(this.value,'');
});
That will save the answer of prompt to 'somevariable'.

How do I permanently store input from an HTML text field into a jQuery variable?

jQuery
$(document).ready(function(){
var guess;
$('#submit').on("click", function() {
guess = $('#guess-value').val();
$("#value").text(guess);
alert(guess);
});
alert(guess);
});
HTML
<div id='game'>
<form id='user-input'>
<input type='text' id='guess-value' placeholder='1-100'></input>
<button id='submit'>Submit</button>
</form>
<h4 id='guess-count'>Attempts left: <span id="attempts">6</span></h4>
</div>
<h4 id='checker'>The value entered is <span id="value">?</span></h4>
I've provided snippets of my HTML and jQuery code above. I am trying to store a number that has been entered into a text field, into a jQuery variable called guess after pressing a submit button.
The following happens occurs:
When I enter a number into the field and press submit, I get an alert showing the value I entered. After closing the event I get another alert that is supposed to show the value of 'guess' and the value is undefined.
This happens even though I declared the variable guess outside of the click event. Why is this and how do I permanently store the value?
You are using a <form> element to ask for user input. The problem with a form, is that when it submits, it wants to navigate away from (or refresh) the page. When the page refreshes, all js is lost.
Simple fix: don't use a form (you can use a DIV instead).
Alternatively, you can tell the form to NOT do its default action of submitting by using event.preventDefault():
jsFiddle Demo
HTML:
<div id='game'>
<form id='user-input'>
<input type='text' id='guess-value' placeholder='1-100'></input>
<button id='submit'>Submit</button>
</form>
<h4 id='guess-count'>Attempts left: <span id="attempts">6</span></h4>
</div>
<h4 id='checker'>The value entered is <span id="value">?</span></h4>
<input type="button" id="myButt" value="Show Value" />
jQuery:
var guess;
$('#submit').on("click", function (evnt) {
guess = $('#guess-value').val();
$("#value").text(guess);
alert(guess);
evnt.preventDefault();
});
$('#myButt').click(function(){
alert( guess );
});
Further Notes:
Note that the 2nd alert(guess) in your posted code will occur immediately upon document.ready. I mean, immediately -- as soon as the DOM is ready. Before anything has been put into guess. That is why it returns undefined.
That is probably not what you want. Code example above adds a button to allow you to view that variable's contents when desired.
The function : $("#value").text(guess) is not corret in this case, replace it with :
$("#value").empty().append(guess);
you should wait to be .ready() in order to submit();
give me feedback please. enjoy :)
The 'guess' variable is out of the click event handler but it's in the ready event handler; So the second alert box will be shown exactly once when the page is loaded. It will then be undefined. The click events will occur later.

Sending form text input to console.log for testing

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);
}

Javascript onsubmit causing page to refresh

Really simple form
<form id="addDonor" name="addDonor" onsubmit="addDonor(); return false;" action="" method="post" enctype="multipart/form-data">
<div class="sectionHeader">Add New Donor</div>
<div class="formRow"><label>Name</label> <input class="inputText fullTextBar" type="text" name="userName">
<div class="formRow"><button style="margin-left:350px; width: 80px" type="button" class="publish">Add Donor</button></div>
</form>
And the addDonor function
<script type="text/javascript">
function addDonor(){
alert("test");
return false;
}
</script>
Eventually that function will include some jquery ajax to submit the info. But, baby, steps. Right now I can't even get the alert to show up. Also, when I hit "Enter" on my keyboard, the whole page refreshes, when I press "Add Donor" nothing happens.
I'm sure it has to be a simple problem. I think it's one of those things that I just need someone else's eyes to point out.
Try assigning the onsubmit event in javascript:
document.getElementById("addDonor").onsubmit = function () {
alert("test");
return false;
}
The problem is that your function is named addDonor and your element is addDonor. Every element with an id has an object created under document to identify it. Try alert(addDonor) in the inline onsubmit to see that it alerts an HTML element, not a function. Inline functions execute in a scope chain inside document, so addDonor points to document.addDonor before it reaches window.addDonor (your function).
you should change your <button> to an <input type="submit"> (as #fireshadow52 suggested) that should fix your problem. you should try the Wc3 Schools online javascript tester to try out simple javascripts before you put it in a page, or any other one that you prefer. google has something along these lines. also, you can normally try the javascript console on your respective browser.
Your button is explicitly set to type="button", which won't make it submit the form. Change it to <button type="submit">, or to <input type="submit"> if you prefer (I like the styling options of <button> myself).

Categories