what I am missing in this code, If I just want the input submit button to enable/disable/enable.. as long as I fill or unfill the input text?
sorry I am doing my best to learn javascript...can anyone help me fix this code?
<form name="myform" method="post">
<input onkeyup="checkFormsValidity();" id="input_id" type="text" name="input_name" value=""/>
<input type="submit" name="submit_name" value="OK" class="submit_class" id="SubmitButton"/>
</form>
<script>
var sbmtBtn = document.getElementById("SubmitButton");
sbmtBtn.disabled = true;
function checkFormsValidity(){
var myforms = document.forms["myform"];
if (myforms.checkValidity()) {
sbmtBtn.disabled = false;
} else {
sbmtBtn.disabled = true;
}
}
</script>
This is the fiddle: https://jsfiddle.net/1zfm6uck/
Am I missing declaring onLoad mode or something like this?
Thanks!
Actually - if it wasn't a jsfiddle example your code would work great:
var sbmtBtn = document.getElementById("SubmitButton");
sbmtBtn.disabled = true;
function checkFormsValidity(){
var myforms = document.forms["myform"];
if (myforms.checkValidity()) {
sbmtBtn.disabled = false;
} else {
sbmtBtn.disabled = true;
}
}
input[type='submit']:disabled{
color:red;
}
<form name="myform" method="post">
<input onkeyup="checkFormsValidity();" id="input_id" type="text" name="input_name" value="" required="required" />
<input type="submit" name="submit_name" value="OK" class="submit_class" id="SubmitButton"/>
</form>
The problem was the jsfiddle put your javascript code inside a clousure, so the checkFormsValidity function is not available in the scope of your input.
I added a required="required" to your input to make sure it's a required field (which will affect the checkValidity() of your form).
function checkFormsValidity(){
needs to be change to:
checkFormsValidity = function(){
Personally I wouldn't check validity that way, but in terms of making your code work without error, that will do it.
Edit: Also add required="required" to the input.
Related
Hi all I have written following code:
<form action="" onsubmit="validate()">
<input type="text" id="FormField_6_input" maxlength="20" name="CompanyName"/>
<button>Continue</button>
</form>
<script>
function validate(){
var company_Name = document.getElementById('FormField_6_input').value;
var companyRGEX = /[2-9]{1}\d{3}/;
var result = !companyRGEX.test(company_Name);
alert(result)
}
</script>
I want to disable the button if the input does not match the regular expression, and enable it if it matches. How can I achieve to that result?
If you want to use JavaScript to dynamically disable the button, use the following:
The input eventListener to listen for changes in the field value;
The .disabled property to toggle it.
How I implemented on your solution:
Created two variables to hold references to the field and to the button.
Added validate as the function for an input eventListener (attached to the field).
Compared the field.value to the companyRGEX using string.match(regEx).
You can run the snippet below.
let companyNameField = document.getElementById('FormField_6_input');
let button = document.getElementById('ContinueButton_6');
companyNameField.addEventListener('input', validate);
function validate(){
var companyNameValue = companyNameField.value;
var companyRGEX = /[2-9]{1}\d{3}/;
if(!companyNameValue.match(companyRGEX)) {
button.disabled = true;
} else {
button.disabled = false;
}
}
<form action="" onsubmit="validate()">
<input type="text" id="FormField_6_input" maxlength="20" name="CompanyName"/>
<button id="ContinueButton_6">Continue</button>
</form>
Just use pattern with required. No JavaScript is needed
<form action="" onsubmit="validate()">
<input type="text" id="FormField_6_input" maxlength="20" name="CompanyName" pattern="[2-9]{1}\d{3}" required>
<button>Continue</button>
</form>
If you want to use JavaScript than cancel the submission
function validateIt (evt) {
var company_Name = document.getElementById('FormField_6_input').value;
var companyRGEX = /[2-9]{1}\d{3}/;
var isValid = !!companyRGEX.test(company_Name);
if (!isValid) {
evt.preventDefault();
alert('error');
}
}
console.log(document.querySelector("form"))
document.querySelector("form").addEventListener("submit", validateIt);
<form action="">
<input type=" text " id="FormField_6_input" maxlength="20" name="CompanyName" />
<button>Continue</button>
</form>
add addEventListener to the input field the return a value from validate function
document.getElementById('FormField_6_input').addEventListener('input', function(evt) {
document.getElementById('submit').disabled = validate(this.value)
});
function validate(company_Name) {
var companyRGEX = /[2-9]{1}\d{3}/;
var result = !companyRGEX.test(company_Name);
return result;
}
<form action="" onsubmit="validate()">
<input type="text" id="FormField_6_input" maxlength="20" name="CompanyName" />
<button id="submit">Continue</button>
</form>
Im trying to figure out how can Javascript check if input field has any value, then it removes class value "is-invalid".
I have this code so far:
<form>
<label for="inputName">Username</label>
<input type="text" class="is-invalid" id="inputName">
</form>
<script>
var checkInput = document.getElementById("inputName");
if (checkInput.value) {
element.classList.remove("is-invalid");
}
</script>
As you can see theres a red border (class="is-invalid") around the input. As soon as user puts any value in the inputfield, Javascript will remove class value "is-invalid".
Or might there be an easier option with jQuery?
You have a mistake in your code. You have used
element.classList.remove("is-invalid");
which is wrong, you have to use it like
checkInput.classList.remove("is-invalid");
You can use like this in javascript.
function check(){
var checkInput = document.getElementById("inputName");
if (checkInput.value) {
checkInput.classList.remove("is-invalid");
} else {
checkInput.classList.add("is-invalid");
}
}
<form>
<label for="inputName">Username</label>
<input type="text" class="is-invalid" id="inputName" onkeyup="check()">
</form>
In Jquery you can try like
$('#inputName').keyup(function(e){
if ($('#inputName').val()) {
$('#inputName').removeClass("is-invalid");
} else {
$('#inputName').addClass("is-invalid");
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<label for="inputName">Username</label>
<input type="text" class="is-invalid" id="inputName">
</form>
You need to add an event listener to the element to know when it changes.
var checkInput = document.getElementById("inputName");
checkInput.addEventListener('keyup', (e)=>{
if (e.target.value!==''){
e.target.classList.remove("is-invalid");
}
})
I have created a form in HTML and have use onblur event on each and every field and it is working very fine. The problem is when i click on submit button(which will send data to a servlet) the data is submitted even if it is invalid. Here is an example.
<html>
<head>
<script>
function check()
{
if(checkName()==true)
return true;
else{
alert('vhvh');
return false;
}
}
function checkName()
{
var uname=document.enq.Name.value;
var letters = /^[A-Za-z, ]+$/;
if(uname.match(letters))
{
document.getElementById('Name').style.borderColor = "black";
return true;
}
else
{
document.getElementById('Name').style.borderColor = "red";
//alert('Username must have alphabet characters only');
//uname.focus();
return false;
}
}
</script>
</head>
<body>
<form name="enq" method="post" action="Enquiry" onsubmit="check()">
<input class="textbox" id="Name"style="margin-top:10px;font-size:16px;" type="text" name="Name" placeholder="Full Name" onblur="checkName()" required /><br><br>
<input class="button" type="submit">
</form>
</body>
</html>
How can i resolve this issue?
use
<input class="button" type="button">
and put a onclick event like this:
<input class="button" type="button" onclick="this.submit()">
so you can manipulate data before you subimit it.
There is an "onsubmit" event that allows you to control form submission. Use it to call your validation functions, and only then decide if you want to allow the user to submit the form.
http://www.htmlcodetutorial.com/forms/_FORM_onSubmit.html
You have to use it in the following way if you want it to prevent the form submission:
<form onsubmit="return check()">
I'm new to javascript / jquery so I may be missing something obvious, but I've found solutions that disable the submit button until all text fields are filled, and I've found solutions that disable it until a file is chosen. However, my form consists of a file input and 3 text fields and I cannot find a way of it being disabled until all text fields AND a file is chosen.
The distilled version of the code I'm working with is here:
HTML
<div>
<input type="file" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="submit" value="Upload" class="submit" id="submit" disabled="disabled" />
</div>
JS
$('.submit').click(function() {
var empty = $(this).parent().find("input").filter(function() {
return this.value === "";
});
if(empty.length) {
$('.submit').prop('disabled', false);
}
});
})()
Thanks for your help
https://jsfiddle.net/xG2KS/482/
Try capture the event on those field and checking the empty values by using another function, see below code :
$(':input').on('change keyup', function () {
// call the function after
// both change and keyup event trigger
var k = checking();
// if value inc not 0
if (k) $('.submit').prop('disabled', true);
// if value inc is 0
else $('.submit').prop('disabled', false);
});
// this function check for empty values
function checking() {
var inc = 0;
// capture all input except submit button
$(':input:not(:submit)').each(function () {
if ($(this).val() == "") inc++;
});
return inc;
}
This is just an example, but the logic somehow like that.
Update :
Event Delegation. You might need read this
// document -> can be replaced with nearest parent/container
// which is already exist on the page,
// something that hold dynamic data(in your case form input)
$(document).on('change keyup',':input', function (){..});
DEMO
Please see this fiddle https://jsfiddle.net/xG2KS/482/
$('input').on('change',function(){
var empty = $('div').find("input").filter(function() {
return this.value === "";
});
if(empty.length>0) {
$('.submit').prop('disabled', true);
}
else{
$('.submit').prop('disabled', false);
}
});
[1]:
The trick is
don’t disable the submit button; otherwise the user can’t click on it and testing won’t work
only when processing, only return true if all tests are satisfied
Here is a modified version of the HTML:
<form id="test" method="post" enctype="multipart/form-data" action="">
<input type="file" name="file"><br>
<input type="text" name="name"><br>
<input type="text" name="email"><br>
<button name="submit" type="submit">Upload</button>
</form>
and some pure JavaScript:
window.onload=init;
function init() {
var form=document.getElementById('test');
form.onsubmit=testSubmit;
function testSubmit() {
if(!form['file'].value) return false;
if(!form['name'].value) return false;
if(!form['email'].value) return false;
}
}
Note that I have removed all traces of XHTML in the HTML. That’s not necessary, of course, but HTML5 does allow a simpler version of the above, without JavaScript. Simply use the required attribute:
<form id="test" method="post" enctype="multipart/form-data" action="">
<input type="file" name="file" required><br>
<input type="text" name="name" required><br>
<input type="text" name="email" required><br>
<button name="submit" type="submit">Upload</button>
</form>
This prevents form submission if a required field is empty and works for all modern (not IE8) browsers.
Listen for the input event on file and text input elements, count number of unfilled inputs and, set the submit button's disabled property based on that number. Check out the demo below.
$(':text,:file').on('input', function() {
//find number of unfilled inputs
var n = $(':text,:file').filter(function() {
return this.value.trim().length == 0;
}).length;
//set disabled property of submit based on number
$('#submit').prop('disabled', n != 0);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<input type="file" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="submit" value="Upload" class="submit" id="submit" disabled="disabled" />
</div>
For my approach, I'd rather use array to store if all the conditions are true. Then use every to make sure that all is true
$(function(){
function validateSubmit()
{
var result = [];
$('input[type=file], input[type=text]').each(function(){
if ($(this).val() == "")
result.push(false);
else
result.push(true);
});
return result;
}
$('input[type=file], input[type=text]').bind('change keyup', function(){
var res = validateSubmit().every(function(elem){
return elem == true;
});
if (res)
$('input[type=submit]').attr('disabled', false);
else
$('input[type=submit]').attr('disabled', true);
});
});
Fiddle
I have following Javascript validation function that should check that the URL posted to my php are OK - if not display a message to correct the entry.
I must have done a mistake somewhere because it is not working and my console.log says: ReferenceError: Can't find variable: $
validateFormbasic.html:12
onsubmitbasic.html:24:95
Could you tell me how to fix it please? Thanks a lot!
<form method="POST" name="inputLinks" onsubmit="return validateForm();">
<input type="text" name="web1" id="url1" placeholder="domain.com">
<input type="text" name="web2" id="url2" placeholder="domain.com">
<input type="text" name="web3" id="url3" placeholder="domain.com">
<input type="submit" name="Submit" value="Done" />
</form>
<script type="text/javascript">
function validateURL(web1, web2, web3) {
var reurl = /^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/;
return reurl.test(url);
}
function validateForm()
{
// Validate URL
var url = $("#url1", "#url2", "#url3").val();
if (validateURL(url)) { } else {
alert("Please enter a valid URL, remember including http://");
}
return false;
}
</script>
As Alberto's comment mentions, it looks like jQuery isn't loaded at the point of calling the function. It also looks to me as if you're syntax for selecting the URL values isn't quite right.
I would use something along the lines of:
<form method="POST" name="inputLinks">
<input type="text" name="web1" id="url1" class="url" placeholder="domain.com" />
<input type="text" name="web2" id="url2" class="url" placeholder="domain.com" />
<input type="text" name="web3" id="url3" class="url" placeholder="domain.com" />
<input type="submit" name="Submit" value="Done" />
</form>
<script type="text/javascript">
$(function(){
function validateURL(url) {
var reurl = /^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/;
return reurl.test(url);
}
$('form').submit(function(e){
var isValid = true;
$('.url').each(function(){
isValid = validateURL($(this).val());
return isValid;
});
if (!isValid){
e.preventDefault();
alert("Please enter a valid URL, remember including http://");
}
});
});
</script>
Update
Demo JS Fiddle