I need to set a form input value to -1 when submitted if nothing is entered.
So far I have this function, but it doesn’t change the value to -1.
<form action="validate.php"
method="post" onsubmit="return validate()" >
<input type="text" name="CategoryID" size="3" maxlength="3" onkeyup="checkCategoryID(this)"/>
function validate()
{
var catID;
catID = document.getElementsByName("CategoryID");
if (catID.value == "")
catID.value = -1;
return true;
}
There are a number of issues with your code. First, JavaScript code should either be included in a separate javascript file or embedded inside script tags.
Second, you'll want to use return false instead of return true.
Also, the default behavior of a form, is for it to be submitted. You might want to pass in a parameter event and use the event.preventDefault method.
Also, getElementsByName returns a collection not a single element. You need to pass in an index like so
getElementsByName("categoryID")[0];
The form tag requires the closing tag </form>.
catID.value == "" is searching for an empty string. You can use a boolean instead. It's equivalent to !catID.value
Here is my temporary solution.
<form action="validate.php"
method="post" onsubmit="validate()" >
<input type="text" name="CategoryID" size="3" maxlength="3" onkeyup="checkCategoryID(this)"/>
</form>
<script>
var catID = document.getElementsByName("CategoryID")[0];
function validate() {
if (!catID.value) {
catID.value = -1;
return false;
}
}
</script>
Related
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 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().
I can't get a form to validate no matter what I try, so I have dumbed it down alot to see if I could get ANYTHING to work, and still when I submit the form the javascript does not validate, and simply sends me to the next page no matter what. You guys see anything wrong??
HTML
<form id="myform" action="/" method="post" onsubmit="return Validate()">
<input id="form_name" type="text" name="name" placeholder="Name" />
<div id="error">Name too short</div>
<input type="submit" id="submit" name="submit" value="Enter" />
JAVASCRIPT IN HEAD
<script language="JavaScript" type="text/javascript">
function Validate() {
if (form.name.value == "") {
$('#error').show();
return false ;
}
return true ;
}
</script>
And in the CSS I have the display for the #error div set to none.
Ultimately I want to check that the user entered at least 4 characters in the text input field, if they didnt then I don't want the form submitted but rather show the error message. But for now I'm just checking to see if its empty to see if I can get anything to work. Any ideas?
First of all remove language from the script tag, it's deprecated.
Then you should not load your script in the head section. Instead put it where body ends to ensure that the HTML has loaded.
Also in your validate function you don't seem to actually target the correct ID's.
Use this:
function Validate() {
if ($('#form_name').val() === '') {
$('#error').show();
return false ;
}
return true ;
}
Replace your javascript for this
function Validate() {
// Use form_name instead of form.name
if (form_name.value == "") {
// This line will break if you do not have jquery.
$('#error').show();
return false ;
}
return true ;
}
Define IDs for tags and use jQuery to get those tags and check their values. For example, if the name tag had id="form_name" you could do something like this:
if ($("#form_name").val() == ""))
$('#error').show();
On the other hand, I recommend you to check jQuery Validate plug-in which is great for validating forms:
http://jqueryvalidation.org/
Instead of
if (form.name.value == "") {
use:
var nameField=document.getElementById("form_name");
if (nameField.value == "") {
Let me know if this works.
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.
I have the following code:
<form action="" method="get" onsubmit="doRequest($('word').value); $('word').value=''; return false;">
<input type="text" name="word" id="word" value="" />
<input type="submit" name="submit" value="Send" />
</form>
doRequest() function:
function doRequest(request)
{
$.ajax(url, {
type: 'get',
data: { 'msg' : request }
});
}
The problem is, if I change the word value manually like value="111", I can see the value is being posted to PHP. However, when I want it to post whatever I write into textarea, it posts nothing, so the problem lies in the onSubmit area.
Can anybody help me about this?
You are missing the # in your jQuery selectors.
onsubmit="doRequest($('#word').value); $('#word').value=''; return false;"
I would also remove the inline JavaScript and replace it with a function in the submit handler instead. Also using jQuery .val() instead of .value.
$(document).ready(function() {
$('form').submit(function() {
doRequest($('#word').val());
$('#word').val('');
return false;
});
});
The correct way to access the value via jQuery is val() - not by setting a property.
$(...).val("set the value");
var get_the_value = $(...).val();
Also, your current selectors are looking for <word> elements which you hopefully don't have. Use #word as the selectors to search by ID.