I have the following search form:
<form method="get" action="SearchResults.asp" id="frmSearch" name="frmSearch">
<input id="q" name="q" type="text" size="50" />
<input type="submit" value="Search" id="button1" name="button1" />
</form>
I add Javascript to the form submit event using the following:
window.onload = function(){
var frm = document.getElementById("frmSearch");
if (window.addEventListener){
frm.addEventListener('submit',function() {validate(frm);} ,false);
}else if (window.attachEvent){
frm.attachEvent('onsubmit', function() {validate(frm);} );
}
}
The validate function is as follows:
function validate(frm) {
alert(frm.id);
var inputs = frm.getElementsByTagName("input");
alert(inputs[0].id);
alert(frm.getElementById("q"));
if (frm.getElementById("q").value=='') {
alert("Please enter your search terms.");
frm.getElementById("q").focus();
return false;
}
frm.getElementById("button1").disabled = true;
return true;
}
The validate function runs but apparently errors out as Javascript ignores the line
frm.getElementById("q")
because alert(frm.id); returns form id "frmSearch", alert(inputs[0].id) returns "q" which is the id of the textbox, but alert(frm.getElementById("q")) does not display anything at all, not even empty alert box.
Can anyone help me diagnose the issue?
getElementById is a method of document, not every HTML element. You'd need to call document.getElementById().
Related
When the submit button is pressed, my validation function should check if the fields are validated then call the setProfile method. currently when i click the submit button it will not validate my fields so something must be wrong
<form name="Login" method="post" action="#" onsubmit="return validateForm()">
<input type="text" name="fName" id="name"> <br>
</form>
<input type="submit" name="Update" value="Update">
function validateForm() {
var n = document.forms['Login']['fName'].value;
if(n==null || n=="")
{
alert("Please enter your name");
return false;
}
return true
}
function UpdateProfile() {
document.querySelector('submit').addEventListener('click', e=>{
const myProfile = new Profile
if (e.validateForm === true){
myProfile.setProfile();}
})
}
The most likely reason for your code not working is that your validateForm() function is not getting called at all on submit button press. To find out if that's the case, the simplest thing to do is to add an alert() at the top of the validateForm() function.
If it's indeed not called, google "call javascript function on button click" for a code sample. Here's one: Using an HTML button to call a JavaScript function
I'm trying to do a form and while the alert is popping up it is still submitting. How do I get it to stop submitting??
function validate() {
var first = document.register.first.value;
if (first == "") {
alert("please enter your name");
first.focus();
return false;
}
return (true);
}
<body>
<form name="register" action="testform.php" onsubmit="return(validate());">
<input type="text" name="first" />
<button type="submit" />Submit
</form>
</body>
You added the parenthesis on return() then return(validate()) which we use () when calling the function so it might be considering return a custom function which returns undefined and when returned the undefined it ignores and continue the execution.
How ever the validate is called but it's response is not returned to the form.
Fixed version:
<head>
<script>
function validate(e) {
var first = document.register.first.value;
console.log(document.register.first)
if( first == "" ) {
alert( "please enter your name" ) ;
return false;
}
return(true);
}
</script>
</head>
<body>
<form name="register" action="testform.php" onsubmit="return validate()">
<input type="text" name="first" />
<button type="submit" >sbmit</button>
</form>
</body>
You are better of using the required attribute on the front end of things. It will 'force' the user to input text into the input field before it is able to submit. Please note that I put quotation marks around the word 'force', because one can just edit the HTML and circumvent the HTML required attribute. Therefore make absolutely sure that you are validating user input on the PHP side as well.
Many tutorials and examples exist for PHP Form Validation, such as this one from W3Schools and this one from Medium.
<form name="register" action="testform.php">
<input type="text" name="first" required/>
<input type="submit" value="Submit"/>
</form>
You have several bugs in your code.
<button> element is not self-closing
you are calling focus on value of the input instead of the input element which throws exception
function validate() {
var input = document.register.first;
var text = input.value;
if( text == "" ) {
alert( "please enter your name" ) ;
input.focus();
return false;
}
return true;
}
I think the issue is with the button's type="submit". Try changing it to type="button", with an onclick function that submits your form if validate() returns true.
edit: Arjan makes a good point, and you should use required. But this answers why the form was submitting.
I am working on jquery validation with form action php submit. I created jquery validation using click function first time it's validate the input field on second click it's redirecting to form action url. How to prevent this using client side validation. How can i solve this.
<form action="test.php" method="post">
<input class="qemail" name="your-email-address" placeholder="Your email address" value="" type="text">
<textarea class="qmessage" name="your-enquiry" rows="8" placeholder="Your message"></textarea>
<input id="submit_sf" name="enquiry-submit" value="SUBMIT" type="submit">
</form>
$(document).ready(function(){
$('input[name="enquiry-submit"]').click(function(){
var email = $('.qemail').val();
var msg = $('.qmessage').val();
var email_regex = /^(([^<>()\[\]\\.,;:\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,}))$/;
if(!email.match(email_regex) || email.length == 0 ){
if ($('.qemail').prev(".rvalidation").length == 0){
$('.qemail').before('<p class="rvalidation" style="position:relative; color: #000; font-size:12px;">Please enter a valid Details *</p>');
$(".qemail").focus();
console.log("email field is empty");
$(".qemail").focus();
//console.log("validate1"); \
return false;
}
//return false;
}
if(msg.length == 0){
console.log("message field is empty");
return false;
}
});
});
change type = "button"
<button id="submit_sf" name="enquiry-submit" value="SUBMIT" type="button">Submit</button>
The function() within the .click event can accept an argument for the event handler.
$('input[name="enquiry-submit"]').click(function(ev) { ...
You can use ev.preventDefault(); to keep the post from actually occurring until validation has passed. You'll need to manually trigger the form post though.
$('input[name="enquiry-submit"]').click(function(ev) {
ev.preventDefault();
...
}
I'm including this form using ajax:
<form action="" method="post">
<input type="number" name="user_id" placeholder="user id" id="user_id_input"/>
<input type="submit" value="update">
</form>
My code:
$.get("application/views/beheer/html/"+widgetName+"div.html", function(response){
$widgetDiv.html("<div class=\"widget_"+widgetName+"\" id=\""+widgetArray.length+"\">"+response+"</div>");
var $form = $(".widget_"+widgetName).find("form");
$form.submit(function( event ){
UpdateObjectSettings($form);
return false;
});
});
function UpdateObjectSettings($form){
//var id = $form.parent().attr("id");
//widgetArray[(id - 1)].Update($form);
return false;
}
If I enter an alert inside the $form.submit it still works.
If I decomment the lines inside the UpdateObjectSettings the return false inside the submit won't work.
Thanks for any help.
Check the error console for errors - my guess is the second line in UpdateObjectSettings is throwing an error.
I want to check a form if the input values are empty, but I'm not sure of the best way to do it, so I tried this:
Javascript:
function checkform()
{
if (document.getElementById("promotioncode").value == "")
{
// something is wrong
alert('There is a problem with the first field');
return false;
}
return true;
}
html:
<form id="orderForm" onSubmit="return checkform()">
<input name="promotioncode" id="promotioncode" type="text" />
<input name="price" id="price" type="text" value="€ 15,00" readonly="readonly"/>
<input class="submit" type="submit" value="Submit"/>
</form>
Does anybody have an idea or a better solution?
Adding the required attribute is a great way for modern browsers. However, you most likely need to support older browsers as well. This JavaScript will:
Validate that every required input (within the form being submitted) is filled out.
Only provide the alert behavior if the browser doesn't already support the required attribute.
JavaScript :
function checkform(form) {
// get all the inputs within the submitted form
var inputs = form.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
// only validate the inputs that have the required attribute
if(inputs[i].hasAttribute("required")){
if(inputs[i].value == ""){
// found an empty field that is required
alert("Please fill all required fields");
return false;
}
}
}
return true;
}
Be sure to add this to the checkform function, no need to check inputs that are not being submitted.
<form id="orderForm" onsubmit="return checkform(this)">
<input name="promotioncode" id="promotioncode" type="text" required />
<input name="price" id="price" type="text" value="€ 15,00" readonly="readonly"/>
<input class="submit" type="submit" value="Submit"/>
</form>
Depending on which browsers you're planning to support, you could use the HTML5 required attribute and forego the JS.
<input name="promotioncode" id="promotioncode" type="text" required />
Fiddle.
Demo: http://jsfiddle.net/techsin/tnJ7H/4/#
var form = document.getElementById('orderForm'),
inputs=[], ids= ['price','promotioncode'];
//findInputs
fi(form);
//main logic is here
form.onsubmit = function(e){
var c=true;
inputs.forEach(function(e){ if(!e.value) {c=false; return c;} });
if(!c) e.preventDefault();
};
//findInputs function
function fi(x){
var f = x.children,l=f.length;
while (l) {
ids.forEach(function(i){if(f[l-1].id == i) inputs.push(f[l-1]); });
l--;
}
}
Explanation:
To stop submit process you use event.preventDefault. Event is the parameter that gets passed to the function onsubmit event. It could be in html or addeventlistner.
To begin submit you have to stop prevent default from executing.
You can break forEach loop by retuning false only. Not using break; as with normal loops..
i have put id array where you can put names of elements that this forum would check if they are empty or not.
find input method simply goes over the child elements of form element and see if their id has been metnioned in id array. if it's then it adds that element to inputs which is later checked if there is a value in it before submitting. And if there isn't it calls prevent default.