html required not working with onclick - javascript

I have the following which I use for submitting forms on my site:
<a onclick="document.forms['REGform'].submit(); return false;" class="button" href="javascript:;">Register</a>
I have inputs within the form with the required tag but this does not seem to fire them? Meaning doesn't stop empty inputs being submitted.
If I use a normal submit button it works fine by the way - is onclick not a recognised way to submit a form within html5?

The problem is the submit() method, not the use of onclick (although you can't avoid the former if you want to submit using JS instead of HTML).
Submitting using JS causes the form's validation steps to be skipped (although you can re-implement them in JS (with checkValidity()).
The submit() method, when invoked, must submit the form element from the form element itself, with the scripted-submit flag set.
— http://www.w3.org/TR/html5/forms.html#dom-form-submit
If the scripted-submit flag is not set, and the submitter element's no-validate state is false, then interactively validate the constraints of form and examine the result: if the result is negative (the constraint validation concluded that there were invalid fields and probably informed the user of this) then abort these steps.
— http://www.w3.org/TR/html5/association-of-controls-and-forms.html#form-submission-algorithm

Here is how you can do
<a onclick="CheckValidation();" class="button" href="javascript:;">Register</a>
function CheckValidation()
{
var isValidForm = document.forms['REGform'].checkValidity();
if (isValidForm)
{
document.forms['REGform'].submit();
}
else
{
return false;
}
}

<a class="button" href="javascript:document.forms['REGform'].submit(); return false;">Register</a>
or
<a onclick="document.forms['REGform'].submit(); return false;" class="button">Register</a>

Related

Using a merged array in another function

Not sure exactly how to word this but hopefully you'll get my drift. I'm trying to use my If statement to merger the contents of my images array into another array, there is then a function that uses that array to do a picture slide show.
I feel that I should mention that this is a school assignment, so I'd like to not change the chgSlide function if I don't have too.
I think my problem is that when i have var myPix=[] it clears the merger. But i'm not sure really what the solution is, i've tried just doing myPix=redCarsPic but it didn't work.
Also, within the code i commented out that ways i had merged the array, i'm not sure if a certain approach is better than an other, i'm sort of partial to the jquery and would like to be able to keep that approach if i can.
Heres my script block:
function radioCheck(){
if (document.getElementById("redCars").checked){
//alert("red"); Array.prototype.push.apply(myPix,redCarsPic);
//alert("red"); myPix.push.apply(myPix, redCarsPic);
$.merge(myPix,redCarsPic)
alert(redCarsPic+" r2");
};
if (document.getElementById("blueCars").checked){
alert("blue"); myPix.push.apply(myPix, blueCarsPic);
};
if (document.getElementById("greenCars").checked){
alert("green"); myPix.push.apply(myPix, greenCarsPic);
};
}
var myPix=[];
thisPic=0;
imgCt=myPix.length-1;
alert(myPix+"mpixalt")
function chgSlide(direction){
if(document.images){
thisPic=thisPic+direction
if(thisPic>imgCt){
thisPic=0
}
if(thisPic<0){
thisPic-imgct
}
document.myPicture.src=myPix[thisPic]
}
}
var redCarsPic =["images/redCarsA.jpg","images/redCarsB.jpg","images/redCarsC.jpg","images/redCarsD.jpg","images/redCarsE.jpg"];
var blueCarsPic =["images/blueCarsA.jpg","images/blueCarsB.jpg","images/blueCarsC.jpg","images/blueCarsD.jpg","images/blueCarsE.jpg"];
var greenCarsPic =["images/greenCarsA.jpg","images/greenCarsB.jpg","images/greenCarsC.jpg","images/greenCarsD.jpg","images/greenCarsE.jpg"];
Heres the entire code if needed:
http://pastebin.com/YLtWFciE
When you press the submit button in your form, it tries to submit your form which causes the page to be reloaded, thus reinitializing all your state back to a new page which is an empty array.
You can stop the form from submitting either by changing the button to be just a normal button, not a submit button or by block the default action of the form submission.
The simplest change is to just change this:
<input type="submit" id="submitButton" value="Go!" onclick="radioCheck()"/>
to this:
<input type="button" id="submitButton" value="Go!" onclick="radioCheck()"/>
With no submit button, the form will not be submitted and the page will not reload.
Working demo: http://jsfiddle.net/jfriend00/4bx35hjy/
FYI, it is also possible to cancel the form submission in your radioCheck() function before it occurs, but since you never want to submit the form, it seems better to just not ever have a submit button in the first place.

How exactly work this form submission JavaScript?

I am very new in JavaScript and I have the following doubt about how exactly work this script that submit a form:
So in my html I have the following form:
<form id="actionButton<%=salDettaglio.getCodice()%>" action="salwf.do?serv=1" method="post">
<button id="accept" name="ctrl" value="Accept" type="submit" class="acceptButton" onclick="sottometti(this,'<%=salDettaglio.getCodice()%>')">ACCEPT ICON BUTTON</button>
<button id="cancel" name="ctrl" value="Cancel" type="submit" class="cancelButton" onclick="sottometti(this)">CANCEL ICON BUTTON</button>
<button id="sap" name="ctrl" value="SAP" type="submit" class="sapButton" onclick="sottometti(this)">SAP ICON BUTTON</button>
<input id="testId<%=salDettaglio.getCodice()%>" name="test" type="hidden">
</form>
So the submission of this form is directed towards a page salwf.do and each time pass a parameter named serv and having 1 as value (is this a GET?)
Then inside the form I have 3 buttons having different id and different values and the input tag (that I think it is what I am submitting, is it right?)
As you can see when the user click on a button is called the sottometti(this) script that take as parameter the reference to the object that have generated the click (in this case the clicked button)
And this is this JavaScript code:
function sottometti(obj,id){
document.getElementById('testId'+id).value = obj.value;
document.getElementById('actionButton'+id).submit()
}
So how exactly work this script?
I think that it do the following thing (but I am not sure about it and maybe I am missing something).
It take 2 input parameters: the clicked button reference (obj) and the id string (that represent a code of a Java object, but this is not important now).
Using:
document.getElementById('testId'+id)
it retrieve the reference of the input tag of the form and set the value (what I want submit) with the button value (that can be: Accept or Cancel or Sap)
Then by:
document.getElementById('actionButton'+id)
retrieve my form and submit it
So the value of the clicked button will be submitted to the salwf.do servlet as POST.
Is it my reasoning correct or am I missing something?
Tnx
Yes your reasoning is correct, but you have some issues.
you only pass the ID from one of the buttons - the accept one
For all buttons you seem to want to add Accept/Cancel/SAP to a hidden field called testAccept, testCancel or testSAP and submit a form with ID actionButtonAccept, actionButtonCancel, actionButtonSAP but do not have either the field nor the form in the Cancel/SAP situation.
do not submit in a click event of a submit button
I would do
function sottometti(obj){
obj.form.test.value = obj.value;
// obj.form.submit(); // all the buttons are submit buttons
}
Be careful about one thing. Here you attach JavaScript to button[type=submit] and you execute form submit. So in fact you submit it twice.
If you want to prevent submission you should at least return false in your callback function (best is anyhow to use event.preventDefault();) like in that answer https://stackoverflow.com/a/23646215/2802756

on('submit' works when clicking the <button> but not when pressing enter on an input field

I'm using on('submit') to detect when the form was submitted, but it only works when the user clicks on the submit button.
I use a <button> tag so I can put an image inside the button. I know I could use an input with type="submit" and use CSS it with the image, but I'd like to know the alternative jQuery way.
I was thinking doing an or comparison, for example on('submit') OR when user presses enter on any of the input field, but how should I do that?
$('#form').on('submit', function (e) {
e.preventDefault();
var email = $('#email').val();
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
});
<form id="form">
<input id="email" maxlength="64" name="EmailEDIT" type="text" width="100">
<button id="submitBtn"><img height="30" src="images/fx_demo_button.png" width="74"></button>
</form>
If the user presses enter in one of the field, the form will submit. It will trigger the same event as the button does. If this does not occur, something's up in your code.
You commented that your code doesnt work, but it does: http://jsfiddle.net/B5pZ4/
All I've added was alert(1); the rest is your code from this topic
You define your function in the eventhandler, might be better to seperate that, just in case you want to use that function again (or alter it a bit and use it in two situations).
If you seperate it in your code, it'll make more sense, I also think this is the problem you're having:
http://jsfiddle.net/B5pZ4/1/
You can actually make your code work with just one line. You create the function in your eventhandler (which, in this case, should be considered bad practice!), but you never call it. Either remove the function declaration, or add this under the function:
return validateEmail( email ); // THIS IS BAD PRACTICE AS FIX!
A tip: if you're working in html5, you can use this and the browser will do validating for you:
<input type="email" />
You need to insert an invisible input type submit for this to work.

Pass name in jQuery form submission

I do not know why the following line will not function properly:
$('form[name="updateNetwork"]').unbind('submit').submit();
I can submit my form with
$("form").unbind('submit').submit();
However doing so will not pass the name attribute of the form which my backend code must identify in order to properly process the form submission. Any assistance would be greatly appreciated.
Thanks
It seems that you have only one form in your page, and that the only reason you're trying to select it with the name attribute in jQuery is so that jQuery will send the name of the form to the server.
Well, that won't work. Once you get a reference to your form via jQuery, it doesn not matter which selector you had used. If what you want is to send a name parameter to your backend code with the form name, use a hidden input inside the form:
<input type="hidden" name="form-name" value="updateNetwork" />
Then, you can get a reference to the form any way you want. The best one, as stated by #anvlasop, is to give your form an id attribute.
EDITED
You were creating the jQuery form object in a wrong way. If you have this:
<input type="submit" name="updateNetwork" />
then you can't do this:
$('form[name="updateNetwork"]).submit();
I assume that you're calling this method, submit(), inside the event handler of the submit event. Don't do that! What you should do, is to only canll preventDefault if there is an error in the validation, and let the form be sent otherwise:
//Never do this:
$('form').bind('submit', function(e) {
var valid;
//code to validate
e.preventDefault();
if (valid) $('form').unbind('submit').submit();
});
Do this:
$('form').bind('submit', function(e) {
var valid;
try {
//code to validate
} catch (error) {
valid = false;
}
if (!valid) e.preventDefault();
});
This also will prevent the sending of the form is there is an exception during validation.
You can give an id to your form. Try something like this html code:
<form id='form_id'>
//your form elements here...
</form>
Then, with jQuery you can have a reference to the form like this:
$("#form_id").unbind('submit').submit();

Adding submit event on form prevents submit parameter from being included in HTTP POST

Just what the question title says. I'm using SpringMVC, but that's irrelevant really. I just need to be able to pass the submit button name=value along with the rest of the form parameters for validation and control purposes. Example below for clarification:
The HTML I'm using:
<form action='somepage.htm' method='post'>
<input name='somename' value='bob' />
<input type='submit' name='mybutton' value='click me' />
</form>
The JavaScript (with jQuery) I'm using:
$('form').submit(function() {
$('input[type="submit"]', this).attr('disabled','disabled');
return true;
}
And so the HTTP POST request looks like this without the JavaScript event binding:
somepage.htm?somename=bob&mybutton=click%20me
And with the bound event, it excludes the button parameter as such:
somepage.htm?somename=bob
I need to be able to disable the buttons and still send the button value to the server for processing.
Thanks!
SOLUTION:
The code I actually used to solve this problem is:
$(document).ready(function() {
$('input[type="submit"]').click(function() {
var clone = $(this).clone();
$(clone).attr("type","hidden");
$(this).attr('disabled','disabled');
$(clone).appendTo($(this).parents('form')[0]);
return true;
});
});
And in case anyone was wondering, pressing Enter on a field in the form does in fact trigger the click event on the first submit button in the form!
Disabled inputs cannot be submitted.
http://www.w3.org/TR/html4/interact/forms.html#h-17.12
So maybe the way to go is to add a hidden element <input type='hidden' value='foo' name='bar'/> to stimulate the validation methods on the other end.
I think, if the submit button is clicked, then it's values will also be submitted, like rest of the form.

Categories