I have a form, with a number of textboxes which a user can fill in. At the bottom of the form I have two buttons. One for canceling and one for submitting. Like the example below
<form action='bla.php' method='post'>
<input type='text' name='someTextField1'>
<input type='text' name='someTextField2'>
<input type='text' name='someTextField3'>
<input type='submit' name='submit'>
<input type='submit' name='cancel'>
</form>
And I have a js function that checks the fields for their data which I used to use for both buttons. I therefor refer to the js function in the form as below:
<form action='bla.php' method='post' name='form' onSubmit='return CheckFields()'>
The js function looks like this:
function CheckFields() {
var formname = "form";
var x = document.forms[formname]["someTextField1"].value;
var result = true;
var text = "";
if (x == null || x == "") {
text += "Dont forget about the someTextField1.\n";
result = false;
}
if(!result)
alert(text);
return result;
}
Now I want this js function to only run when using the submit and not the cancel button. When I try to move the call to the function to the submit button as below it doesn't work:
<input type='submit' name='submit' onClick='return CheckFields()'>
<input type='submit' name='cancel'>
Why? What is the smartest way of solving this? Should I leave the call to CheckFields() in the form and check within the script what button was clicked or should I remake the function to somewhat work with a button instead? Anyone have an idea or an example?
replace <input type='submit' name='cancel'> by <input type='button' name='cancel'>.Your Version actually has two submit-buttons, both of which will submit the form.
Watch this sample http://jsfiddle.net/355vw560/
<form action='bla.php' method='post' name="form">
<input type='text' name='someTextField1'>
<input type='text' name='someTextField2'>
<input type='text' name='someTextField3'>
<br/>
<input type='submit' name='submit' onclick="return window.CheckFields()">
<input type='submit' name='cancel' value="cancel" onclick="return false;">
anyway it's always better to use jquery or event listeners instead of managing events directly in the dom.
The function didnt worked because its scope was the element, if u specify window as context your function works.
First at all, it's not needed have submit button on a form if you want to use javascript to check all the fields before submitting.
I think the smartest way of doing it will be as follow:
Your form (without action, submit button, and method. Only identifing each component with id's):
<form id="formId">
<input type='text' id="text1">
<input type='text' id="text2">
<input type='text' id="text3">
<input type='button' id="accept">
<input type='button' id="cancel">
</form>
Your javascript (you have to have jQuery added):
jQuery("#formId").on("click", "#accept", function(){ //listen the accept button click
if(CheckFields()){ //here you check the fields and if they are correct
//then get all the input values and do the ajax call sending the data
var text1 = jQuery("#text1").val();
var text2 = jQuery("#text2").val();
var text3 = jQuery("#text3").val();
jQuery.ajax({
url: "bla.php",
method: "POST",
data: {
"someTextField1":text1, //In your example "someTextField1" is the name that the bla.php file is waiting for, so if you use the same here, it's not needed to change anything in your backend.
"someTextField2":text2,
"someTextField3":text3
},
success: function(){
//here you can do whatever you want when the call is success. For example, redirect to other page, clean the form, show an alert, etc.
}
});
}
});
jQuery("#formId").on("click", "#cancel", function(){ //here listen the click on the cancel button
//here you can clean the form, etc
});
function CheckFields() { //here I did a little change for validating, using jQuery.
var x = jQuery("#text1").val();
var result = true;
var text = "";
if (x == null || x == "") {
text += "Dont forget about the someTextField1.\n";
result = false;
}
if(!result)
alert(text);
return result;
}
I hope it helps you!
I handle it with this way , Hope it will help.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<form method="post" action="/">
<div class="container" style="background: #efefef; padding: 20px;">
<label>Encrypt and decrypt text with AES algorithm</label>
<textarea name="inputText" id = "inputText" rows="3" cols="100" placeholder="Type text to Encrypt..." maxlength="16" ></textarea>
<br>
<br>
<textarea name="inputKey" id = "inputKey" rows="1" cols="100" placeholder="Type key to Encrypt\Decrypt text with..." maxlength="16"></textarea>
<br>
<br>
<label>SBox :</label>
<div>
<div class="s-box-radios">
<ul class="sbox">
<li>
<label>SBox 1
<input id="sbox1" name="sboxOption" type="radio" value="option1" required/>
</label>
</li>
<li>
<label>SBox 2
<input id="sbox2" name="sboxOption" type="radio" value="option2" />
</label>
</li>
<li>
<label>SBox 3
<input id="sbox3" name="sboxOption" type="radio" value="option3" />
</label>
</li>
<li>
<label>SBox 4
<input id="sbox4" name="sboxOption" type="radio" value="option4" />
</label>
</li>
</ul>
</div>
<div class="s-box-display">
<textarea rows="5" cols="10"></textarea>
</div>
</div>
<div class="clear"></div>
<br>
<label>Result of Decryption in plain text</label>
<textarea name="inputCipher" rows="3" cols="100" placeholder="Encrypted Texts..." name="decrpyted"></textarea>
<br>
<input type="submit" value="Encrypt" name="Encrypt" id ="encrypt" onclick="valEncrypt()" />
<input type="submit" value="Decrypt" name="Decrypt" id ="decrypt" onclick="valDncrypt()" />
</div>
</form>
<script>
function valEncrypt()
{
var inputText = document.getElementById('inputText');
var inputkey = document.getElementById('inputKey');
if (inputText.value.length <16)
{
doAlert(inputText);
return false;
}
else
{
removeAlert(inputText);
}
if (inputkey.value.length <16)
{
doAlert(inputkey);
return false;
}
else
{
removeAlert(inputkey);
}
}
function valDncrypt()
{
var inputkey = document.getElementById('inputKey');
if (inputkey.value.length <16)
{
doAlert(inputkey);
return false;
}
alert('!Success');
}
function doAlert(element){
element.style.border = "1px solid #FF0000";
}
function removeAlert(element){
element.style.border = "1px solid #000000";
}
</script>
</body>
</html>
Related
I have to do the validation of the input text field.
I would like Js to show an error message through the setCustomValidity() method.
Is it possible?
function checkName() {
var x = document.formUser;
var input = x.name.value;
if (input.length < 3) {
input.setCustomValidity('This field is invalidate');
return false;
}
}
<form name="formUser" id="formUser" action="#" method="POST" onsubmit="return validateForm();">
<div class="section">
<label for="fname">Nome</label>
<input class="form-control" type="text" id="name" required>
</div>
<input type="submit" class="btn btn-primary" value="Invia" onclick="validateForm();">
</form>
You need to call reportValidity() on the input after setting the custom validity message.
Additionally you must call the reportValidity method on the same element or nothing will happen.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLObjectElement/setCustomValidity#examples
function checkName() {
const inp = document.getElementById('name');
const val = inp.value;
if (val.length < 3) {
inp.setCustomValidity('This field is invalidate');
inp.reportValidity();
return false;
}
}
<form name="formUser" id="formUser" action="#" method="POST" onsubmit="return checkName();">
<div class="section">
<label for="fname">Nome</label>
<input class="form-control" type="text" id="name" required>
</div>
<input type="submit" class="btn btn-primary" value="Invia" onclick="checkName();">
</form>
I would like to control more text input with javascript.
The setCustomValidity() method means that it will have to show an error message if input has less than three characters.
it doesn't always work.
Eg. If I put a string of one character in the first field and a string of four in the second field; it sends without showing the error. If I repeat the same test, it works.
Why?
window.onload = function() {
const field = document.getElementsByClassName("input-field");
for (let i = 0; i < field.length; i++) {
field[i].addEventListener('input', function() {
const val = field[i];
if (val.length < 3) {
field[i].setCustomValidity('Field is invalid');
}
})
}
}
<form name="formUser" id="formUser" action="#">
<div class="section">
<label for="fname">First name</label>
<input class="form-control input-field" type="text" id="fname" required>
<label for="lname">Last name</label>
<input class="form-control input-field" type="text" id="lname" required>
</div>
<input type="submit" class="btn btn-primary" value="Send">
You could add a <p class="error">...</p> inside your section div.
Hide it with css (display: none) and when you get an error in your validation add a class to that like "show" to show it (display: unset).
You can do custom form validation using Javascript like this.
Here I have just added a div with a warning and alert box. You can do whatever you want.
It will alert a warning if you will click on submit when fields were empty.
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
let alertBox = document.getElementById("alert-box");
// Here instead of checking (x == " "), you can use your custom validations
if (x == "") {
alertBox.innerHTML = `<p>Form input are empty</p>`; // appends a div with warning
alert("Name must be filled out"); // alert box
return false;
}
}
</script>
</head>
<body>
<h2>JavaScript Validation</h2>
<div id="alert-box"> </div>
<form name="myForm" action="#" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>
Would like your help resolving this piece of code.
Trying to clear inputs after submit but not able to.
Can someone give me a hint??
Thank you so much.
<script>
var list = document;
function process(idTable)
{
var newRow = list.createElement('tr');
newRow.insertCell(0).innerHTML = list.getElementsByName('name')[0].value;
newRow.insertCell(1).innerHTML = list.getElementsByName('surname')[0].value;
newRow.insertCell(2).innerHTML = list.getElementsByName('email')[0].value;
list.getElementById(idTable).appendChild(newRow);
return false;
list.getElemntsByName('form')[0].value="";
}
</script>
<section>
<form name="form" method="post" id="myForm" onsubmit=" return process('myTable')" >
<p> <label>Name:</label> <input type="text" name="name" placeholder = "Your first name" required> </p>
<p> <label>Surname:</label> <input type="text" name="surname" placeholder = "Your last name" required> </p>
<p> <label>Email:</label> <input type="e-mail" name="email" placeholder = "xpto#example.com" required> </p>
<p> <input type="submit" value="Add"> <input type="reset" value="Reset"> </p>
</form>
</section>
Two points:
You exited the function before assign value to the form
Better use list.getElemntsByName('form')[0].reset();
So your code will be like this:
<script>
var list = document;
function process(idTable)
{
var newRow = list.createElement('tr');
newRow.insertCell(0).innerHTML = list.getElementsByName('name')[0].value;
newRow.insertCell(1).innerHTML = list.getElementsByName('surname')[0].value;
newRow.insertCell(2).innerHTML = list.getElementsByName('email')[0].value;
list.getElementById(idTable).appendChild(newRow);
list.getElemntsByName('form')[0].reset();
return false;
}
</script>
Why don't you use button tag for your 'submit' and 'reset', then in that use clientclick event, have reset function that clears the input tag.
Use $('#id of input element ').val(' ') inside process function . Also write this code above return false statement
I'm coding a form on HTML with JS that asks for the user to enter their name and displays it. I would like the form and the button to disappear when they hit submit.
<form>
<br/>What is your name: <input type="text" id="name" />
<input type="button" value="done" onclick="write_name();" />
</form>
<h4 id=welcome></h4>
The script is below:
function write_name() {
var welcome_parra = document.getElementById('welcome');
var name = document.getElementById('name');
welcome_parra.innerHTML = "Welcome " + name.value + "!";
}
Jquery Code
$(document).ready(function () {
$("#btn_sbumit").click(function () {
$(this).next().text($("#name").val());
$("#name").hide();
$(this).hide();
});
});
HTML Code
<input type="text" id="name" value="" />
<input type="button" id="btn_sbumit" value="Submit" />
<span></span>
I want to pass the value 9112232453 of one textfield to another.
I know I need Javascript for this but I don't know how to do it.
HTML
<form method = "post" action="">
<input type="checkbox" name="phone" value="9112232453" onclick='some_func();' >
<input type="text" name="phone" value="" id="phone">
<input type="submit" name="Go">
</form>
Then later, I want to use the value in my php.
You could use a JS. function to take param (this.value) like:
<script>
var some_func = function (val){
var input = document.getElementById("phone");
input.value = val;
}
</script>
<form method = "post" action="">
<input type="checkbox" name="phone" value="9112232453" onclick='some_func(this.value);' >
<input type="text" name="phone" value="" id="phone">
<input type="submit" name="Go">
</form>
The best way is to not obtrude the HTML code with Javascript event handlers.
So, you can add a DOMContentLoaded event listener to the document, and as soon as DOM is loaded:
You add a change event listener to the input[type=checkbox], and then:
1.1. If the checkbox is checked, then you change the input#phone's value to its value
1.2. If not, then you empty the input#phone's value.
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('cbphone').addEventListener('change', function(e) {
var phone = document.getElementById('phone');
if (this.checked) {
phone.value = this.value;
// you can even enable/disable the input#phone field, if you want to, e.g:
// phone.disabled = false;
}
else {
phone.value = '';
// phone.disabled = true;
}
});
});
<form method="post" action="">
<input type="checkbox" name="cbphone" id="cbphone" value="9112232453">
<input type="text" name="phone" id="phone">
<input type="submit" name="Go" value="Go">
</form>
before submit form use validation and check whether the field value is filled up or not. if yes get value of the field.
if(document.getElementBy("fieldIdfirst").value!="")
{
document.getElementBy("fieldIdSecond").value=document.getElementElementById("fieldIdfirst");
}
Thanks it..
Try this: http://jsfiddle.net/yhuxy4e1/
HTML:
<form method = "post" action="">
<input type="checkbox" name="phone" value="9112232453" onclick='some_func();' id="chk_phone">
<input type="text" name="phone" value="" id="txt_phone">
<input type="submit" name="Go">
</form>
JavaScript:
some_func = function() {
var checkBox = document.getElementById('chk_phone');
var textBox = document.getElementById('txt_phone');
textBox.value = checkBox.value;
}
I have the following code written in angular JS
<html lang="en" ng-app="person_info">
<head>
<meta charset="utf-8">
<title>Person info</title>
<script src="../angular.min.js"></script>
<script src="controller_class2.js"></script>
<style type="text/css">
.forms{width:200px;height:300px;padding:75px;float:left;background:#CCC;}
.deatils{width:200px;height:auto;padding:100px;float:left;background:#CCC;margin- left:10px;}
.fields {background:#999999;float: left;height:120px;padding: 20px;width:260px;}
</style>
</head>
<body ng-controller="info">
<div class="forms"> Name:</br>
<input type="text" value="name" ng-model="person.name">
</br>
</br>
First Name :</br>
<input type="text" value="fname" ng-model="person.firstname">
</br>
</br>
Phone Number :</br>
<input type="number" value="number" ng-model="person.number">
</br>
</br>
Email :</br>
<input type="email" value="email" ng-model="person.email">
</br>
</br>
Address :</br>
<input type="text" value="address" ng-model="person.address">
</br>
</br>
<input type="submit" value="submit" name="submit" ng-click="test()">
</div>
<div class="deatils">
<p>Name : {{person.name}}</p>
<p>First Name : {{person.firstname}}</p>
<p>Phone Number: {{person.number}}</p>
<p>Email : {{person.email}}</p>
<p>Address :{{person.address}}</p></br></br>
<p>Details in json format : </br>{{ person | json }}
</div>
<div class="fields">
Submit the persons serial number to display his details
</br>
</br>
<input type="number" >
</br>
</br>
<input type="submit" value="submit number">
</div>
</body>
</html>
Controller code
var person_info = angular.module('person_info', []);
person_info.controller('info', function($scope) {
$scope.test = function () {
console.log($scope.person);
}
});
When the user fills the form and click on submit button i want the details to be saved into a array and clear all the field so that the next users details can be filled. each user details will be stored in the array.
i have also created a text field where user can enter the serial number of the user whose detail have to be displayed. for example when i enter the value 3 and submit this. the 3rd person's details in the array have to be displayed.
you can define a function like your test() function in your controller to save current model into an array and clear it, here is example function,
$scope.savePerson = function () {
$scope.personList.push($scope.person);
//clear person model/form
$scope.person = {};
};
and here is html form,
<div class="forms">
Name: <input type="text" value="name" ng-model="person.name">
First Name : <input type="text" value="fname" ng-model="person.firstname">
Phone Number : <input type="number" value="number" ng-model="person.number">
Email : <input type="email" value="email" ng-model="person.email">
Address : <input type="text" value="address" ng-model="person.address">
<input type="submit" ng-click="savePerson()">
</div>
and define another function to retrieve data from your personList[] array like this,
$scope.getPerson = function (index) {
//selected person details
$scope.personDetail = $scope.personList[index];
};
of course you shoudl make few changes in your html as well, here is full PLUNKER of my solution...
you can try extracting the value using .serialize() like this
var count=0;
var formArr={};
$('.forms input[type=submit]').on('click',function () {
formArr[count++]=$( "form" ).serialize(); //this would serialize the form data
// clear the form data for next client details entry
$(':input','#myform')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
});
$('.fields input[type=submit]').on('click',function () {
var serNo=$(this).find ('input[type=text]').val();
var formData= formArr[serNo];
formData=formData.split("&");
for(i=0;i<formData.length;i++)
{
$('input[name='+ formData[i]+']').val(formData[++i]);
}
});
Note: this is untested code, it may require few code tunings
Happy Coding :)