Using regEx to auto enable/disable button depending on characters and spaces - javascript

I have been stuck on trying to create a submit button that auto enables/disables when the user types into an input box. I have successfully been able to create a submit button that starts out disabled and then enables when a user starts typing, but I want the button to disable if the user enters a number or anything else except a character or a string.
Here is the code I currently have for my script:
$(document).ready(function() {
$('#seed').on('keyup', function(){
var regEx = /^[a-zA-Z\s]*$/;
if($(this).val() != regEx) {
$('#submit').prop('disabled', false);
} else {
$('#submit').prop('disabled', true);
}
});
});
Along with my main index file with my form:
<head>
<title>Story Ideas</title>
<link type="text/css" rel="stylesheet" href="style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script defer src="js/script.js"></script>
</head>
<div class="form-style">
<form class="form" name="form" method="post" action="?v=ture">
<label for="table">Select Your Story</label> <br />
<select name="table" id="table">
<option value="moons">Moons</option>
<option value="lionbird">Lionbird</option>
<option value="chik">Chik</option>
</select>
<br>
<input type="text" id="seed" name="seed">
<br>
<input id="submit" type="submit" disabled="disabled">
</form>
</div>
<?php
include_once('includes/functions.php');
if (isset($_GET['v']) && $_GET['v'] == true)
{
$t = $_POST['seed'];
$table = $_POST['table'];
echo genPoem($t, $table);
echo "<br>";
echo "<br>";
}
?>
</body>
I tried using var regEx = /^[a-zA-Z\s]*$/; to prevent this. Have I missed something?

You are not using the correct condition to check if your value matches the regex or not, your regex is fine just switch if($(this).val() != regEx) for if(regEx.test($(this).val())).
Reference for test method:
https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test

You could try $(this).val().match(regEx) instead of using !=, as documented in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions.

Related

Why is my input validation from jquery wont work?

I want a validation onkeyup from an input form, I've made a jquery. I'm having a hard time finding why is it not checking? I need to go to a php page in checking. What could be wrong to my code that it don't work?
<html>
<head>
<title>
reg
</title>
</head>
<body>
<form method="post">
<input type="text" name="name" onkeyup="check_user()" id="name"/><div id="checking">Checking</div>
<button type="submit" name="submit">Submit<button>
</form>
<script src="jquery-3.3.1.min.js"></script>
<script>
document.getElementById("submit").disabled=true;
function check_user(){
var name = document.getElementById("name").value;
$.post("user_check.php",
{
user: name
},
function(data,status){
if(data=='<p style="color:red">Name contains a number</p>'){
document.getElementById("submit").disabled=true;
}
else{
document.getElementById("submit").disabled=false;
}
document.getElementById("checking").innerHTML=data;
}
);
}
</script>
</body>
</html>
user_check.php
<?php
if (isset($_POST['user'])) {
if(preg_match('/^\d+$/', $_POST['user'])) {
echo '<p style="color:red">Name contains a number</p>';
} else {
echo '<p style="color:green"> You can take this name</p>';
}
}
?>
You can validate the text box by adding the pattern attribute like this pattern="[a-zA-Z]+"
<input type="text" name="name" pattern="[a-zA-Z]+" title="please just add strings" id="name"/>
i also notice in your code you did not add the id for the submit button thats why your submit button is not disabled, your code should like this for submit button.
Submit
1- first add the id attribute of the submit button id="submit"like this
<button type="submit" id="submit" name="submit">Submit<button>
2- update the code on user_check.php
if (isset($_POST['user'])) {
if(!preg_match('/^([^0-9]*)$/', $_POST['user'])) {
echo '<p style="color:red">Name contains a number</p>';
} else {
echo '<p style="color:green"> You can take this name</p>';
}
}

On validate revise html code using javascript

I use this code for validation:
<html>
<head>
<script>
function validateNew() {
var x1 = document.forms["register"]["firstname"].value;
if (x1 == null || x1 == "") {
alert("Please enter your first name.");
return false;
}
}
</script>
</head>
<body>
<form name="register" method="POST" onsubmit="return validateNew()">
<label id="fname_lbl" class="">First Name
<input type="text" name="firstname">
<input type="submit" value="Submit">
</form>
But I want to do something a little different. I had this code a while back, but I cant remember where I put it. Basically, instead of a pop up window, I want the validate to conditionally trigger code in the html, which will accomplish the goal of preventing the submission, but show, let's say, text above the field that says, in red, "Required Field".
The pseudo-code:
<html>
<head>
<script>
function validateNew() {
var x1 = document.forms["register"]["firstname"].value;
if (x1 == null || x1 == "") {
$trigger = for label id('fname_lbl') class=="require";
return false;
}
}
</script>
</head>
<body>
<form name="register" method="POST" onsubmit="return validateNew()">
<label id="fname_lbl" class="<? $trigger ?>">First Name
<input type="text" name="firstname">
<input type="submit" value="Submit">
</form>
Where the class named "require" will turn the font color of 'First Name' to red.
So on the validation, when the code finds out there is no first name, it then, using a trigger variable, modifies that variable, which is read inside the quotes of 'class'.
I know my pseudo-code is way off. I just remember being able to do something like that a couple years ago.
EDIT
I found that code snip
<head>
<script>
$(document).ready(function (){
$("#b_down").change(function() {
if ($(this).val() < 20 ) {
$("#pmi").show();
}else{
$("#pmi").hide();
}
});
});
</script>
</head>
<body>
<select name="b_down" id="b_down">
<option value=""></option>
<option value="1">1</option>
<option value="2" >2</option>
<option value="3" >3</option>
</select>
<? if ($row['b_down']<2) { ?>
<span id="pmi" style="display;" class="dropt">PMI:
<? } else { ?>
<span id="pmi" style="display:none;" class="dropt">PMI:
<? } ?>
Basically, on the change event, it either shows or hides a particular input. Not sure how to apply it to my project.
You could use this:
<html>
<head>
<title>LIGHTBOX EXAMPLE</title>
<style>
.normal {
color: #0f0;
}
.required {
color: #f00;
}
</style>
</head>
<body>
<form name="register" method="POST" onsubmit="return validateNew();">
<label id="fname_lbl" class="normal">First Name</label>
<input type="text" name="firstname">
<input type="submit" value="Submit">
</form>
</body>
<script>
function validateNew() {
var x1 = document.forms["register"]["firstname"].value;
if (x1 == null || x1 == "") {
document.getElementById("fname_lbl").className = "required";
return false;
}
}
</script>

Posted variable used in javascript 'if' statement disappears instantly

I have forms running on my page which post data to a php file which causes the posted item to appear in a cart:
<form method="post"><fieldset>
<input type="hidden" name="jcartToken" value="<?php echo $_SESSION['jcartToken'];?>" />
<input type="hidden" name="my-item-name" value="is716" />
<input type="hidden" name="my-item-price" value="10" />
<input id="716" type="submit" name="my-add-button" value="&nbsp" />is716</input>
</fieldset></form>
I then put a script running at the bottom of my page which essentially toggles controls so that further selections become clear based on previous selections:
if (name == 'is716') {
document.getElementById('716b').style.display = 'none';
document.getElementById('716c').style.display = 'inline';
}else{
document.getElementById('716b').style.display = 'none';
document.getElementById('716c').style.display = 'inline';}
The problem is that the above script's if statement, that name == 'is716' apparently only becomes true for a moment when you click submit. The css will change and flash for just a second, showing that the statement is indeed working and then it will disappear. I can make the changes stay by adding 'return false' but this stops the form from being submitted and the data updated, which completely misses the point. Is there a way to both submit the data but also have the value 'stick'?
How can I make this change last until the statement changes again?
edit:
Here is the page's code:
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>jCart - Free Ajax/PHP shopping cart</title>
<link rel="stylesheet" type="text/css" media="screen, projection" href="style.css" />
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" media="screen, projection" href="jcart/css/jcart.css" />
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'> </script>
<style type="text/css">
input.add {
background-image: url('off.png');
width: 12px;
height: 12px;
border: 0;
cursor: pointer;
}
</style>
</head>
<body>
<div id="wrapper">
<div id="sidebar">
<div id="jcart"><?php $jcart->display_cart();?></div>
</div>
<div id="content">
<form method="post"><fieldset>
<input type="hidden" name="jcartToken" value="<?php echo $_SESSION['jcartToken'];?>" />
<input type="hidden" name="my-item-id" value="1" />
<input type="hidden" name="my-item-name" value="is716" />
<input type="hidden" name="my-item-price" value="5000" />
<input type="hidden" name="my-item-partn" value="716" />
<input type="hidden" name="my-item-qty" value="1" size="3" />
<input id="716a" type="submit" name="my-add-button" class="add" value="&nbsp" />
<a id="716b" href="addtocart.php?jcartRemove[]=1" /><img src="on.png"></a> &nbsp Apples $5<br>
<br></fieldset></form>
<div class="clear"></div>
<?php
//echo '<pre>';
//var_dump($_SESSION['jcart']);
//echo '</pre>';
?>
</div>
<div class="clear"></div>
</div>
<script type='text/javascript'>
$(document).ready(function() {
$('input[name=my-add-button]').change(function(){
$('form').submit();
});
});
</script>
<script type="text/javascript">
$('#720').click(function() {
$('#720click').click();
});
</script>
<script type='text/javascript'>
window.onload = function() {
var myItemName = <?php echo (isset($_POST["my-item-name"])? $_POST["my-item-name"] : ""); ?>;
if (myItemName == "is716") {
document.getElementById('716a').style.display = 'none';
document.getElementById('716b').style.display = 'inline';
}
}
That pushes to another page: jcart.php
Like Suman said your page is getting submitted, therefore the style reloads with the page so any changes made in the page session to your style will be reset.
A solution to your problem would be to set session flags in your form's php target page. You could do this like:
<?php
if (isset($_POST["my-item-name"]) {
session_start();
$_SESSION["my-item-name"] = $_POST["my-item-name"];
}
?>
And then on your cart page you would echo the session variable into a JavaScript that will toggle the styling of your page as necessary:
<?php session_start(); ?>
window.onload = function() {
var myItemName = <?php echo $_SESSION["my-item-name"]; ?>;
if (myItemName == "is716") {
document.getElementById('716b').style.display = 'none';
document.getElementById('716c').style.display = 'inline';
}
}
Hopefully this is what you are looking for.
EDIT: For if your target page is the same page you could simplify this by having your javascript look like this:
window.onload = function() {
var myItemName = "<?php echo (isset($_POST["my-item-name"])? $_POST["my-item-name"] : ""); ?>";
if (myItemName == "is716") {
document.getElementById('716b').style.display = 'none';
document.getElementById('716c').style.display = 'inline';
}
}
Your form is getting posted and hence the page is getting reloaded. Now, when a webpage is reloaded previous states are forgotten by the browser until and unless you use some persistence (like local storage or something) and check saved data and restore previous stage of any element on page reload by yourself.
Use ajax to post your data and to get information back from server. This way your styles and states will be retained.
Do an event.preventDefault() on your form submit button click and then do whatever server post activity you want to do by ajax call. That should do.

How to validate a php form with java script, that is on everypage of my site

The problem i'm having is Im trying to get the contact.php to validate a contact form that is now in the bottom of every page in my site. It worked great with just validating one page and having a hard URL to take them back to. the troubleing code is this.
/* In case of no valid input go back */
if ($p1==""||$p2==""||$p3==""||$p5==""||$n0!=0||$f0<7||$NL==0||$p7=="") {
header($_SERVER['HTTP_REFERER'].$report);
}else{$report='noerror';}
Ive also tryed this:
/* In case of no valid input go back */
if ($p1==""||$p2==""||$p3==""||$p5==""||$n0!=0||$f0<7||$NL==0||$p7=="") {
header($_SERVER['PHP_SELF'].$report);
}else{$report='noerror';}
This is the original code that worked for one page:
/* In case of no valid input go back */
if ($p1==""||$p2==""||$p3==""||$p5==""||$n0!=0||$f0<7||$NL==0||$p7=="") {
header('Location:estimate_page.php?'.$report);
}else{$report='noerror';}
I could just make a new "contact.php" page for every page that has the form in the footer, but thats stupid if i can just make this work. Any ideas
You are thinking in the right direction with javascript/jQuery -- it will allow you to catch the invalid fields before submitting / changing pages. Much better user experience. Only submit when fields are validated.
Here is a link for how to do simple field validation testing with jQuery:
jsFiddle Demo
HTML:
One: <input type="text" id="f1"><br />
Two: <input type="text" id="f2"><br />
Three: <input type="text" id="f3"><br />
Four: <input type="text" id="f4"><br />
<br />
<input type="button" id="mybutt" value="Go" />
javascript/jQuery:
var chkFld, arrAll = {'One':'f1','Two':'f2','Three':'f3','Four':'f4'};
$('#mybutt').click(function() {
var errMsg='', badFlds='', firstBad='';
for(var key in arrAll){
chkFld = '#'+arrAll[key];
$(chkFld).removeClass('error');
if ($(chkFld).val() ==''){
$(chkFld).addClass('error');
//alert('Please complete field ' + arrAll[key] );
errMsg += '*' + key + '\n';
if (firstBad=='') firstBad=chkFld;
}
}
if (errMsg != '') {
alert(errMsg);
$(firstBad).focus();
}
}); //END mybutt.click
Note that the above example uses jQuery, so you must reference the jQ libraries (usually inside the head tags, something like this:)
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
EDIT:
Here is what the full HTML would look like:
<?php
//Any initial PHP code goes here
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
//javascript
var chkFld, arrAll = {'One':'f1','Two':'f2','Three':'f3','Four':'f4'};
$(document).ready(function() {
$('#mybutt').click(function() {
var errMsg='', badFlds='', firstBad='';
for(var key in arrAll){
chkFld = '#'+arrAll[key];
$(chkFld).removeClass('error');
if ($(chkFld).val() ==''){
$(chkFld).addClass('error');
//alert('Please complete field ' + arrAll[key] );
errMsg += '*' + key + '\n';
if (firstBad=='') firstBad=chkFld;
}
}
if (errMsg != '') {
alert(errMsg);
$(firstBad).focus();
return false;
}
//If it gets to here, it passed validation
$('#yourForm').submit();
}); //END mybutt.click()
}); //END $(document).ready()
</script>
</head>
<body>
<form id="yourForm">
One: <input type="text" id="f1" /><br />
Two: <input type="text" id="f2" /><br />
Three: <input type="text" id="f3" /><br />
Four: <input type="text" id="f4" /><br />
</form>
<input type="button" id="mybutt" value="Click Me">
</body>
</html>
Note that, using the above scenario, no further PHP code would execute until the form is submitted, using the manual $('#yourForm').submit(); statement.

How do I fetch a value from multiple select used by asmselect?

I have my code with a form.
I validate this with a javascript function sub().
When validation successful inside the javascript function i post to a php file by $.POST.
I can fetch the name field by its id name.
But I cant fetch the Cities as it has multiple value.
I am using jquery asmselect for multiple selection.
Can any one help me to fetch the multiple values of cities.
I tried by its id but failed to do.
Plz help me.............
My javascript code
<link rel="stylesheet" type="text/css" href="../jquery.asmselect.css" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.ui.js"></script>
<script type="text/javascript" src="jquery.asmselect.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("select[multiple]").asmSelect({
addItemTarget: 'bottom',
animate: true,
highlight: true,
sortable: true
});
});
</script>
<script type="text/javascript">
function sub(){
var udt;
var name = document.getElementById('name').value;
var cities = document.getElementById('cities').value;
if(name!=""&&cities!=""){
udt ="name="+name+"&cities="+cities;
$.post( "submit.php", udt, function( data ) {
window.location.href = "/";
});
return false;
} else {
alert("Please, Complete the Registration Form...");
return false;
}
}
</script>
My html code is below
<form action="" onsubmit="return sub()" method="post">
<input type="text" id="name" name="name"/>
<select id="cities" multiple="multiple" name="cities[]" title="Select City">
<option>Paris</option>
<option>San Diego</option>
<option>San Francisco</option>
<option>Vancouver</option>
</select>
<input type="submit" name="submit" value="submit" />
</form>
Plz help me to solve my problem.
I can not find any solution. So I post this question here, thanks.
Try this (add whatever delimiter you want):
cities = '';
$("select[multiple] option:selected").each(function(){
cities += $(this).val() + '|';
});

Categories