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>
Related
I have an HTML form and some JavaScript code below it. Everything works. But what bothers me is that while everything else is in a function, the way I capture the submit button is not in a function.
So am I doing this correctly?
My form:
<form autocomplete="off" action="/cgi-bin/prl.pl">
<div class="autocomplete" style="width:300px;">
<input id="myInput" type="text" name="myCountry" placeholder="Pick a country" autofocus>
<input id="113" type="submit" value="Ok">
</form>
The top of my scripts:
<script>
var form = document.querySelector("form");
form.addEventListener("submit", function(e)
{
//////insert code to validate that
//////specific data is in my form
e.preventDefault();
});
function setFocusToInput()
{
var textbox = document.getElementById("myInput");
textbox.focus();
}
function autocomplete(inp, arr)
{
var currentFocus;
there is nothing wrong with inconsistency in javascript, but if you like it,
you can do something like this:
function validateForm(ev){
// do some validation
var valid = false;
if (!valid){
ev.preventDefault();
}
}
var form = document.querySelector("form");
form.addEventListener("submit", validateForm);
notice there is no () when attaching the event handler
<form autocomplete="off" action="/cgi-bin/prl.pl" id="my-form">
<div class="autocomplete" style="width:300px;">
<input id="myInput" type="text" name="myCountry" placeholder="Pick a country" autofocus>
<input id="113" type="submit" value="Ok">
</form>
function processForm(e) {
if (e.preventDefault) e.preventDefault();
/* do what you want with the form */
// You must return false to prevent the default form behavior
return false;
}
var form = document.getElementById('my-form');
if (form.attachEvent) {
form.attachEvent("submit", processForm);
} else {
form.addEventListener("submit", processForm);
}
there's nothing wrong with you code, but if you really want to make it a function, you can add onSubmit to <form>, and write a JS function to process it. something like this:
HTML:
<form onsubmit="process()">...</form>
JS:
function process() {}
How would I take user input from html and set it to a variable in javascript?
This is what i'm trying to implement:
<p>
<label>how old are you?</label>
<form id="form" onsubmit="return false;">
<input style=position:absolute;top:80%;left:5%;width:40%; type="number" id="userInput">
<input style=position:absolute;top:50%;left:5%;width:40%; type="submit" onclick="age()">
</form>
<script type="text/javascript">
function age()
{
var input = document.getElementById("userInput");
alert(input);
}
if(age<20)
{
alert(YOU ARE UNDER 20)
}
</script>
</p>
With pure JavaScript:
var input = document.getElementById('userInput');
alert(input.value);
With jQuery:
var input = $('#userInput');
alert(input.val());
To achieve what you want:
function age() {
var input = document.getElementById('userInput');
var age = parseInt(input.value);
if(age < 20) {
alert('YOU ARE UNDER 20');
}
}
There are some problems in your code. I will explain them.
1. You are creating a var input = document.getElementById("userInput"); But after that in your alert(input) it returns the entire object instead of the input value. 2. After that you are comparing Age wich is undefined because you didnt created var age = input;. If you compare input<20 it will work. In your alert you didnt use double quotes("") to create a string and alert that string. I hope its more clear now.
function age()
{
var age = document.getElementById("userInput").value;
alert(age);
if(age<20) { alert("YOU ARE UNDER 20"); }
}
<p>
<label>how old are you?</label>
<form id="form" onsubmit="return false;">
<input style=position:absolute;top:80%;left:5%;width:40%; type="number" id="userInput">
<input style=position:absolute;top:50%;left:5%;width:40%; type="submit" onclick="age()">
</form>
</p>
use document.getelementbyId
or
document.getelementbyclassname
alert(document.getElementById("userinput"));
or
alert( document.getElementsByClassName("classname"));
Try below
function age()
{
var input = document.getElementById("userInput").value;
if(input<20) { alert("YOU ARE UNDER 20"); }
}
<p>
<label>how old are you?</label>
<form id="form" onsubmit="return false;">
<input type="number" id="userInput">
<input style=position:absolute;top:50%;left:5%;width:40%; type="submit" onclick="age()">
</form>
</p>
what are you trying to achieve?
if you want to check age then move if inside function
function age()
{
var age = document.getElementById("userInput").value;
if(age<20)
{
alert("YOU ARE UNDER 20")
}
}
This is the HTML code:
<body>
<form>
<input id="input" type="text" name="input" value="Enter Here">
<input type="submit" value="Submit">
</form>
<div id="display">
</div>
</body>
This is the JavaScript:
input = document.getElementById("input");
if (input.value == "Hello") {
display.innerHTML = "Hello";
} else {
display.innerHTML = "Type";
}
When I change the input value by clicking on the input field and typing "Hello", it does not display "Hello" in display.innerHTML. I would like it to display "Hello" when "Hello" is typed into the input field. That's a lot of "Hello"'s! Any help would be great! Thanks in advance.
var input = document.getElementById("input"),
display=document.getElementById("display");
input.oninput=function(){
if (input.value === "Hello") {
display.innerHTML = "Hello";
} else {
display.innerHTML = "Type";
}
};
<input id="input" type="text" name="input" value="Enter Here">
<div id="display">
</div>
Your javascript code only gets executed once before you have entered anything in the input field.
You need to either setup a change handler for the input field or a submit handler for the form and set display.innerHTML.
Also, did you miss a display = document.getElementById("display");?
If you want use your button for submit the value of your textbox (your input type text-field) use onclick event as follows:
function displayData() {
var div_display = document.getElementById('display');
/* This is your input, but you shoud use another Id for your fields. */
var textValue = document.getElementById('input').value;
/* Change the inner HTML of your div. */
div_display.innerHTML = textValue;
}
<input id="input" type="text" name="input" value="Enter Here" />
<input type="submit" value="Submit" onclick="displayData();" />
<div id="display">
</div>
Hope it helps.
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.
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