This question already has answers here:
HTML form action and onsubmit issues
(3 answers)
Closed 3 years ago.
i know there are other questions like mine but before you mark it as a duplicate could you please read it.
i am trying to validate my html form using javascript.
i have done this before in another web page and it worked correctly however i am trying to use the same code for my new page but it does not work.
this is the code:
function validateForm(form) {
var valid = true;
if (!form.title.value.length)
{
valid = false;
document.getElementById('titleRequired').style.display = "inline-block";
}
else
{
document.getElementById('titleRequired').style.display = "none";
}
}
<form id="form" action="register.php" method="post" onsubmit="return validateForm(this)">
<h2> create profile: </h2>
<div>
<label for="fname">First Name</label>
<input type="text" id="fname" name="fname" placeholder="Given Name">
<span class="error" id="fNameRequired">first name required</span>
<span class="error" id="capitalRequired">first letter must be capital</span>
</div>
<div>
<input type="submit" value="Submit" name="submit" >
</div>
</form>
i have more inputs for this form however i am doing it step by step and not sure where i am going wrong.
i have this exact same code on another project i worked on with more inputs and it works fine.
the output i am currently getting is: it submits the form as normal even when no text is entered.
You're not returning the result of the validation. Add return valid; before the last curly brace to return false or true so the submit handler knows what to do.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Below is my HTML code of form where I used Form button outside the form and its working fine for me..and the value of my field is fetching from Mysql Like Status is Active, Passive or Dead what I am looking for is my form will execute only if the fetching input value equals to Passive or Dead Only Totally Don't Know What to Do.
<input type="submit" form="nameform" value="Admit Student" style="margin-right: 16px" name="admit" />
<form action="/student/create" method="get" id="nameform">
<div class="row">
<div class="col-sm-4">
<div class="form-group" style="display:none;">
<label>Current Status</label>
<input type="text" value="<?php echo $enquiry_data['status']; ?>" name="status" class="form-control">
</div>
</div>
</form>
Try this, using onsubmit="return validateForm()" on your form to validate your input field.
function validateForm() {
var current_status = document.forms["nameform"]["status"].value;
var default_value = ['passive', 'dead'];
if (!default_value.includes(current_status)) {
alert("You are not allowed to continue");
return false;
}
}
<input type="submit" form="nameform" value="Admit Student" style="margin-right: 16px" name="admit" />
<form action="/student/create" method="get" id="nameform" onsubmit="return validateForm()">
<div class="row">
<div class="col-sm-4">
<div class="form-group" >
<label>Current Status</label>
<input type="text" value="" name="status" class="form-control">
</div>
</div>
</form>
There are plenty of ways to do this, best would be, do not send form request via the form, use Javascript to validate on click of button, then send form data, something like this easiest way
var request = new XMLHttpRequest();
request.open("POST", "http://example.com/submitform.php");
request.send(formData);
Something like this?
$("#nameform").on("submit",function(e) {
const val = $("[name=status]").val().trim();
console.log(val)
if (val==="" || "Active" === val) e.preventDefault();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="submit" form="nameform" value="Admit Student" style="margin-right: 16px" name="admit" />
<form action="/student/create" method="get" id="nameform">
<div class="row">
<div class="col-sm-4">
<div class="form-group" style="display:none;">
<label>Current Status</label>
<input type="text" value="Active" name="status" class="form-control" />
</div>
</div>
</div>
</form>
If I got your question correctly, you will likely have to set/get that value through javascript on an event.
I assume what you want to do is: perform an action automatically the moment value is retrieved (if it fits your condition) and not on user action, such as button click.
Fetch your data into a javascript code. Following question answers might be helpful with that How do I pass variables and data from PHP to JavaScript?.
From that point enter those values into the form field. An answer to This question has info on how to do that.
If you get the values you want THEN trigger whatever action you want to trigger.
mplungjan's answer should work if you want to perform your actions on form submission (when the user clicks a button or something).
As a side note: if you clarify exactly what you expect to achieve (for example: is it something should execute automatically when the page loads OR do you just need to validate a value) you might get a more specific answer - perhaps even a better solution to your problem. If you only need validation then my solution is an overkill at this point.
This question already has answers here:
Stop form refreshing page on submit
(20 answers)
Closed 4 years ago.
I did this JS component but in some pages as codepen it crashes when I click submit because the the button adds a "?#" to the URL (running locally) and is like it changes to another page, this happens the first time I post a message, can be avoided? or is a normal thing of submit?
<div id = "typeSection">
<label for="message">Message:</label>
<form action="#" id="typeForm">
<label for="message"></label>
<textarea id= "character">0/280.</p>
<input type="submit" id = "addButton" value="Submit">
This is the component running in CodePen:
https://codepen.io/LeonAGA/pen/vroRBB
when you add 'action="#"' in the form tag below:
<form action="#" id="typeForm">
it redirects the page to the current url with a "#" appended on to the end. If you put:
<form action="" id="typeForm">
you shouldn't have to worry about the "#" anymore.
<form action="#" id="typeForm">
Action value might be the reason why adding # after the URL, try assign "" instead of # symbol
This question already has answers here:
Remove query string "?" in HTML form method GET
(2 answers)
Closed 4 years ago.
I have a simple image search form that open in a new window:
HTML
<input type="radio" id="google" name="image" onclick="googleImages();" checked/>
<label for="google">Google Images</label>
<input type="radio" id="unsplash" name="image" onclick="poly();"/>
<label for="unsplash">Poly</label>
<form id="form" method="GET" action="https://www.google.com/search?q=">
<input id="input" type="text" name="q" value="" required>
<input id="button" type="submit" value="Search" onclick="this.form.target='_blank';">
<input id="helper" type="hidden" name="tbm" value="isch">
</form>
JS
var
form = document.getElementById("form"),
input = document.getElementById("input"),
button = document.getElementById("button"),
helper = document.getElementById("helper");
function googleImages() {
form.action="https://www.google.com/search?q=";
input.name="q";
helper.name="tbm";
helper.value="isch";
}
function poly() {
form.action="https://poly.google.com/search/";
input.name="";
helper.name="";
helper.value="";
}
Code working here
PROBLEM
When I change to Poly in my search form, query string continue set "?" in URL output, generating an error on search results page.
Google Images use some URL parameters like google.com/search?q=lion&tbm=isch that I can reproduce in the form. However, Poly not use query string (?) or parameters (param=value) they just use the "URL/value" like poly.google.com/search/lion
QUESTION
How create a function that when I select Poly the query string "?" is removed generating an output "URL/value" on submit? In other words, pass the search term (value) as part of the URL without any query or parameters.
It looks like for the poly you are just navigating to a different url. You don’t want or need this to be a form submission. Instead of submitting a form call window.location.href= in the JavaScript.
This question already has answers here:
HTML text input allow only numeric input
(78 answers)
Closed 6 years ago.
Trying to limit the user to only enter numbers in a text field.
I am assuming you're talking about FORM in HTML.
There are several ways to do that:
Input type
As Alexander proposed, you can set the input type to number.
For example, in this form the user is required to provide his/her ID number before submitting. Please note that, the type is set to number.
<!DOCTYPE html>
<html>
<body>
<form action="action_page.php">
ID Number:<br>
<input type="number" name="id" value="0">
<br><br>
<input type="submit">
</form>
</body>
</html>
Javascript
you can set a javascript function that validates the input on-submit.
<script>
function validateForm() {
var x = document.forms["myForm"]["id"].value;
if (x == null || x.search(/^\d+$/i) < 0) {
alert("ID must be a number");
return false;
}
}
</script>
<form name="myForm" action="demo_form.php"
onsubmit="return validateForm()" method="post">
ID: <input type="text" name="id">
<input type="submit" value="Submit">
</form>
Here is another example on W3Schools
AngularJS
There is a lot of buzz around AngularJS and I assume you may want to go there in some point.
Fortunately, the AngularJS documents regard that subject are pretty understandable and straightforward or at least to me.
Here are some examples:
Input directive
AngularJS API Ref - input
I've just started programming and I'm at a very basic level, I've just created a form for my student website and I'm trying to validate the Radio Buttons. I know I can just select "checked" in the HTML code but my tutor stipulates it has to be within the JavaScript code. I have researched on here already but the examples many of you have shown haven't worked for me (my fault!) and it just crashes all my previous validations.
Any guidance from all you ninjas is greatly appreciated. Here is a small sample of my code that does work for me as I have deleted the Radio Button validation in frustration, I just want to know how to adapt this code:
<script>
function validate(){
firstname = document.getElementById("txtFirst").value;
errors = "";
if (firstname == ""){
errors += "Please supply a valid First Name \n";
} else if (!firstname.match(/^[a-zA-Z-\s]*$/)){
errors += "Please use only letters in your First Name \n";
}
}
</script>
<body>
<form method="post" action="" class="booking">
<fieldset>
<div>
<label for="txtFirst" class="fixedwidth">First Name</label>
<input type="text" name="txtFirst" id="txtFirst"/>
</div>
<div class="buttonarea">
<input type="submit" value="submit" onclick="validate()"/>
</div>
</fieldset>
</form>
I recommend jQuery for this as you only would need to check $('element').val(). In JavaScript you have to check document.getElementById('element').value. Remember to match both name and id properties for this to work as you can only select one value in a set of radioboxes.