HTML form submission in Opera - javascript

The HTML form shown below does not work as expected in Opera (Version: 9.52). The form does not have an onsubmit attribute nor does it have an input element with type=submit. It just has two input elements of type=button and both of them onclick calls a js method where I want the user to confirm the submission. If I remove the confirm() call, it works perfectly fine. And in all other browsers (FF2, FF3, IE7) it is working fine.
Any pointers ?
<script type = "text/javascript">
function userSubmit(submitStatus)
{
// Omitted code that uses the parameter 'submitStatus' for brevity
if(confirm('Are you sure you want to submit?'))
document.qpaper.pStatus.value = something;
else
return;
document.qpaper.submit();
}
</script>
<form name = "qpaper" method = "post" action = "evaluate.page">
<input name = "inp1" type = "button" value = "Do This" class = "formbutton" onClick = "userSubmit(false)">
<input name = "inp2" type = "button" value = "Do That" class = "formbutton" onClick = "userSubmit(true)">
</form>

Never use document.nameofsomething. It's an outdated technique that has patchy support in 21st century browsers. For forms use document.forms.nameofform.
Don't use onclick on buttons unless you need Javascript to behave differently depending on which button was pressed. If you just want to validate form or confirm submission, then use <form onsubmit> instead.
<form onsubmit="return confirm('Sure?')">
And this way you don't even need form.submit(). If <form onsubmit> returns false, submission will be aborted.
You don't even need to find that form.
In <button onclick> form will be this.form.
In <form onsubmit> form will be in this variable.

Related

Console.log data from HTML form input

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>

Not able to get serialized Array of Kendo UI Form

I have a simple form, where I have a form element with one input type and button.
When I am click button, I am trying to get form data using
var fData = $("#test").serializeArray();
However for some reason, I am not able to get any values of form.
What could be the reason for this?
JSFiddle Demo
There are several issues. Firstly, the input has no name attribute, so it cannot be serialized. Secondly, you create the variable called fData, but log fdata - JS is case sensitive. Finally the form is being submit in the usual method when the button is clicked which means processing will be prevented after the first alert. To prevent this you can change the button to be a standard type, instead of a submit button:
<form id="test" method="POST">
<p>
<input id="val" name="foo" />
</p>
<button class="k-button" id="rset" type="button">submit</button>
</form>
Example fiddle
Or alternatively you can set the code to run under the submit event of the form, and use preventDefault to stop the standard form submission:
$("#test").submit(function (e) {
e.preventDefault();
alert('ok');
var fData = $(this).serializeArray();
alert('rData ' + fData);
});
Example fiddle

Check validity of as required marked fields in javascript

I do not want to perform a submit action when pressing the "submit" button on my form but rather perform some data manipulation and then submit the form using javascript form.submit - as such I do not use the <input type="submit"> element in my form:
<form action="process.php" method="post" name="myForm">
<input type="text" name="entry" id="entry" required />
<input type="button" value="Submit" onclick="manipulate_and_submit(this.form, this.form.entry);" />
</form>
With the script being something like:
function manipulate_and_submit(form, entry) {
var val = entry.value;
var hidden = document.createElement("input");
form.appendChild(hidden);
hidden.type = "hidden";
hidden.name = "m";
hidden.value = generate_other_value(val);
entry.value = "";
form.submit();
}
But before submitting I want to validate the entry and other elements of the form - I can do that manually ofc. but HTML5 gives us the required and so many other attributes - how can I simply integrate them? Is there something like form.isValid() ? Googling "validate javascript html form" just gives me examples that deal with the manual validation in javascript from "ye olde times" ...
You can use checkValidity, which is a method provided by HTMLFormElement. In your example, it would be something like if ( !form.checkValidity() ) { code here }. From MDN:
[checkValidity] Returns true if all controls that are subject to constraint validation satisfy their constraints, or false if some controls do not satisfy their constraints. Fires an event named invalid at any control that does not satisfy its constraints; such controls are considered invalid if the event is not canceled.
Source
As that says, it also fires an invalid event at every invalid form item. Then you can just make your own handler to show invalidity, like something described in this answer.

Submit and onclick not working together

<input type="submit" class="sub" onClick="exefunction2()" id="button">
When I click on the submit button onClick is not working. How can I fix this? I need to work this on submitting the form because onClick event contains values.
The best way is to call you method on the form tag like this:
<form onsubmit="return exefunction2();">
...
</form>
Returning false will not submit the form, true will submit!
to post more data (builded with exefunction2) you can use this
<script type="text/javascript">
function exefunction2(form) {
//add dynamic values
var dynValues = {
"val1": 1,
"val2": "bla"
};
for(var name in dynValues) {
//check if field exists
var input = null;
if(document.getElementsByName(name).length === 0) {
input = document.createElement('input');
input.setAttribute('name', name);
input.setAttribute('type', 'hidden');
form.appendChild(input);
}
else {
input = document.getElementsByName(name)[0];
}
input.setAttribute('value', dynValues[name]);
}
return true;
}
</script>
<form onsubmit="return exefunction2(this);">
<input type="submit" />
</form>
W3 schools has a good explanation here: http://www.w3schools.com/js/js_validation.asp
Basically, submit waits for a return value from onClick before doing anything. You can wire up a confirm() request too, if you like. If the form validates, just write something like return confirm("continue"). It's an old question, but I hope it helps anyone who stumbles across it. Another big reason for failure is a bug in your script. Unfortunately, unless you are running a debugger in your browser, it is very difficult to know what if anything is crashing your script. Turning on your browser debugger can be helpful to trace any issues. In Chrome you can use CTRL-SHIFT-I for Windows or CMD-OPTION-I for Mac. If you pause on caught errors, you can find any syntax or fatal errors that are prematurely stopping your script.
You can submit the form with Javascript.
<form id="form_id" ...>
<input type="button" class="sub" onclick="exefunction2();" id="button">
The Javascript:
function exefunction2() {
...
document.forms["form_id"].submit();
}
Well, I don't know if that's the "official" expected behavior, but that's how it works: a submit-type button will no longer submit if you add to it an onclick Javascript function. Just have the function also submit the form or have the function return false
Try <form onSubmit="exefunction2()">.
Agreeing to #silly , I used the same idea . I am sharing the implementation. My objective was , to disable a button "Execute" which is used to submit a form , until a response is received , upon which , the "execute" button should be enabled again. I am using Flask .
My Form:
<form onsubmit="return disableExecuteButton();" method="POST" action="/dothis">
.....
</form>
My JS:
function disableExecuteButton(){
var executeButton = document.getElementById("executeButton");
executeButton.setAttribute("disabled","disabled");
return true;
}
function reactivateExecuteButton(){
var executeButton = document.getElementById("executeButton");
executeButton.setAttribute("disabled","enabled");
}
From Flask, I return:
return render_template('result.html', message=message, error=error, html_content=result, history=session['actions_taken'], done=True)
The "done=True" , is what I use to indicate, that the response is received and we need to enable the button again.
To re enable the button:
{% if done %}
<script type="text/javascript">
reactivateExecuteButton()
</script>
{% endif %}
Change the event to onsubmit, and return false to avoid the form to be submitted.
<input type="submit" class="sub" onsubmit="exefunction2();return false;" id="button">

nested html FORM is inaccessible - multiple forms problem

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!

Categories

Resources