How to append some text to text box - javascript

This JavaScript checks whether the name-text box is empty or not.
If empty then the same line should have "Name is required" appended.
function checkFields(){
var name = document.forms["contact-form"]["name"].value;
if(name == ""){
}
<!--- This is the html code for text box for name and submit button to call checkFields() method -->
<div class="required-fields">
<label>My Name:</label>
<input type="text" name="name"/>
</div>
<input type="button" onclick="checkFields()" value="Send Message"/>

Well I think you just need placeholder html attribute, google it.
And, the method you chose is more likely not necessary in the first place, still check this updated fiddle out,
function checkFields(){
var name = document.forms["contact-form"]["name"].value;
console.log(name);
if(name == ""){
document.getElementsByClassName('error-text')[0].innerHTML='Name field required'
}
else{
document.getElementsByClassName('error-text')[0].innerHTML='';
}
}

Try with placeHolder : or use with input required method . if you need with append some error see the below snippet:
Snippet:
function checkFields(){
var name = document.forms["contact-form"]["name"].value;
if(name =="" ){
document.getElementById("input").placeholder = "**Name required**";
document.getElementById("error").innerHTML ="**Name required**";
}
}
<!--- This is the html code for text box for name and submit button to call checkFields() method -->
<form name="contact-form">
<div class="required-fields">
<label>My Name:</label>
<input type="text" name="name" id="input" >
<p id="error" style="color:red"></p>
</div>
<input type="button" onclick="checkFields()" value="Send Message"/>
</form>

Related

Second input box in form doesn't work second time

I have this form:
<form id="addChore" method="post" action="allocate.php">
<label>Name of new chore:</label>
<input type="text" id = "choreName" name="choreName">
<p></p>
<label>Description:</label>
<input type="text" id="description" name="description">
<p></p>
<label>Frequency:</label>
<select id="frequency" name="frequency">
...
</select>
<input type="submit" value="Submit">
</form>
and this jQuery
$(document).ready(function(){
$("#addChore").on('submit',function(e){
e.preventDefault();
$("#error").empty();
var name = $("#choreName").val();
console.log(name);
var description = $("#description").val();
console.log(description);
var frequency = $("#frequency").val();
console.log(frequency);
var message=("Please fill all fields");
// $('#addChore')[0].reset();
if (!name || !description){
$("#error").append("<p>"+message+"</p>");
return false;
}
else{...}
but when I try and use the form a second time, description is empty in the log, while name and frequency accept a new input. I have tried resets and .val("") but nothing seems to change this. Any help? :/
Turns out I had another element with the same id, but defined in php in a separate script

Validate user inputs before submit form

I have this code to validate inputs:
<script>
function validate()
{
var firstName = document.form.fullname.value;
var lastName = document.form.fullname.value;
var email = document.form.email.value;
var password = document.form.password.value;
var conpassword = document.form.conpassword.value;
if (firstName == null || firstName == "")
{
alert("Firstname can't be blank");
return false;
} else if (lastName == null || lastName == "")
{
alert("Lastname can't be blank");
return false;
} else if (email == null || email == "")
{
alert("Email can't be blank");
return false;
} else if (password.length < 6)
{
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
And this is my form:
<form name="form" action="<%=request.getContextPath()%>/register" method="post">
<div class="container">
<div class="left">
<div class="header">
<h2 class="animation a1">Register now</h2>
<h4 class="animation a2">Enter information in field and create account!</h4>
</div>
<div class="form">
<input type="text" name="firstName" class="form-field animation a3" placeholder="Name...">
<input type="text" name="lastName" class="form-field animation a3" placeholder="Last name...">
<input type="email" name="email" class="form-field animation a3" placeholder="Email adress...">
<input type="password" name="password" class="form-field animation a4" placeholder="Password">
<button class="animation a6" value="Submit" type="submit">REGISTER</button>
</div>
</div>
<div class="right"></div>
</div>
</form>
How to implement that function to my form? Because now when I click submit, in my database an empty user is added. I want to add that it throws out an error in each field if it is not validly filled in
You can get the validate function to execute by adding an 'onsubmit' to your form html tag ( see here w3 Schools for executing a function on submit: onsubmit in forms)
As for the errors, when executing the code, the function cannot read a property 'value' of undefined. So what is happening is that you are telling the validate function to get parts out of the form out that it cannot find (fullname and conpassword are not defined).
Take a look at your form's name tags for fields and then reference those names in the validate function. So when declaring firstName instead of document.form.fullname.value try document.form.firstName.value referring in the form. Do this for first and last name using their names in the form, and also get rid of (or comment out) the conpassword variable.
This validation could be done without javascript function. Use the "required" tag for the inputs which are mandatory.
For example :
<input type="text" name="firstName" class="form-field animation a3" placeholder="Name..." required>
In case of password you may use the pattern attribute.
If you need to use javascript in particular, then go for onclick in the button tag.
<button class="animation a6" onclick="validate()">REGISTER</button>
and include the form submit in the javascript function -
document.form.submit();

Changing innerHTML based on input value

This is the HTML code:
<body>
<form>
<input id="input" type="text" name="input" value="Enter Here">
<input type="submit" value="Submit">
</form>
<div id="display">
</div>
</body>
This is the JavaScript:
input = document.getElementById("input");
if (input.value == "Hello") {
display.innerHTML = "Hello";
} else {
display.innerHTML = "Type";
}
When I change the input value by clicking on the input field and typing "Hello", it does not display "Hello" in display.innerHTML. I would like it to display "Hello" when "Hello" is typed into the input field. That's a lot of "Hello"'s! Any help would be great! Thanks in advance.
var input = document.getElementById("input"),
display=document.getElementById("display");
input.oninput=function(){
if (input.value === "Hello") {
display.innerHTML = "Hello";
} else {
display.innerHTML = "Type";
}
};
<input id="input" type="text" name="input" value="Enter Here">
<div id="display">
</div>
Your javascript code only gets executed once before you have entered anything in the input field.
You need to either setup a change handler for the input field or a submit handler for the form and set display.innerHTML.
Also, did you miss a display = document.getElementById("display");?
If you want use your button for submit the value of your textbox (your input type text-field) use onclick event as follows:
function displayData() {
var div_display = document.getElementById('display');
/* This is your input, but you shoud use another Id for your fields. */
var textValue = document.getElementById('input').value;
/* Change the inner HTML of your div. */
div_display.innerHTML = textValue;
}
<input id="input" type="text" name="input" value="Enter Here" />
<input type="submit" value="Submit" onclick="displayData();" />
<div id="display">
</div>
Hope it helps.

HOw can i retrieve name value of input type at run time

In my form I have written something like:
Enter your Name : <input type="text" name="myname" />
<div id="mynameerror"> </div>
<br />
In the validation: i retrieve the element with id 'mynameerror', and if the input is empty, and i set some error string into innterHTML.
Question:
Now, is it possible to construct id name of div tag by retrieving 'name' property of the 'input' tag ?
something like:
<div id="name property" + "error"> </div>
ids cannot have spaces. Use an underscore or other separator.
Also, it is bad practice to be altering the id of an element at runtime.
window.setTimeout(function() {
// Get the input's name
var name = document.querySelectorAll('input[type="text"]')[0].name;
// Set the id for the div to be "myname_error"
document.getElementById("mynameerror").setAttribute("id", name + "_error");
// Verify the element's id was altered by retrieving it.
console.log(document.getElementById("myname_error"));
}, 1000);
Enter your Name :
<input type="text" name="myname" />
<div id="mynameerror"></div>
Try this:
HTML:
<input type="text" name="fname" id="fname">
<span id="fname_error"></span>
<br><br>
<input type="button" onclick="check()" value="Check">
Script:
<script>
function check(){
var fname = document.getElementById("fname").value;
if(!fname){
document.getElementById("fname_error").innerHTML = "Text Empty!";
} else {
document.getElementById("fname_error").innerHTML = "No Error!";
}
}
</script>

Validating an HTML form with onClick added form fields

I have a form I cobbled together with bits of code copied online so my HTML and Javascript knowledge is VERY basic. The form has a button that will add another set of the same form fields when clicked. I added some code to make it so that if the "Quantity and Description" field is not filled out, the form won't submit but now it just keeps popping up the alert for when the field's not filled out even if it is. Here's is my script:
<script type='text/javascript' src='http://code.jquery.com/jquery-1.5.2.js'>
</script><script type='text/javascript'>
//<![CDATA[
$(function(){
$('#add').click(function() {
var p = $(this).closest('p');
$(p).before('<p> Quantity & Description:<br><textarea name="Quantity and Description" rows="10"
cols="60"><\/textarea><br>Fabric Source: <input type="text" name="Fabric Source"><br>Style# & Name: <input
type="text" name="Style# & Name"><br>Fabric Width: <input type="text" name="Fabric Width"><br>Repeat Information:
<input type="text" name="Repeat Info" size="60"><input type="hidden" name="COM Required" /> </p><br>');
return false;
});
});
function checkform()
{
var x=document.forms["comform"]["Quantity and Description"].value
if (x==null || x=="")
{
alert("Quantity & Description must be filled out, DO NOT just put an SO#!!");
return false;
}
}
//]]>
</script>
And here's my HTML:
<form action="MAILTO:ayeh#janusetcie.com" method="post" enctype="text/plain" id="comform" onSubmit="return
checkform()">
<div>Please complete this worksheet in full to avoid any delays.<br />
<br />Date: <input type="text" name="Date" /> Sales Rep: <input type="text" name="Sales Rep" /> Sales Quote/Order#: <input type="text" name="SQ/SO#" /><br />
<br />Quantity & Description: <font color="red"><i>Use "(#) Cushion Name" format.</i></font><br />
<textarea name="Quantity and Description" rows="10" cols="60">
</textarea>
<br />Fabric Source: <input type="text" name="Fabric Source" /><br />Style# & Name: <input type="text" name="Style# & Name" /><br />Fabric Width: <input type="text" name="Fabric Width" /><br />Repeat Information: <input type="text" name="Repeat Info" size="60" /><br /><font color="red"><i>Example: 13.75" Horizontal Repeat</i></font><br />
<br /><input type="hidden" name="COM Required" />
<p><button type="button" id="add">Add COM</button></p>
</div>
<input type="submit" value="Send" /></form>
How can I get it to submit but still check every occurence of the "Quantity and Description" field?
First, I would not use spaces in your input names, as then you have to deal with weird escaping issues. Use something like "QuantityAndDescription" instead.
Also, it looks like you're trying to have multiple fields with the same name. The best way to do that is to add brackets to the name, meaning the values will be grouped together as an array:
<textarea name="QuantityAndDescription[]"></textarea>
This also means the code has to get all the textareas, not just the first. We can use jQuery to grab the elements we want, to loop over them, and to check the values. Try this:
function checkform()
{
var success = true;
// Find the textareas inside id of "comform", store in jQuery object
var $textareas = $("form#comform textarea[name='QuantityAndDescription[]']");
// Loop through textareas and look for empty values
$textareas.each(function(n, element)
{
// Make a new jQuery object for the textarea we're looking at
var $textarea = $(element);
// Check value (an empty string will evaluate to false)
if( ! $textarea.val() )
{
success = false;
return false; // break out of the loop, one empty field is all we need
}
});
if(!success)
{
alert("Quantity & Description must be filled out, DO NOT just put an SO#!!");
return false;
}
// Explicitly return true, to make sure the form still submits
return true;
}
Also, a sidenote of pure aesthetics: You no longer need to use the CDATA comment hack. That's a holdover from the old XHTML days to prevent strict XML parsers from breaking. Unless you're using an XHTML Strict Doctype (and you shouldn't), you definitely don't need it.

Categories

Resources