JS Measure the word and take action - javascript

How to write a script in Javascript, which will measure the number of characters from the input text field on the form and if it is less than 2 will display an alert when you try to send the form, and if it is more than or equal to 2, will send the form with click send?

There are many ways of achieving this, including:
1- Adding a pattern attribute to your input element:
<form>
<input type="text" pattern=".{2,}">
<input type="submit" value="Submit">
</form>
In this case, if the input is invalid, the form will not submit and display the browser's default error message.
The regular expression .{2,} matches all strings with length 2 or more.
2 - Checking the length of the input value via Javascript, and taking action accordingly:
function validate() {
var text = document.getElementById("input").value;
if(text.length < 2) {
//display an alert or whatever
console.log("invalid");
return false; //form will not submit
}
return true; //form will submit
}
<form onsubmit = "return validate();">
<input type="text" id="input">
<input type="submit" value="Submit">
</form>
Using this method, once the form's submit button is clicked, the function validate() will execute. If the function returns true, the form will submit. If it returns false, the form will not submit.
Method 1 is quicker, while method 2 is more customizable/flexible.

In the submit button inside the form, consider doing the following:
<button onclick="checkValidity()">Submit</button>
And within <script> tags inside the body of the html add the following code:
function checkValidity(){
var val = document.getElementById('inputfield').value; //I'm assuming the id of the input text field to be inputfield
if(val.length<2) window.alert('too short');
}

Another simple way :
HTML :
<form id="form1">
<input id="input2" type="text" placeholder="your text here"></input>
<button type="submit">submit</button>
</form>
JS:
$('#form1').submit(function(event){
if($('#input2').val().length < 2){
event.preventDefault();
alert('ur input text will be more than 1 character');
}
});
Don't forget to import jQuery library before the code :
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>

Related

fill and submit form using javascript from console

Here is my form:
<form id="myForm">
<input id="htmlString" type="text" name="htmlField" ><br>
<input type="Submit" value="Submit" >
</form>
And need to fill it from console.
just to use it in my app,
Will inject javascript with data to local html file.
I tried to make the form without a submit button like so:
<body>
<form id="myForm">
<input id="htmlString" type="text" name="htmlField" ><br>
</form>
<script>
htmlString.oninput = function(){
///do some stuff
}
</script>
</body>
Expecting that :
document.getElementById('htmlString').value="moo" ;
It automatically submit the form, because here oninput used.
But it just stayed filled with inputs and not proceed further.
Tried with other solution:
form = document.getElementById("myForm")
form.submit()
But it just refreshed the page and not submitted the form.
The need is just one filed without else, and inject my string to it with javascript to run functions embedded in the html.
Try making the input button hidden.
<body>
<form id="myForm">
<input id="htmlString" type="text" name="htmlField" ><br>
<input type="Submit" value="Submit" style="display: none" >
</form>
<button onclick="simulateConsole()">Try it</button>
<script>
htmlString.oninput = function(){
if(this.value === "moo") {
myForm.submit();
}
}
// This event will be triggered even if you use console
htmlString.onsubmit = function(){
if(this.value === "moo") {
// do something onSubmit
}
}
function simulateConsole() {
// you can simulate this in console
htmlString.value = "moo";
myForm.submit();
}
</script>
</body>
I hope it helps.
You need to supply an action to the form, otherwise it will just reload the page.
See more here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form

Pass the specific submitted form to a function with jQuery/Javascript

I want to intercept a form submission, then pass the form as a variable to a Javascript function, then grab form element values within that specific form. In my example, there could be more than one form with class "formtype". I don't think what I have here is quite correct, but maybe close? How do I reference the specific form that has been submitted, in case of multiple "formtype" class forms?
$('.formtype').on('submit', function(e){
var $submittedform=$(this);
e.preventDefault();
processForm($submittedform);
});
function processForm($submittedform){
var email=$($submittedform+' .email').val();
}
You are pretty close, but use find() instead of the string concatenation
$('.formtype').on('submit', function(e) {
var $submittedform = $(this);
e.preventDefault();
processForm($submittedform);
});
function processForm($submittedform) {
console.log($submittedform.find('input.email').val())
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="formtype">
<input class="email" value="foo">
<input type="submit">
</form>
<form class="formtype">
<input class="email" value="bar">
<input type="submit">
</form>

Pop up if values are under -5

I have a database with a table called "quote". It stores a margin field which is updated by users using an ajax table. This is in "process2.php" file.
I want a pop-up message saying "are you sure you want to put this margin" when the user clicks on the submit button if a margin value is below 5".
This is my submit form.
<form action="process3.php" method="POST" enctype="multipart/form-data">
<input type="submit" name="submit" value="Generate Quote"/>
</form>
You could do this with JavaScript (and jQuery, in this example). Your form would need an ID, as below:
<form action="process3.php" method="POST" id="myForm">
<input type="text" name="checkMargin1" />
<input type="text" name="checkMargin2" />
<input type="submit" value="Send" />
</form>
And then this would go into the head of your document:
<script type="text/javascript">
$('#myForm').onSubmit(function() {
var check1 = $('input[name="checkMargin1"]').val();
var check2 = $('input[name="checkMargin2"]').val();
if (check1 <= 5 || check2 <= -5) {
var answer = confirm("Are you sure you want to submit?");
return answer;
} else {
return true;
}
});
</script>
That function is fired when your form is submitted. It gets the values of the two margin fields (adding more should be easy) and checks if they are over -5. If they are, then return true allows the form to submit. If they are not, then a prompt dialog asks the user, which returns true when they click "Okay" and false when they click "Cancel", thus allowing or stopping the form from being sent.
Hope this helps :)

JS validation false, form still submitting

I've got a JS problem. My validation seems to be working, checking that the user inputs a valid number which isn't zero, but the form is still submitting. I have seen this question asked many times but I can't find a solution that works for me. Any ideas would be great.
My Javascript
function checkNotZero()
{
var theNumber = document.getElementById("theNumber").value;
var str = /^\+?[1-9]\d*$/.test(theNumber);
if ( str == false ) {
alert('You have not entered a valid number');
return false;
} else {
document.getElementById('numberCheck').submit();
}
}
My HTML
<form action="/next.php" method="post" id="numberCheck">
<input type="text" id="theNumber" value="0">
<button id="submitButton" OnClick="checkNotZero();">Add to Basket</button>
</form>
Use an <input type="submit"> for the submit button.
Validate on the form's submit event rather than some onclick. Forms can get submitted in other ways than just clicking a button (for instance, pressing "enter", or procedurally through code).
Prefer .addEventListener to attributes for attaching events to elements. Use preventDefault() to prevent form submission.
Hi for the above requirement of 'validating form' java script validation should be done
when the form gets submitted. follow the below approach, form will not get submitted
until and unless the validation is correct.
<html>
<head>
<script type="text/javascript">
function checkNotZero()
{
var theNumber = document.getElementById("theNumber").value;
var str = /^\+?[1-9]\d*$/.test(theNumber);
if ( str == false ) {
alert('in');
alert('You have not entered a valid number');
return false;
} else {
document.getElementById('numberCheck').submit();
}
}
</script>
</head>
<body>
<form action="/next.php" method="post" id="numberCheck" onsubmit="return
checkNotZero()">
<input type="text" id="theNumber" value="0">
<button id="submitButton">Add to Basket</button>
</form>
</body>
</html>
the only change is <form action="/next.php" method="post" id="numberCheck"
onsubmit="return checkNotZero()">
do not use onclick event in submit button.

When working with a form element how would you access what was input into the element to display a message?

I have a form
<form>
<input id="input" type="number">
<input type="submit">
</form>
I want to be able to input a number into the number and click the submit button and javascript displays a number based on the number submitted.
(My Guess is that this question is very basic but I am pretty knew to javascript.)
Here is a very simple (jquery-less) example of what you might be after:
<script type="text/javascript">
function ShowANumber() {
var currentNumber = document.getElementById("input").value;
var newNumber = currentNumber * 10 // Do something with input
document.getElementById("result").innerHTML = newNumber;
return false; // Stop form submit
}
</script>
<form onsubmit="return ShowANumber();">
<input id="input" type="text"/>
<input type="submit"/>
</form>
<div>Result: <span id="result"></span></div>

Categories