I looked over my code and changed it and everything looks alright I just dont understand why it is not working! When I open it in my browser and enter a phone number and press the button nothing happens. It does not alert me like I want it to.
<html>
<head>
<title>Phone Number Validation</title>
</head>
<body>
<script language="javascript">
window.onload=function(){
document.getElementById("valButton".onclick=validateIt;
}
function validateIt(){
var phoneno = /^\d{10}$/;
if((inputtxt.value.match(phoneno))
{
alert("Yay it's a phone number!");
return true;
}
else
{
alert("Not a valid number");
return false;
}
}
</script>
<p>Phone Number Validation:</p>
<p>Enter a phone number here:<br>
<input type="text" size=30 id="phoneno" /><br>
<input type="button" value="Validate" id="valButton" />
</p>
</body>
</html
Add an "onblur=phonenumber()" to your input, to trigger calling the function when control leaves the input (click or tab away).
Issues:
1- The function is never called
2- The function has a syntax error
function phonenumber(inputtxt) {
var pattern = "/^\d{10}$/",
phoneno = new RegExp(pattern);
if (inputtxt) {
if(inputtxt.match(phoneno)) {
return true;
} else {
alert("message");
return false;
}
}
}
//Using jQuery for DOM manipulation you can execute the function on validate button click
$('#valButton').on('click', function () {
var phoneInputValue = $('#phoneno').val();
phonenumber(phoneInputValue);
});
Checkout fixed code here:
https://jsfiddle.net/au7aft0k/2/
The function you have written never gets executed. You need to add an event handler onto the button and/or the input itself. The easiest way to do so is after the DOMContentLoaded event fires (DOM has been parsed).
var btn = document.getElementById( 'valButton' );
btn.addEventListener( 'DOMContentLoaded', function(){
var txt = document.getElementById( 'phoneno' ).value;
if ( phonenumber( txt ) ) {
alert( 'Test passed. Do stuff here' );
} else {
alert( 'Test failed!!' );
}
}, false );
Similarly if you want to automatically check after the person leaves the input field you would use:
var input = document.getElementById( 'phoneno' );
input.addEventListener( 'blur', function(){
if ( phonenumber( input.value ) ) {
alert( 'Test passed. Do stuff here' );
} else {
alert( 'Test failed!!' );
}
}, false );
Related
A php page has a jquery interface.
an on submit button dynamically writes an alert.
the confirm box is of the style : return confirm.
in other words there is a script on the page that does something like this:
confirm (okay cancel );
I need a way of listening for when the alert has been dynamically written so I can confirm it dynamically.
any ideas?
is there an event listener for 'confirm'?
<html>
<head>
<script>
function getConfirmation() {
var retVal = confirm("Do you want to continue ?");
if( retVal == true ) {
document.write ("User wants to continue!");
return true;
} else {
document.write ("User does not want to continue!");
return false;
}
}
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" onclick = "getConfirmation();" />
</form>
</body>
</html>
You can use window.confirm = function() { } to intercept the confirm command.
Returning true would be the same as clicking the "ok" button.
window.confirm = function() { return true; }
if (window.confirm("Delete everything?") == true)
{
alert("Deleting all your files as you confirmed")
}
I have the following form on my site. It's simple, one search input field and one submit button:
<form id="search-form" name="search-form" onsubmit="return search()">
<input type="search" id="query" class="search-field" value="<?php echo $searchQuery;?>">
<input type="submit" name="search-btn" id="search-btn" value="">
</form>
As you can see, in the search field (id=query) I have a php which sometimes inserts value into his field.
What I want to do is following:
If $searchQuery doesn't exist (or in other words, if value of search
field id=query is empty, allow user to click on the search button
manually.
If $searchQuery exist, auto submit the the form (simulate click on
the search button.
Any solution will help, JavaScript, jQuery or in PHP. I just need to figure out how to auto submit this form when PHP variable $searchQuery exists.
I believe you are asking specifically on initial page load. Use jQuery:
$(document).ready(function() {
if ($('#query').val() !== '') {
$('#search-form').submit();
}
});
You would need to just look to see if the value is populated and submit the form if it is.
jQuery Version:
$( function() {
if ( $( '#query' ).val() !== '' ) {
$( '#search-form' ).submit();
}
});
Fiddle: https://jsfiddle.net/fe9m8pk3/
Javascript Version:
function ready( fn ) {
if ( document.attachEvent ? document.readyState === 'complete' : document.readyState !== 'loading' ) {
fn();
} else {
document.addEventListener( 'DOMContentLoaded', fn );
}
}
ready( function() {
if ( document.getElementById( 'query' ).value != '' ) {
document.getElementById( 'search-form' ).submit();
}
});
Fiddle: https://jsfiddle.net/qeo25yu1/
<script type="javascript/text">
var query = document.getElementById('query');
if(query.value != ''){
//do your submit
}
function yoursubmitfunctionname(){
//do your submit
}
query.addEventListener('change',yoursubmitfunctionname);
</script>
This code will submit form if character length minimum fullfiled using Jquery:
$(document).ready(function ()
{
var minimum_character = 7;
$('#query').on('propertychange input', function (e)
{
var valueChanged = false;
if(e.type=='propertychange')
{
valueChanged = e.originalEvent.propertyName=='value';
}
else
{
valueChanged = true;
}
if(valueChanged)
{
str_length = $('#query').val().length;
if(str_length == minimum_character)
{
$("#search-form").submit();
}
}
});
});
This is a question from my elder brother's question paper which I'm trying to solve but I am not able to do so .
Create a form containing a two Text fields and radio button and submit button. Name the
text fields account number and amount and radio button as transaction (deposit ,withdraw
and enquiry).Write a JavaScript the validates the text field to have only numbers, the first
text field should be of size 10 and second text field should have values between 500 to
20,000. Using onclick event a jQuery is called that performs necessary transactions and
display the updated value.
.............................................................................
So I have written the following code:
form1.html
<!DOCTYPE html>
<html>
<head>
<title>Web Tech DA 1</title>
<script type="text/javascript" src="script1.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$('#sub').click(function() {
var acc=document.getElementById("acc").value;
var amt=document.getElementById("amt").value;
var bal=acc%100;//balance , I am using this to dynamically generate a new balance each time a new account number is entered
$("#t1").click(function(){
bal=acc+amt;
alert(bal);
});
$("#t2").click(function(){
if(acc>amt){
bal=acc-amt;
alert(bal);
}
else{
alert('Insufficient Funds.');
}
});
$("#t3").click(function(){
alert(bal);
});
});
});
</script>
</head>
<body>
<form name="myform" onsubmit="if(validateform()) {window.alert('succefully submitted')} else {return false;}" >
<p>Account Number : <input type="text" maxlength="10" name="acc" id="acc" height="20px" width="100px" required="required" onblur="validacc(this.value)"></p>
<p>Amount : <input type="text" name="amt" id="amt" height="20px" width="100px" required="required" onblur="validamt(this.value)"></p>
<p>Transaction : <input type="radio" name="trans" id="t1" value="deposit" />Deposit
<input type="radio" name="trans" id="t2" value="withdraw" />Withdraw
<input type="radio" name="trans" id="t3" value="enquiry" />Enquiry </p>
<input type="submit" name="sub" id="sub" value="Submit">
</form>
</body>
main1.css
*{
margin:0;
padding: 0;
}
body{
margin: 25px;
}
form p {
margin: 10px;
}
form input {
margin: 10px;
}
script1.js
function validateform() {
var acc = document.getElementById("acc").value.trim();
var amt = document.getElementById("amt").value.trim();
if(validregno(acc)&&validname(amt))
{window.alert("No errors found");return true;}
else
{window.alert("invalid entries found");return false;}
}
// Overall Go
function validacc(r)
{
var p = new RegExp(/^[0-9]{10}$/i);
if(!p.test(r))
{
chngborder("acc");
return false;
}
chngborderr("acc");
return true;
}
function validamt(amt)
{
var p = new RegExp( /^[0-9]{1,}$/);
if(amt>=500 && amt<=20000){
if(p.test(n))
{
chngborderr("amt");
return false;
}
else
{
chngborder("amt");
return true;
}
}
chngborder("amt");
return false;
}
function chngborder(i)
{
document.getElementById(i).style.borderColor="red";
}//red color means wrong format
function chngborderr(i)
{
document.getElementById(i).style.borderColor="green";
}//green color means correct format
For some reason I'm not able to enter a number in the "Amount" text field and none of the radio buttons are working .
Please point out any mistakes that I have done here .
P.S. I'm new to jQuery and form validation
UPDATE
I made the changes pointed out and even then for some reason the "Amount" text field doesn't get validated and the "submit" button resets the form .
I am analysing your code. if this is exactly what you have, I can notice that
1 - You did not include jQuery library in the of you.
you can do it by adding <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> or <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.4.min.js"></script> inside the <head> element
2 - I think it is better to add and Else in onsubmit event of #myForm
if(validateform()) window.alert('succefully submitted'); else return false.
3 - I have never seen a javascript (.js files) variable declaration starting by int: they start with var keyword regardless the type of the variable
Here is a working code.
script1.js
function validateform() {
var accValue = document.getElementById("acc").value.trim();
var amtValue = document.getElementById("amt").value.trim();
if (validacc(accValue) && validamt(amtValue))
{ window.alert("No errors found"); return true; }
else
{ window.alert("invalid entries found"); return false; }
}
// Overall Go
function validacc(r) {
var p = new RegExp(/^[0-9]{10}$/i);
if (!p.test(r)) {
chngborder("acc");
return false;
}
chngborderr("acc");
return true;
}
function validamt(amt) {
var p = new RegExp(/^[0-9]{1,}$/);
var amtValue = document.getElementById("amt").value;
if (amtValue >= 500 && amtValue <= 20000) {
if (p.test(n)) {
chngborderr("amt");
return false;
}
else {
chngborder("amt");
return true;
}
}
chngborder("amt");
return false;
}
function chngborder(i) {
document.getElementById(i).style.borderColor = "red";
}//red color means wrong format
function chngborderr(i) {
document.getElementById(i).style.borderColor = "green";
}
//Script inside your html file
$(document).ready(function () {
$('#sub').click(function() {
var accValue = document.getElementById("acc").value;
var amtValue = document.getElementById("amt").value;
var bal = accd % 100;})
$("#t1").click(function(){
bal = Number(document.getElementById("aac").value) +
Number(document.getElementById("amt").value);
alert(bal);
});
$("#t2").click(function(){
if(acc > amt){
Number(document.getElementById("aac").value) +
Number(document.getElementById("amt").value);
alert(bal);
}
else{
alert('Insufficient Funds.');
}
});
});
I am working with a javascript function which works first time but not from the 2nd time.The console shows: Uncaught TypeError: pizza_name is not a function
My html is :
<div class="pizza_name_div">
<input type="text" name="pizza_name" id="pizza_name" placeholder="Enter your pizza name as u like. i.e : my-pizza" value="">
<input type="submit" value="Go" id="pizza_name_submit" onclick="pizza_name()">
</div>
And My js
function pizza_name() {
if( pizza_name != "" ) {
.........
}else{
alert( "please enter a name" );
}
}
It shows alert properly for 1st time.But not form 2nd
Link
js code:
function pizza_name() {
var pizzaName=document.getElementById("pizza_name").value;
if(!pizzaName ) {
alert("no value");
}else{
alert( "please enter a name" );
}
}
Change your code with:
function pizza_name() {
var pizzaName = document.getElementById('pizza_name').value;
if(pizzaName != "") {
//.........
} else {
alert( "please enter a name" );
}
}
It's very important to not assign any value to a possible pizza_name variable inside the function.
You can use jquery for this too
HTML
<div class="pizza_name_div">
<input type="text" name="pizza_name" id="pizza_name" placeholder="Enter your pizza name as u like. i.e : my-pizza" value="">
<input type="submit" value="Go" id="pizza_name_submit" >
</div>
JQUERY
$(document).ready(function(){
$("#pizza_name_submit").on("click", function(){
if( $("#pizza_name").val()) {
alert( $("#pizza_name").val());
}else{
alert("enter value");
}
});
});
demo
Don't re-use names, you're probably overwriting your function to be a string instead.
(that's what I'm assuming happens in the code you didn't show since you're trying to test pizza_name as a string)
function pizza_name() {
if( pizza_name != "" )
You'd be better off naming the function something like getPizzaName. Name the function for what it does, not what it returns.
I tried to do a simple validation on a button, but when I click the button without entering anything it still goes to testValidation1.html instead of popping up the alert window.
<html>
<head>
</head>
<body>
<form action="testValidation1.html">
Parameter1 :
<input type = 'text' name = 'param1'/><br>
<input type='submit' value = 'submit' onclick = 'return validateForm()'>
</form>
<script type="text/javascript">
function validateForm() {
var f1 = document.forms[0];
var p1 = f1.param1;
if(p1.value.length == 0) {
alert('Plz enter parameters');
p1.focus();
return false;
}
}
</script>
</body>
</html>
you might find it easier to use the submit event of the form to validate
function validateForm(event) {
var form = this;
var p1 = form.elements['param1'];
if(p1.value.length === 0) {
alert('Plz enter parameters');
p1.focus();
event.preventDefault();
return false;
}
}
document.getElementById('form').addEventListener('submit', validateForm);
http://jsfiddle.net/7j0usuam/