https://codepen.io/anon/pen/NYaeXV
I am trying to log the value of a HTML form input. I put multiple options inside the CodePen. Here is my initial thought process.
<form action="">
<input type="text" name="data" id="data">
<button type="submit">Submit</button>
</form>
function sConsole() {
var data = document.getElementById("data");
console.log(data.value());
}
sConsole();
You need to use value instead of value() since value is not a function , also consider using e.preventDefault() to avoid the page reload one more thing , by adding sConsole() into your js file you're asking the function to be executed when the page load, you need to move your function to the submit event instead.
Here is a working example and Happy coding :)
function sConsole(event) {
event.preventDefault();
var data = document.getElementById("data");
console.log(data.value);
}
<div id="container">
<h1>Hello, world!</h1>
<h4>Input your console data below : </h4>
<form action="" id="form" onsubmit="sConsole(event)">
<input type="text" name="data" id="data">
<button type="submit">Submit</button>
</form>
</div>
You missed onclick or onSubmit , you should also use .value
function sConsole() {
var data = document.getElementById("data");
console.log(data.value);
//!!Option 1a
//console.log(data.submit());
}
<div id="container">
<h1>Hello, world!</h1>
<h4>Input your console data below : </h4>
<form action="">
<input type="text" name="data" id="data">
<button type="submit" onClick="sConsole()">Submit</button>
</form>
</div>
You were close, just a few things to consider.
Getting the value of an input field
The value attribute of an input element stores the text in the textbox. To retrieve, this in javascript, use ExampleElement.value, for example:
var dataValue = document.getElementById("data").value;
or
var data = document.getElementById("data");
var dataValue = data.value;
You can also specify the value attribute in the input tag with value="". This is useful if you want to prefill the input text box, for instance, if you send the user input to a php script for action and wanted to return the textbox with information already included.
Calling a Javascript Function
There are multiple ways to call a javascript function, including doing so when certain events occur. In your situation, you probably want the input value logged every time the user clicks submit. You could add an event listener, but for simplicity sake of understanding, let's just use inline code. Every time they submit, let's log it, so onsubmit="sConsole();". Now the submit action will run your logging function.
If you wanted to log every change while the user was typing, you would use an event listener with more complex evaluation of the input value.
Prevent Default
It's likely that you don't want the form to actually be submitted to the server and page reloaded every time the user clicks submit. By using event.preventDefault();, javascript prevents the usual action of submitting the form to the server and instead leaves the user input and the page as is.
If you want the textbox to be "erases" after each submit, it's probably best to reset the value in your function rather than submitting the form. To reset the value, you would simply do data.value = "".
Code Example
Putting it all together, here's an example code segment with comments about your original sample.
<form action="" onsubmit="event.preventDefault(); sConsole();"> <!-- use inline JS to print input to console on submit -->
<input type="text" name="data" id="data">
<button type="submit">Submit</button>
</form>
<script>
function sConsole() {
var data = document.getElementById("data");
console.log(data.value); // data is the element, and we want its value
}
//sConsole(); This would call it only on script load, which isn't what you want
</script>
Related
I have the following HTML code:
<html>
<!-- assume jquery is loaded -->
<body>
<form id="sform" method="get" style="display:none;">
<input type="hidden" name="eid" />
<input type="hidden" name="returnURL" />
<input type="hidden" name="returnID" value="ieid" />
<select id="dropdownlist" name="ieid">
<option selected="selected"></option>
</select>
</form>
</body>
</html>
What happens is the user enters an email address, it checks (server-side with PHP) the credentials and if valid, returns the following JSON object (in this case, assume that the values are valid urls (ie. http://sitehere.com/somethingelse):
{
"get_action" : "geturl",
"eid" : "eidurl",
"return_url" : "returnurl",
"option_url" : "optionurl"
}
This is retrieved when the user hits the login button on the home page. This button triggers a POST request which retrieves the results and parses the JSON into the form above. I then change the values of the form from the original code and the action of the form itself before submitting the form. This is shown below.
$.post('/?c=controller&a=method', {'email' : $('input[name="email"]').val() }, function(data){
var result = $.parseJSON(data);
$('#sform').change_action(result.get_action);
$('input[name="eid"]').change_val(result.eid);
$('input[name="returnURL"]').change_val(result.return_url);
$('select[name="ieid"]').find('option:selected').change_val(result.option_url);
$('#sform').submit();
};
Where change_val() and change_action() are defined like this:
$.fn.change_val = function(v){
return $(this).val(v).trigger("change");
}
$.fn.change_action = function(v){
return $(this).attr('action', v).trigger("change");
}
The reason why I defined these functions was because originally, I had just been calling val('new value'); and the form seemed to not be updating at all. I read that I had to trigger a change when using jQuery to update the form before submitting it.
However, even after triggering a change, it seems like the HTML still isn't updated (at least in Chrome) and the form is not being submitted correctly because none of the values are actually changing.
So, I need to be able to take a parsed result, update the values in the form (with specific id's), and then submit the form so that it re-directs somewhere. Is there a way to do this correctly?
I have two forms. I want to submit both forms with 1 button. Is there any method that can help me do it?
Example:
<form method="post" action="">
<input type="text" name="something">
</form>
<form method="post" action="">
<input type="text" name="something">
<input type="submit" value="submit" name="submit">
</form>
I want both forms to be submitted with 1 submit button. Any help would be appreciated.
The problem here is that when you submit a form, the current page is stopped. Any activity on the page is stopped. So, as soon as you click "submit" for a form or use JavaScript to submit the form, the page is history. You cannot continue to submit another page.
A simplistic solution is to keep the current page active by having the form's submission load in a new window or tab. When that happens, the current page remains active. So, you can easily have two forms, each opening in a window. This is done with the target attribute. Use something unique for each one:
<form action='' method='post' target='_blank1'>
The target is the window or tab to use. There shouldn't be one named "_blank1", so it will open in a new window. Now, you can use JavaScript to submit both forms. To do so, you need to give each a unique ID:
<form id='myform1' action='' method='post' target='_blank1'>
That is one form. The other needs another ID. You can make a submit button of type button (not submit) that fires off JavaScript on click:
<submit type='button' onclick="document.getElementById('myform1').submit();document.getElementById('myform2').submit();" value='Click to Submit Both Forms'>
When you click the button, JavaScript submits both forms. The results open in new windows. A bit annoying, but it does what you specifically asked for. I wouldn't do that at all. There are two better solutions.
The easiest is to make one form, not two:
<form action='' method='post'>
<input type='text' name='text1'>
<input type='text' name='text2'>
<input type='submit' value='Submit'>
</form>
You can place a lot of HTML between the form tags, so the input boxes don't need to be close together on the page.
The second, harder, solution is to use Ajax. The example is certainly more complicated than you are prepared to handle. So, I suggest simply using one form instead of two.
Note: After I submitted this, Nicholas D submitted an Ajax solution. If you simply cannot use one form, use his Ajax solution.
You have to do something like that :
button :
<div id="button1">
<button>My click text</button>
</div>
js
<script>
$('#button1').click(function(){
form1 = $('#idIFirstForm');
form2 = $('#idISecondForm');
$.ajax({
type: "POST",
url: form1.attr('action'),
data: form1.serialize(),
success: function( response ) {
console.log( response );
}
});
$.ajax({
type: "POST",
url: form2.attr('action'),
data: form2.serialize(),
success: function( response2 ) {
console.log( response2 );
}
});
});
</script>
You could create a pseudo form in the background. No time to write the code, jsut the theory. After clicking submit just stop propagation of all other events and gather all the informations you need into one other form you append to document (newly created via jquery) then you can submit the third form where all the necesary infos are.
Without getting into why you want to use only 1 button for 2 forms being submitted at the same time, these tools that will get the input data available for use elsewhere:
Option 1...
Instead of using <form> - collect the data with the usual Input syntax.
ex: <input type="text" name="dcity" placeholder="City" />
Instead of using the form as in this example:
<form class="contact" method="post" action="cheque.php" name="pp" id="pp">
<label for="invoice">Your Name</label>
<input type="text" id="invoice" name="invoice" />
<button class="button" type="submit" id="submit">Do It Now</button>
</form>
use:
<label for="invoice">Your Name</label>
<input type="text" id="invoice" name="invoice" />
<button type="button" onclick="CmpProc();" style="border:none;"><img src="yourimage.png"/> Do It Now</button>
Then code the function CmpProc() to handle the processing/submittion.
Inside that function use the Javascript form object with the submit() method as in...
<script type="text/javascript">
function submitform() {
document.xxxyourformname.submit();
}
</script>
Somehow I suspect making the two forms into one for the POST / GET is worth reconsidering.
Option 2...
Instead of POST to use the data to the next page consider using PHP's $_SESSION to store each of your entries for use across your multiple pages. (Remember to use the session_start(); at the start of each page you are storing or retrieving the variables from so the Global aspect is available on the page) Also less work.
Look man. This is not possible with only HTML. weither you gether the inputs in one form or else you use jquery to handle this for you.
I am creating a page that is only javascript and html. I have 2 problems.
When it calls the function inputs() in this form, it fails at the first time and success on the next submissions.
<div id="container">
<form onsubmit="inputs()" action="#">
Variables: <input type="number" id="vars" size="1" required/>
Constraints: <input type="number" id="cons" size="1" required/>
<input type="submit" value="Submit">
</form>
</div>
I wasnt able to solve this but I skipped it because it still proceeds to the inputs() the next submissions.
But in my inputs(), i created a form dynamically. The form is created as this:
var form = document.createElement("form");
form.setAttribute("action","#");
form.setAttribute("onsubmit","solve()");
Now, when I submit the dynamically created form, the problem is it goes back to the first set of form. solve() was not called.
Why is it? What should be edited?
Thanks for the help in advance.
solve() has these lines of codes. It's just a test if it will successfully go into it but it fails. This just deletes all the elements.
var container = document.getElementById("container");
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
This line
form.setAttribute("onsubmit","solve()");
isn't doing what you think it does. If it was in the actual html it would work but not now. What it does is just make the attribute appear in the console. The event handler isn't actually being set.
Instead do it via onsubmit property or addEventListener
form.onsubmit = solve; // now it must work
Try return false at the end of the function solve. this should work to show but would not perform action. Also add "return solve()" instead of "solve()".
I'm trying to run a JS method with a custom text variable as a parameter. I need to be able to write some text in a form, and then send that value to the method to execute it. I'm not sure why it's not working - it seems to be receiving the value of the VALUE as "" or blank. How would I go about doing this?
<FORM NAME="myform" ACTION="" METHOD="GET">
Choose a Place: <INPUT TYPE="text" NAME="inputbox" VALUE="" id = "place"><P>
</FORM>
<button type="button" onclick="buttonGenerator()">Generate Postcard</button>
<script>
var x = document.getElementById('place').value;
function buttonGenerator(){
generate(x);
}
</script>
Your x variable is being set when the script first runs (when the page is loading). You want to avoid setting it until the button is clicked. Simply move it into the function and you should be set:
function buttonGenerator(){
var x = document.getElementById('place').value;
generate(x);
}
Here is the scenario, I have 3 html forms on a page and they look like
form1() form2(form3())
a dummy program to test out the 3 forms
__
<script language="javascript" type="text/javascript">
function submitthisform(no){
document.forms[no].submit;
}
</script>
<form action="http://cnn.com" name="1">
<input type=submit value="cnn" onclick="submitthisform('1')" name='submit1'>
</form>
<form action="http://google.com" name="2">
<form action="http://yahoo.com" name="3">
<input type=submit value="yahoo" onclick="submitthisform('3')" name="submit3">
</form>
<input type=submit value="google" onclick="submitthisform('2')" name="submit2">
</form>
now when i do submit3, the onclick function gets called, where I try to submit the form3 because otherwise it always submits the form 2
in onclick, I send the form name. But form3 seems to be inaccessible. Reason is, if i traverse all the forms on the page, it doesnt return form 3 but only form 1 & 2
var forms = document.getElementsByTagName("form");
for (var i=0; i<forms.length; i++){
alert('form'+i+' = '+forms[i].name);// displays name of form1&2
}
it also gives javascript err on click submit2.
try this small code and u will get the idea.
tell me if i can submit form 3!!!!
According to XHTML specs
form must not contain other form elements.
So please do not do this as you can not guarantee compatibility across browsers (current or future)
My solution: deactivate the parent form by moving all children into a new div. In fact, I change the form element´s type to div.
Here my code snippet tyken from a Vue.js method:
let target = document.createElement('div');
let source = document.getElementById(this.parentFormId); // change this!
source.parentNode.insertBefore(target,source);
source.childNodes.forEach(node => {
node.parentNode.removeChild(node);
target.appendChild(node);});
source.parentNode.removeChild(source);
target.id = this.parentFormId;
The nested form markup ist pasted in dynamically via computed property to avoid conflicts. Optionally, if the outer form needs to be restored, the form-attributes can by copied too. For my purpose, this is not necessary.
Maybe a hack, but it works well!