I need to find a way to tell if a field is empty, using javascript or html, here's the code:
<script>
function setAction(form) {
alert(form.name);
return false;
}
</script>
A Snippet like this should do the trick, putting inputx as the selected field your testing for
if (inputtx.value.length == 0){
alert("empty form");
return false;
} else
alert("filled form");
return true;
}
The alerts are just to let you know if its working, you could also use a
console.log("empty/filled form");
and then check in the web browser console
Your code snippet is so generic, but is not a problem. For solving this task you will need to get HTML input object in JavaScript and extract it's value length to compare if is greater than zero. Notice that you are not able to get HTML object if the window is not fully loaded this is why you will need to deal with DOM events.
Creating the form:
<form id="myForm" onSubmit="return false;">
<label for="name">First name:</label><br>
<input type="text" id="nameField" name="name" value="Your Name"><br>
</form>
In this example I selected enter key and will be used to check if the form field is empty or not, this is why onSubmit="return false;" event was bound to return false, avoiding reloading the page on form submit with enter key press.
Creating script part
window.onload = function windowLoaded(windowEvent)
{
const myInputFieldHtmlObject = document.querySelector("#nameField");
myInputFieldHtmlObject.onkeypress = function(event)
{
if(event.which == 13)
{
if(myInputFieldHtmlObject.value.length == 0)
{
alert("Fill please the name field.");
}
}
}
myInputFieldHtmlObject.onfocus = function(event)
{
myInputFieldHtmlObject.value = "";
}
}
Bind onload event to the window object. This guarantee that all HTML objects in the page are loaded before accessing it with document.querySelector("#nameField").
Bind on key press and on focus events to your each individual fields in the form what need checks. On key press will check after you type the name and press Enter key (value 13) if number of characters are at least 1, otherwise will pop an error.
On focus event will just clear the text input default value to nothing.
Complete example:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>My Form Test</title>
<style>
html, body
{
width: 100%;
height: 100%;
margin: 0 !important;
padding: 0 !important;
overflow: hidden;
}
</style>
<script>
window.onload = function windowLoaded(windowEvent)
{
const myInputFieldHtmlObject = document.querySelector("#nameField");
myInputFieldHtmlObject.onkeypress = function(event)
{
if(event.which == 13)
{
if(myInputFieldHtmlObject.value.length == 0)
{
alert("Fill please the name field.");
}
}
}
myInputFieldHtmlObject.onfocus = function(event)
{
myInputFieldHtmlObject.value = "";
}
myInputFieldHtmlObject.onSubmit = function(event)
{
return false;
}
}
</script>
</head>
<body>
<h2>My Form</h2>
<form id="myForm" onSubmit="return false;">
<label for="name">First name:</label><br>
<input type="text" id="nameField" name="name" value="Your Name"><br>
</form>
</body>
</html>
If you have a single form and you want the index numbers of empty fields:
function emptyFields(form) {
return [...document.forms[form]].flatMap((field, index) =>
field.value.length < 1 ? [index] : []);
}
console.log(emptyFields('data'));
<form name='data'>
<input>
<input value='not empty'>
<input>
<input>
<input value='not empty'>
<input>
</form>
Related
I want the user to be able to submit a form by clicking the submit button or the enter key. I'm using jQuery and here's my code:
<input id="weather"/>
<button id="myButton" type="text">Response</button>
</div>
<script type="text/JavaScript">
$("#myButton").keypress(function(event) {
if (event.which == 13) {
event.preventDefault();
$("#myButton").submit();
}
});
document.getElementById("myButton").onclick = function() {
if (document.getElementById("weather").value.toLowerCase() != "nice" && document.getElementById("weather").value.toLowerCase() != "crappy") {
alert("Please enter only either 'Nice' or 'Crappy.'");
} else if (document.getElementById("weather").value.toLowerCase() == "nice") {
alert("GREAT! Let's go the the BEACH!!");
} else {
alert("Hmm. That blows. Well then, I just won't be going outside today.")
}
};
</script>
Wrap the whole thing in a form tag and change the button type to submit. Enter will then submit the form.
<form>
<input id="weather"/>
<button id="myButton" type="submit">Response</button>
</form>
JSFiddle
<input type="text" id="weather" />
<input type="button" id="myButton" value="Response"/>
The onclick script should be
document.getElementById("myButton").onclick(function(){
if (document.getElementById("weather").value.toLowerCase() !="nice" && document.getElementById("weather").value.toLowerCase() !="crappy") {
alert("Please enter only either 'Nice' or 'Crappy.'");
}
else if (document.getElementById("weather").value.toLowerCase() =="nice"){
alert("GREAT! Let's go the the BEACH!!");
} else {
alert("Hmm. That blows. Well then, I just won't be going outside today.")
}
});
You should use submit type of button. It should not be a text type.
Best way is to wrap input and button with form and check input only in case of form submit like:
$(function() {
$("#weatherForm").submit(function(event) {
event.preventDefault();
var $weatherElement = $('#weather');
if ($weatherElement.val() != "Nice" && $weatherElement.val() != "Crappy") {
alert("Please enter only either 'Nice' or 'Crappy.'");
} else if ($weatherElement.val() == "Nice") {
alert("GREAT! Let's go the the BEACH!!");
} else {
alert("Hmm. That blows. Well then, I just won't be going outside today.")
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" id="weatherForm">
<input id="weather" name="weather" />
<input type="submit" id="myButton" value="Response" />
</form>
I'm trying to validate email upon submit. Right now, I have it working so that it validates if I tab from the email to submit button, and also if I click the submit button directly. However, it doesn't validate if I press Enter from within the email field. Also, once it validates on clicking submit, I have to click the button again to actually submit.
The reason is because I start with type="button" rather than type="submit" on the submit input. This is because before when I started with type="submit" it would submit regardless of whether the email was valid or not.
So now, I start with type="button", validate the email, and then change it to type="submit" on valid emails. However, like I mentioned, it still isn't the most user-friendly (even though it does work as is). I'd like to add the user-friendly features described above. Here is the code I have (note: I'm using the Mailgun jQuery email validator for the validation part):
<form accept-charset="UTF-8" id="icpsignup" name="icpsignup" action="process.php" method="post">
<p>
<input type="text" onfocus="this.value=''" onblur="this.value=!this.value?'Enter name...':this.value;" class="txtbox_index" placeholder="Enter name..." value="Enter name..." name="fields_fname" id="fields_fname">
</p>
<p>
<input type="text" class="txtbox_index" onfocus="this.value=''" onblur="this.value=!this.value?'Enter email...':this.value;" name="fields_email" id="fields_email" Value="Enter email..." placeholder="Enter email...">
<input type="text" style="border: none;color: #fff;cursor: none; background-color:transparent; height:0px;" size="1" value="<?=$country_field;?>" name="fields_country" id="fields_country">
</p>
<div id="status"></div>
<p class="forfree">
<input type="button" value="Signup For Free!" id="validate_submit" class="signupbtn_new" name="submit">
</p>
<input type="hidden" value="<?php echo $paramstring ;?>" name="fields_trk">
</form>
<script src="js/vendor/jquery.js"></script>
<script src="js/mailgun_validator.js"></script>
<script>
// document ready
$(function() {
// capture all enter and do nothing
/* $('#fields_email').keypress(function(e) {
if(e.which == 13) {
$('#fields_email').trigger('focusout');
return false;
}
});
// capture clicks on validate and do nothing
/* $("#validate_submit").click(function() {
return false;
});*/
// attach jquery plugin to validate address
$('#fields_email').mailgun_validator({
api_key: 'pubkey-8s-e-ovj0nbi32xw5eeyibrmv-lkq2e2', // replace this with your Mailgun public API key
in_progress: validation_in_progress,
success: validation_success,
error: validation_error,
});
});
// while the lookup is performing
function validation_in_progress() {
$('#status').html("<img src='images/loading.gif' height='16'/>");
}
// if email successfull validated
function validation_success(data) {
$('#status').html(get_suggestion_str(data['is_valid'], data['did_you_mean']));
}
// if email is invalid
function validation_error(error_message) {
$('#status').html(error_message);
}
// suggest a valid email
submitHandler: function(form) {
function get_suggestion_str(is_valid, alternate) {
if (alternate) {
form.preventDefault();
return '<span class="warning">Did you mean <em>' + alternate + '</em>?</span>';
} else if (is_valid) {
form.submit();
//return '<span class="success">Address is valid.</span>';
} else {
form.preventDefault();
return '<span class="error">Address is invalid.</span>';
}
}
}
// Another version of trying to using the Submithandler. I'm not sure if I'm supposed to use the validate or not.:
$(function() {
$("#icpsignup").validate({
submitHandler: function('icpsignup') {
function get_suggestion_str(is_valid, alternate) {
if (alternate) {
icpsignup.preventDefault();
return '<span class="warning">Did you mean <em>' + alternate + '</em>?</span>';
} else if (is_valid) {
icpsignup.submit();
//return '<span class="success">Address is valid.</span>';
} else {
icpsignup.preventDefault();
return '<span class="error">Address is invalid.</span>';
}
}}
})
})
</script>
UPDATE: A MORE complete answer:
NOTE: this assumes you will be using jQuery 1.4.3 or higher
The SUBMIT event is sent to an element when the user is attempting to submit a FORM:
It can only be attached to <form> elements.
Forms can be submitted either by clicking an explicit:
<input type="submit">,
<input type="image">, or
<button type="submit">,
or
by pressing Enter when certain form elements have focus.
NOTE: *Depending on the browser, Enter may only cause a form submission if:
the form has exactly one text field, or
only when there is a submit button present.
Therefore, your code shouldn't rely on a particular behavior for this key unless the issue is forced by observing the keypress event for presses of the Enter key which is character code 13.
Here is information about how to use the .keypress() handler from jQuery.com
Here is a chart comparing all ASCII character/key codes, HTML escape codes, and they keys/character they represent.
You can get more detailed information at the jQuery.com site .submit() page HERE.
In your scenario (and most), I would use a <input type="submit"> button and capture the SUBMIT event.
In the submit handler callback function:
$( "form#icpsignup" ).submit(function( evt ){
//...
$('#fields_email').mailgun_validator({
api_key: 'pubkey-8s-e-ovj0nbi32xw5eeyibrmv-lkq2e2', // replace this with your Mailgun public API key
in_progress: validation_in_progress,
success: validation_success,
error: validation_error,
});
//...
}
You will need to validate your <form> (i.e. use whatever code, statement, etc. on one or more input fields). Then upon...
success - use a return true statement
failure - use an evt.preventDefault(); where evt is the argument passed to your submit handler.
.
Below is a detailed example:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>submit demo</title>
<style>
p {
margin: 0;
color: blue;
}
div,p {
margin-left: 10px;
}
span {
color: red;
}
</style>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Type 'correct' to validate.</p>
<form action="javascript:alert('success!');"
<div>
<input type="text">
<input type="submit">
</div>
</form>
<script>
// "function( evt )" is an anonymous function. It *is* your handler
$( "form" ).submit(function( evt ) { // evt is the *event* object.
// name it whatever you'd like.
if ( $( "input:first" ).val() === "correct" ) {
$( "span" ).text( "Validated..." ).show();
return true;
}
$( "span" ).text( "Not valid!" ).show().fadeOut( 1000 );
evt.preventDefault();
});
</script>
</body>
</html>
Following my code:
<script>
function getText(text){
alert(text);
}
</script>
<form action="getText(/*here function for get text*/)">
<input type="text" class="text"/>
<input type="submit"/>
<div></div>
</form>
How to get textarea value with pure javascript in the <form> where indicated?
The action attribute contains the URL that the form will be submitted to, not JavaScript.
If you want to process the form data with JavaScript, then bind a submit event handler to it. This will be fired in the context of the form, so you can access the form element via this.
You can access the form controls through the elements collection. They will have value properties containing their values.
<form action="/some/handler" id="myForm">
<textarea name="myTextArea" class="text"></textarea>
<input type="submit">
<div></div>
</form>
<script>
function getText(text){
alert(text);
}
function formSubmitHandler(evt) {
var textarea = this.elements.myTextArea;
getText(textarea.value);
}
document.getElementById('myForm').addEventListener('submit', formSubmitHandler);
</script>
You may wish to call evt.preventDefault() if you are going to handle the form processing entirely with JS (when JS is available).
If you want value from input without using selector, then you can use some thing like this,
but remember, the value your are getting from input tag should be used as a first child of form element.
<form action="">
<input type="text" class="text"/>
<input type="button" onclick="getText()" value="get value">
<div></div>
</form>
<script>
function getText(text){
var textValue = document.getElementsByTagName('input')[0].value;
alert(textValue);
}
</script>
EDIT
If you want the text from input value after pressed the enter key then you could do like this.
<form action="">
<input type="text" class="text" onkeydown="getText(event)"/>
<div></div>
</form>
<script>
function getText(event){
var textValue = document.getElementsByTagName('input')[0].value;
if(event.which == 13){
alert(textValue);
}
}
</script>
Here a little function for you
function getTextAreaByClass(lookFor) {
var i; /* I always define at the top so jslint doesn't carp */
var elems = document.getElementsByTagName("textarea");
for (i in elems) {
if((' '+elems[i].className+' ').indexOf(' '+lookFor+' ') > -1) {
return elems[i].innerHTML;
}
}
return ""; /* or return false or whatever else you want to denote not found */
}
The above will search through all the textarea tags, look for a class that matches and will return the content within the textarea.
Below is a code of a simple html form and javascript code for checking if the fields are empty or not, when user clicks the submit button.
The problem is, that the form is submitted, even if the necessary fields are not filled in.
As you can see, I am just a beginner with JS coding, so I don't know, if the problem is in if/else statements, somewhere else in the JS code or if the form is not set up properly.
<script>
function preveri(pov){
var preveriime = pov.ime.value;
var preverirojstvo = pov.rojstvo.value;
var preverimail = pov.email.value;
var preverikategorijo = pov.kategorija.value;
if (preveriime == "") {
document.getElementById('imeA').style.display="block";
}
if (preverirojstvo == "") {
document.getElementById('datumA').style.display="block";
}
if (preverimail == "") {
document.getElementById('emailA').style.display="block";
}
if (preverikategorijo == "") {
document.getElementById('kategorijaA').style.display="block";
}
if(preveriime != "" && preverirojstvo != "" && preverimail != "" && preverikategorijo != ""){
document.pov.submit();
}
else{
return false;
}
}
</script>
<h4>OBRAZEC ZA SPLETNE PRIJAVE</h4>
<br/>
<form name="pov" method="POST" action="thankUPage.php">
<input name="ime" type="text" placeholder="Ime in Priimek"></input>
<input name="rojstvo" type="text" placeholder="Datum rojstva"></input>
<input name="email" type="text" placeholder="E-pošta"></input>
<input name="kategorija" type="text" placeholder="Kategorija"></input>
<textarea name="povprasaj" placeholder="Povprašaj"></textarea>
<input type="submit" name="submit" id="submit" value="Pošlji!" onclick="preveri(pov)" />
</form>
<div id="imeA" class="imeA">Obvezno polje!</div>
<div id="datumA" class="datumA">Obvezno polje!</div>
<div id="emailA" class="emailA">Obvezno polje!</div>
<div id="kategorijaA" class="kategorijaA">Obvezno polje!</div>
</div>
Tnx in advance!
You're returning false on the click event. You need to bind your callback function to the form's submit event, so returning false will cancel the form's submission.
Pressing "enter" while in a form field will submit the form and might not trigger the click event on the submit button.
<form name="pov" method="POST" action="thankUPage.php" onsubmit="return preveri(this);" >
As you know I want to remove default value of a text box while clicking on it, This code works.
But when I click on the box and then click again another part of screen (I mean out of textbox) the data won't come back.
what should I do?
<html><head><title>(Type a title for your page here)</title>
<script type="text/javascript">
function make_blank()
{
document.form1.type.value ="";
}
</script>
</head>
<body >
<form name=form1 method=post action='test.php'>
<input type=text name=type value='Enter your user id' onclick="make_blank();">Enter User ID
<b>Type</b>
<input type=submit value=Submit> </form>
</body>
</html>
The solution to your problem is one of the following, depending on whether you're using HTML5 or XHTML (or HTML4). Since you're not stating which one you're using, I'll add both.
By the way, you really want to use the focus event, and not the click event. This is because a user can also navigate to a form field using his/her keyboard or by other access keys.
As Quentin correctly states, the specification is clear about what a placeholder text is supposed to be used for. Therefore I've updated the text you're using to something more fitting.
HTML5
<input type="text" name="type" placeholder="email#example.com">
XHTML
HTML:
<input type="text" name="type" value="email#example.com"
onfocus="make_blank(this);" onblur="restore_placeholder(this);" />
Javascript:
function make_blank (oInput)
{
if (!('placeholder' in oInput))
oInput.placeholder = oInput.value;
if (oInput.value != oInput.placeholder)
oInput.value = '';
}
function restore_placeholder (oInput)
{
if (oInput.value == '' && 'placeholder' in oInput)
oInput.value = oInput.placeHolder;
}
The following combination of HTML5 and JavaScript (for HTML4) works nice for me:
HTML:
<input type="text" name="type" placeholder="email#example.com"
onfocus="make_blank(this);"
onblur="restore_placeholder(this);" />
Javascript:
function make_blank(oInput) {
if (oInput.value == 'placeholder') {
oInput.value = '';
}
}
function restore_placeholder(oInput) {
if (oInput.value == '') {
oInput.value = 'placeholder';
}
}