enable buttons in javascript/jquery based on regex match - javascript

I'm having trouble getting the match to bind to the oninput property of my text input. Basically I want my submit button to be enabled only when the regular expression is matched. If the regex isn't matched, a message should be displayed when the cursor is over the submit button. As it stands, typing abc doesn't enable the submit button as I want it to. Can anyone tell me what I'm doing wrong? Thank you.
<div id="message">
</div>
<form method="POST">
<input type="text" id="txt" oninput="match()" />
<input type="submit" id="enter" value="enter" disabled />
</form>
<script>
var txt = $("#txt").value();
var PATTERN = /abc/;
var REQUIREMENTS = "valid entries must contain the string 'abc'";
// disable buttons with custom jquery function
jQuery.fn.extend({
disable: function(state) {
return this.each(function() {
this.disabled = state;
});
}
});
$('input[type="submit"]).disable(true);
var match = function(){
if (txt.match(PATTERN)){
$("#enter").disable(false)
}
else if ($("#enter").hover()){
function(){
$("#message").text(REQUIREMENTS);
}
}
</script>

Your code would be rewrite using plain/vanille JavaScript.
So your code is more clean and better performance:
<div id="message"></div>
<form method="POST">
<input type="text" id="txt" oninput="match()" />
<input type="submit" id="enter" value="enter" disabled />
</form>
<script>
var txt;
var enter = document.getElementById('enter');
var message = document.getElementById('message');
var PATTERN = /abc/;
var REQUIREMENTS = "valid entries must contain the string 'abc'";
function match() {
txt = document.getElementById('txt').value;
if (PATTERN.test(txt)) {
enter.disabled = false;
} else if (isHover(enter)) {
enter.disabled = true;
message.innerHTML = REQUIREMENTS;
} else {
enter.disabled = true;
}
}
function isHover(e) {
return (e.parentElement.querySelector(':hover') === e);
}
</script>
If you wanted to say that you want handle the events in different moments, your code should be the following.
Note: the buttons when are disabled doesn't fired events so, the solution is wrapper in a div element which fired the events. Your code JavaScript is more simple, although the code HTML is a bit more dirty.
<form method="POST">
<input type="text" id="txt" oninput="match()" />
<div style="display: inline-block; position: relative">
<input type="submit" id="enter" value="enter" disabled />
<div id="buttonMouseCatcher" onmouseover="showText(true)" onmouseout="showText(false)" style="position:absolute; z-index: 1;
top: 0px; bottom: 0px; left: 0px; right: 0px;">
</div>
</div>
<script>
var txt;
var enter = document.getElementById('enter');
var message = document.getElementById('message');
var PATTERN = /abc/;
var REQUIREMENTS = "valid entries must contain the string 'abc'";
function match() {
txt = document.getElementById('txt').value;
if (PATTERN.test(txt)) {
enter.disabled = '';
} else {
enter.disabled = true;
}
}
function showText(option) {
message.innerHTML = option ? REQUIREMENTS : "";
}
</script>

Two problems here:
The variable txt is defined once outside the function match, so the value is fixed to whatever the input with id txt has when the script/page is loaded.
You should move var txt = $("#txt").val(); into the match function.
Notice I changed the function value() to val().

Problems identified:
jQuery events don't happen on disabled inputs: see Event on a disabled input
I can't fix jQuery, but I can simulate a disabled button without it actually being disabled. There's other hacks you could do to get around this as well, for example, by overlaying a transparent element which actually captures the hover event while the button is disabled.
Various syntactical errors: format your code and read the console messages
.hover()){ function() { ... } } is invalid. It should be .hover(function() { ... })
else doesn't need to be followed by an if if there's no condition
.hover( handlerIn, handlerOut ) actually takes 2 arguments, each of type Function
$('input[type="submit"]) is missing a close '
Problems identified by #Will
The jQuery function to get the value of selected input elements is val()
val() should be called each time since you want the latest updated value, not the value when the page first loaded
Design issues
You don't revalidate once you enable input. If I enter "abc" and then delete the "c", the submit button stays enabled
You never hide the help message after you're done hovering. It just stays there since you set the text but never remove it.
https://jsfiddle.net/Lh4r1qhv/12/
<div id="message" style="visibility: hidden;">valid entries must contain the string 'abc'</div>
<form method="POST">
<input type="text" id="txt" />
<input type="submit" id="enter" value="enter" style="color: grey;" />
</form>
<script>
var PATTERN = /abc/;
$("#enter").hover(
function() {
$("#message").css('visibility', $("#txt").val().match(PATTERN) ? 'hidden' : 'visible');
},
$.prototype.css.bind($("#message"), 'visibility', 'hidden')
);
$('form').submit(function() {
return !!$("#txt").val().match(PATTERN);
});
$('#txt').on('input', function() {
$("#enter").css('color', $("#txt").val().match(PATTERN) ? 'black' : 'grey');
});
</script>

Related

How can I make it so that when input field is empty, button does nothing?

I'm making a simple searcher in which the user enters a query, clicks search, and the program returns either the location of said element, or a "No results found" line.
I'm having trouble with the search button itself. It works perfectly fine when the element that is being searched exists, but if I click on it while the input is blank, it returns the "No results found" message. I would like it so that it does nothing.
I'm using mainly JavaScript. What I've tried so far is make an if statement to check the length of the input, and then select the element from the DOM and make it disabled when length is 0.
I have tried adding both console.log and alert() to check the state of the button (enabled/disabled), and they both work equally, no matter the length of the input value.
<button value="submit" id="button" data-key="13" onclick="clickFunction()">
</button>
function clickFunction() {
var input = document.getElementById('input_id').value;
var input = input.toLowerCase();
/* disables button if there is no input */
if ( input.length === 0 ) {
document.getElementById("button").disabled = true;
console.log("disabled");
} else if (input.length > 0) {
document.getElementById("button").disabled = false;
console.log("enabled");
}
}
I have also tried using jQuery ($("#button").attr("disabled", true)), but it's not working either.
Am I missing something?
You need to stop the click, disabling the button with click means you will not be able to enable it.
function clickFunction(evt) {
var input = document.getElementById('input_id').value.trim();
// if (!input.length) { evt.preventDefault(); }
if (!input.length) return false; // cancel click
return true
}
<form>
<input type="search" id="input_id" name="input_id" />
<button value="submit" id="button" data-key="13" onclick="clickFunction(event)">
</button>
</form>
but why use JavaScript, let HTML do it for you.
<form>
<input type="search" name="search" required />
<input type="submit" />
</form>
this should work
function validate(obj) {
if (obj.value.length > 0) {
document.getElementById("btnSave").disabled = false;
} else {
document.getElementById("btnSave").disabled = true;
}
}
<input type="text" id="txtName" onkeyup="validate(this)"/>
<button disabled id="btnSave">save</button>
You can modify your code in this manner:
function clickFunction() {
var input = document.getElementById('input_id').value;
input = input.toLowerCase();
if (input.length) {
// write your search logic here
} else {
// won't do anything
return false;
}
}
I hope it will help.

Regex always returning either always true or always false regardless of valid test value

I am trying to validate a form field using Regex. The field should contain 5 numbers (ie 12345 = valid, 1234a = invalid, 123456 = invalid), that is it. no more, no less. The problem is with different regex formats, the .test() method either always returns true, or always returns false. It never works for correct values and fails for incorrect values. All regex testers test the regex successfully for JavaScript but when I add it to my page (WordPress), I get these issues. I read up about the /g field should be removed and tried all that. still no luck.
HTML:
<form name="newform" action="Create.php" onsubmit="return validateForm()" method="POST" >
Code <br/><br/><input id="code" class="form-control" type="text" value="" name="code" onkeypress="CodeStyleRefresh()" />
<button type="submit" id="submit" name="submit">Create</button>
</form>
JavaScript:
<script type="text/javascript">
function validateForm(){
var CodePattern = new RegExp(/\b\d{5}\b/);
if(CodePattern.test(document.forms["newform"]["code"].value) == true)
{
return true;
}
else
{
return false;
}
}
function CodeStyleRefresh(){
document.getElementById("code").setAttribute("style", "background-color: #ffffff;");
}
</script>
Some other ways I have tried to specify the expression:
var CodePattern = new RegExp(/\b\d{5}\b/);
var CodePattern = new RegExp('/\b\d{5}\b/');
var CodePattern = /\b\d{5}\b/;
var CodePattern = '/\b\d{5}\b/';
var CodePattern = \b\d{5}\b;
var CodePattern = '\b\d{5}\b';
This is my first time ever touching regex and I am fairly new to the JavaScript family as well. Not having such a good time.
UPDATE:
I have gone back to basics. My JavaScript now looks as follows based on a few suggestions:
function validateForm(event)
{
console.log("Im running the script!");
console.log(event.target.querySelector("[name=code]").value);
var CodePattern = new RegExp(/\b\d{5}\b/);
var codeVal = event.target.querySelector("[name=code]").value;
if(CodePattern.test(codeVal) == true)
{
alert("Expression Passed!");
}
else
{
alert("Expression Failed!");
return false;
}
}
My HTML is now:
<form name="newform" onsubmit="return validateForm(event)" method="POST">
Code
<input id="code" class="form-control" type="text" value="" name="code" />
<button type="submit" id="submit" name="submit">Create</button>
</form>
Still this expression is only hitting the failed state and alerts expression failed.
If it helps, I am adding the JavaScript to a WordPress page, the form is normal html on the same page. I have tried adding the JavaScript to both the header and the footer but this does not change anything. I'm starting to think I should just check if the length of the field = 5 and if I can then cast it to an int instead of using RegEx at all!
Your regex is fine. If you are only getting the error when you upload your code to your wordpress site, I'd be tempted to say that your problem is your context, perhaps you have more than one form with the same name?
Try a context aware piece of code, update your html to:
<form name="newform" onsubmit="return validateForm(event)" method="POST">
Code
<input id="code" class="form-control" type="text" value="" name="code" onkeypress="CodeStyleRefresh()" />
<button type="submit" id="submit" name="submit">Create</button>
</form>
And your javascript:
function validateForm(event){
var myRegex = new RegExp(/\b\d{5}\b/);
//event.target holds the node element that triggered the function in our case, the Form itself
var myValue = event.target.querySelector("[name=code]").value; //here we find the input with the name=code inside the form that triggered the event
return myRegex.test(myValue) //return true if it passed, false if not
}
Since I cannot insert this much code in comments, I am posting an answer here to show how it all works.
function validateForm(frm, evt)
{
var codeVal = frm.code.value;
var CodePattern = /\b\d{5}\b/;
// comment below line after testing
evt.preventDefault();
if(CodePattern.test(codeVal) == true)
{
console.log("Expression Passed!");
return true;
}
else
{
console.log("Expression Failed!");
return false;
}
}
<form name="newform" onsubmit="return validateForm(this, event)" method="POST">
Code <br/><br/>
<input id="code" type="text" value="abc 12345 foo bar" name="code" />
<input type="submit" id="submit" name="submit" value="Create" />
</form>
Thank you for all the suggestions. I have learnt a few things by looking at them all and I have made a few changes.
I could not however get the regex to work properly in wordpress. I was forced to create a longwinded, dirtier solution to this. I will continue to look at possible solutions and test on other wordpress sites, but for now, this is the code I am using to validate the field:
function validateForm(frm, evt)
{
var codeVal = frm.code.value;
console.log("Code Value: " + String(codeVal));
// comment below line after testing
evt.preventDefault();
var lenPass = false;
var strlen = codeVal.length;
if(strlen == 5)
{
lenPass = true;
}
if(lenPass)
{
var c1 = Number.isNaN(Number(codeVal.charAt(0)));
var c2 = Number.isNaN(Number(codeVal.charAt(1)));
var c3 = Number.isNaN(Number(codeVal.charAt(2)));
var c4 = Number.isNaN(Number(codeVal.charAt(3)));
var c5 = Number.isNaN(Number(codeVal.charAt(4)));
console.log(c1);
console.log(c2);
console.log(c3);
console.log(c4);
console.log(c5);
var pass = true;
if(c1)
{
pass = false;
}
if(c2)
{
pass = false;
}
if(c3)
{
pass = false;
}
if(c4)
{
pass = false;
}
if(c5)
{
pass = false;
}
if(pass)
{
alert("Expression Stage 2 Passed!");
return true;
}
else
{
alert("Expression Stage 2 Failed!");
return false;
}
}
else
{
alert("Expression Stage 1 Failed!");
return false;
}
}
<html>
<head>
</head>
<body>
<form name="newform" onsubmit="return validateForm(this, event)" method="POST">
Code <br/><br/>
<input id="code" type="text" value="" name="code" />
<input type="submit" id="submit" name="submit" value="Create" />
</form>
</body>
</html>

Prevent multiple alert on "oninvalid" html

I was thinking, can i stop the alerts after the first?
I'll explain it better, every time I confirm the form, start an aler for every input that has oninvalid.
so if i have 10 inputs, i'll have 10 alarms. Is it possible to interrupt them after the first one?
<form>
<input type="text" oninvalid="alert('test1')" required />
<input type="text" oninvalid="alert('test2')" required />
<button>Send</button>
</form>
Fiddle: https://jsfiddle.net/9d1L5pxd/1/
You can consider doing something like I demonstrate below. Basically just add an event handler to the send button, which will call a validation function on your form each time it's clicked.
The validation function checks all the text type field values. If a text field with an invalid value is encountered, the function will return false (stop immediately).
If the function doesn't find any problems with the user input then it will return true. You can use the return value to determine if the form should be submitted or whatever if you need to.
var btnSend = document.getElementById('btnSend');
btnSend.addEventListener('click', function() {
var isValid = validateForm();
if (isValid)
console.log('Form is ready to submit.');
});
function validateForm() {
var formToValidate = document.getElementById('dataForm');
var elements = formToValidate.elements;
var i;
for (i = 0; i < elements.length; i++) {
if (elements[i].type == 'text') {
//replace this with your actual validation
var invalid = elements[i].value.length == 0;
if (invalid) {
alert(elements[i].id + ' is invalid.');
return false;
}
}
}
return true;
}
<form id="dataForm">
<input id="field1" type="text" required />
<input id="field2" type="text" required />
<input id="btnSend" type="button" value="Send">
</form>

Disable Button Until Fields are Full Pure JS

Trying to keep a button disabled until the form fields are filled in and I cannot seem to accomplish this. I've created a small example with a single field but the principle will be the same with a larger form.
Can anyone help?
Code:
function checkForm() {
var name = document.getElementById("name").value;
var cansubmit = true;
if (name.value.length == 0) {
cansubmit = false;
}
if (cansubmit == false) {
document.getElementById("submitbutton").disabled = true;
}
};
<input type="text" id="name" onkeyup="checkForm()" />
<button type="button" id="myButton">Test me</button>
There are a couple of mistakes in your sample:
var name is assigned to the value string of the name element, then you check the value property of that - the string has no value property.
the id of the submit button is myButton so use that id to get it by id (when setting the disabled attribute).
You can disable the submitbutton until the length of the name input is greater than 0.
And disabling the button initially sounds like a good idea, right?
See corrected example below:
function checkForm()
{
var name = document.getElementById("name").value;
var cansubmit = (name.length > 0);
document.getElementById("myButton").disabled = !cansubmit;
};
<input type="text" id="name" onkeyup="checkForm()" />
<button type="button" id="myButton" disabled="disabled">Test me</button>
You might also want to consider handling change via methods other than keypress - e.g. mouseup, etc... I tried adding onchange="checkForm()" and it works but only on blur (focus-change)...

Fill data in input boxes automatically

I have four input boxes. If the user fills the first box and clicks a button then it should autofill the remaining input boxes with the value user input in the first box. Can it be done using javascript? Or I should say prefill the textboxes with the last data entered by the user?
On button click, call this function
function fillValuesInTextBoxes()
{
var text = document.getElementById("firsttextbox").value;
document.getElementById("secondtextbox").value = text;
document.getElementById("thirdtextbox").value = text;
document.getElementById("fourthtextbox").value = text;
}
Yes, it's possible. For example:
<form id="sampleForm">
<input type="text" id="fromInput" />
<input type="text" class="autofiller"/>
<input type="text" class="autofiller"/>
<input type="text" class="autofiller"/>
<input type="button"value="Fill" id="filler" >
<input type="button"value="Fill without jQuery" id="filler2" onClick="fillValuesNoJQuery()">
</form>
with the javascript
function fillValues() {
var value = $("#fromInput").val();
var fields= $(".autofiller");
fields.each(function (i) {
$(this).val(value);
});
}
$("#filler").click(fillValues);
assuming you have jQuery aviable.
You can see it working here: http://jsfiddle.net/ramsesoriginal/yYRkM/
Although I would like to note that you shouldn't include jQuery just for this functionality... if you already have it, it's great, but else just go with a:
fillValuesNoJQuery = function () {
var value = document.getElementById("fromInput").value;
var oForm = document.getElementById("sampleForm");
var i = 0;
while (el = oForm.elements[i++]) if (el.className == 'autofiller') el.value= value ;
}
You can see that in action too: http://jsfiddle.net/ramsesoriginal/yYRkM/
or if input:checkbox
document.getElementById("checkbox-identifier").checked=true; //or ="checked"

Categories

Resources