How to check if the required attribute is set on a field - javascript

I have a simple form that has some required fields in it.
<form name="form" method="post">
<pre>
<label> Name: </label><input type="text" name="name" required>
<label> Address: </label><input type="text" name="add" required>
<label>Telephone: </label><input type="text" name="tel">
<input type="submit" value="Submit Form">
</pre>
</form>
I know you can set the required attribute using document.forms['form']['name'].required = false. But is there a way where you can just check if the required attribute is set or not? I tried using getattribute() but it just returns blank. I also tried using the code below, but it always executes the statement, even if the required attribute isn't set (e.g. on the telephone field).
if( document.forms['form']['name'].required = true)
label.innerHTML += " (required)"
Does anyone know of a way I can do this?
Update: Both setting the if statement to == instead of = and using hasAttribute work, thanks.

Try this :
var elem = document.getElementsByTagName('input')[0];
if(elem.hasAttribute('required')){
//do your stuff
}

Related

Display value in input in html

I have the following code for html:
<label for="">Input</label>
<input type="text" name="" id="input_01" placeholder="Enter some text">
<label for="">Output</label>
<input type="text" name="" id="ouput_01">
<script>
var input_01 = document.getElementById("input_01")
var output_01 = document.getElementById("output_01")
input_01.addEventListener('keyup',function(){
output_01.value = input_01.value
})
</script>
I want to display the input value as the output. However, I found that the command "output_01.value = input_01.value" doesn't work and there is nothing displayed. I do not know why and do not know how to solve this problem. How can I display the content of an input in 'ouput_01'? Thank you.
make sure you don't have typo in your code.
change from
<input type="text" name="" id="ouput_01">
to
<input type="text" name="" id="output_01">
your INPUT tag output ID does not match the one on your javascript DOM and this output_01.value = input_01.value is wrong, instead you should add event to your function parameter in your Event Listener then assign your event.target.value to your output DOM value
<label for="">Input</label>
<input type="text" name="" id="input_01" placeholder="Enter some text">
<label for="">Output</label>
<input type="text" name="" id="output_01">
<script>
var input_01 = document.getElementById("input_01")
var output_01 = document.getElementById("output_01")
input_01.addEventListener('keyup', function(event) {
output_01.value = event.target.value
})
</script>

Can I submit form on timeout even if required fields are not filled

I was wondering if it is possible to submit a form after a certain period of time (e.g. 2 minutes) even if not all the required fields are filled out, as I would like all the data entered by that fixed period of time to be submitted. Currently, although I'm using a timeout function that is javascript-based, it does not allow for the form to be submitted upon timeout as the required fields are not completed. I set all the fields to required as the autofocus function does not seem to work if it is not a required field (i.e. does not go into the next input field automatically upon pressing enter in the current field. Is there a way around this? Thanks so much for any help!
window.setTimeout(() => this.submit(), 120000)
<html>
<main>
<form>
<br><label for="response1"><b>Animals</b></label><br>
<input type="text" id="response1" name="response1" autocomplete="off" autofocus required></br>
<br><input type="text" id="response2" name="response2" autocomplete="off" autofocus required></br>
<br><input type="text" id="response3" name="response3" autocomplete="off" autofocus required></br>
<br><input type="text" id="response4" name="response4" autocomplete="off" autofocus required></br>
<button type="submit">Submit</button>
</form>
</main>
</html>
Sure, just put this logic in your function. You just remove required attribute from fields.
let form = document.querySelector('form');
let inputs = form.getElementsByTagName('input');
let i;
for (i = 0; i < inputs.length; i++) {
inputs[i].required = false;
}
there are a couple problems with your code:
you should not open and close br tags, you just put a <br> where you want the line break
the autofocus attribute should only be placed on one input, and that input will have the focus when the page loads.
depending on how you are calling your code, you might run in to problems with the this keyword, you might be better calling the form directly.
I changed those things in your code and succeeded with the following code (no need to remove the required attributes, but if they are not really needed just remove them):
window.setTimeout(() => document.forms[0].submit(), 1000)
<html>
<main>
<form>
<br>
<label for="response1">
<b>Animals</b>
</label>
<br>
<input type="text" id="response1" name="response1" autocomplete="off" autofocus required>
<br>
<input type="text" id="response2" name="response2" autocomplete="off" required>
<br>
<input type="text" id="response3" name="response3" autocomplete="off" required>
<br>
<input type="text" id="response4" name="response4" autocomplete="off" required>
<button type="submit">Submit</button>
</form>
</main>
</html>
I changed the timeout to one second just to be able to see the effect.

How can i change AlertBox into a div?

I would like to know how can I change the AlertBox into a div.
I want the alertBox message to appear next to the input but in a div.
Thank You.
This is my Form input code:
<form name="form" action="gigi.php" method="POST" onsubmit="return validateForm()">
<input type="hidden" name="action" value="submit">
First Name:<br>
<input name="name" type="text" size="30"/><br>
Last Name:<br />
<input name="lname" type="text" size="30"/><br>
Email:<br>
<input name="caca" type="text" size="30"/><br>
Your message:<br>
<textarea name="message" rows="7" cols="30"></textarea><br>
<input class="submit" type="submit" value="Send email"/>
</form>
And this is First Name input code in JavaScript:
function validateForm(){
var x=document.forms["form"]["name"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
In your HTML add something like:
<div id="form-errors"></div>
Then in JS, you can do that:
var alertDiv = document.getElementById('form-errors');
if (!x || x == '') {
alertDiv.textContent = 'First name must be filled out!';
}
Readings:
textContent
Similar question
Your question is about forms ? Since HTML5 you can simply write required on the input tab and it won't validate until you write some data.. you can then sanitize it.
In addition to Ramy's response, you can add jquery hide/show effects to display and hide the div element.
Also, do not forget to add style "z-index" to the div, so that it will appear on above other content of web-page.

Javascript form validation not working - Script not being called?

I have a pretty straight-forward javascript form validation script written:
function validateForm(){
var x=document.forms["contactForm"]["firstname"].value;
if (x==null || x==""){
return false;
}
var y=document.forms["contactForm"]["lastname"].value;
if (y==null || y==""){
return false;
}
var z=document.forms["contactForm"]["emailaddress"].value;
var atpos=z.indexOf("#");
var dotpos=z.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=z.length){
return false;
}
var msg_area = document.getElementById("message");
msg_area.innerHTML = "";
if (document.getElementById("message").value.length < 20) {
return false;
}
else document.getElementById("contactForm").submit();
}
It's supposed to be validating this form:
<form name="contactForm" onsubmit="return validateForm()" action="./thankyou.html" method="post">
<label for="firstName">First Name <sup>*</sup></label>
<input name ="firstname" id="firstName" type="text" placeholder="First Name" required />
<label for="lastName">Last Name <sup>*</sup></label>
<input name ="lastname" id="lastName" type="text" name="lastName" placeholder="Last Name" required />
<label for="emailaddress">Email address <sup>*</sup></label>
<input name="emailaddress" id="emailAddress" type="email" placeholder="something#example.com" required />
<label for="message">Message<sup>*</sup></label>
<textarea id="message" placeholder="Remember, be nice!" required></textarea>
<input type="submit" name="submit" value="Email Me!" class="emailsub" />
<p class="small"><sup>*</sup> denotes a required field.</p>
</form>
When it's submitted, it doesn't seem to actually call the javascript at all. The only thing that it looks for is that it meets the "required" part of the html. I'm pretty new to javascript so it's probably glaringly obvious where the problem is, but I just can't locate it myself.
Any help is much appreciated!
p.s. this is for a local website at the moment so the action="" goes to another html instead of a page to process the message. Is this possibly the problem here?
The html5 "required" attribute tells the browser to validate before proceeding, read more here. This means that it's stopping the event before the javascript function is even called (on supported browsers) unless it passes the basic validation (required fields and email).
If you want the javascript to execute and perform your own validation, you'll need to remove the "required" attribute. You may also try more complex html form validation. Here is a good article on the subject.

How to fix form action issue in XHTML 1.0 Strict

I've got an issue with validating my code to XHTML 1.0 Strict.
I've been using the w.3 validator to try and validate my page.
It tells me
Line 112, Column 24: required attribute "action" not specified
<form id="orderform">
The attribute given above is required for an element that you've used,
but you have omitted it. For instance, in most HTML and XHTML document
types the "type" attribute is required on the "script" element and the
"alt" attribute is required for the "img" element.
Typical values for type are type="text/css" for and
type="text/javascript" for script.
I'm relatively new to XHMTL and CSS and I'm also learning Javascript at this time, I've done a Google search and I've found a lot of people talking about using a Javascript line to fix the error, but none of them are clear enough. Is there anyone here who can provide a clear explanation for me?
This is my XHTML code..
<form id="orderform">
<div class="field">
Name:
<input type="text" id="name" name="name" value="" />
</div>
<div class="field">
# of Home shirts:
<input type="text" id="homeshirt" name="home" value="" onchange="updateOrder();" />
</div>
<div class="field">
# of Away shirts:
<input type="text" id="awayshirt" name="away" value="" onchange="updateOrder();" />
</div>
<div class="field">
Date of collection:
<input type="text" id="date" name="date" value="" />
</div>
<div class="field">
Subtotal:
<input type="text" id="subtotal" name="subtotal" value="" readonly="readonly" />
</div>
<div class="field">
Tax:
<input type="text" id="tax" name="tax" value="" readonly="readonly" />
</div>
<div class="field">
Total:
<input type="text" id="total" name="total" value="" readonly="readonly" />
</div>
<div id="button">
<input type="button" class="button" value="Place Order" onclick="placeOrder(this.form);" />
</div>
</form>
and my Javascript...
<script type="text/javascript">
function updateOrder() {
const TAXRATE = 0.0925;
const SHIRTPRICE = 39.99;
var numHomeShirt = parseInt(document.getElementById("homeshirt").value);
var numAwayShirt = parseInt(document.getElementById("awayshirt").value);
if (isNaN(numHomeShirt))
numHomeShirt = 0;
if (isNaN(numAwayShirt))
numAwayShirt = 0;
var subTotal = (numHomeShirt + numAwayShirt) * SHIRTPRICE;
var tax = subTotal * TAXRATE;
var total = subTotal + tax;
document.getElementById("subtotal").value = "£" + subTotal.toFixed(2);
document.getElementById("tax").value = "£" + tax.toFixed(2);
document.getElementById("total").value = "£" + total.toFixed(2);
}
function placeOrder(form) {
if (document.getElementById("name").value == "")
alert("I'm sorry but you need to provide a name to print on the shirt.");
else if (document.getElementById("date").value == "")
alert ("I'm sorry but you must provide a date you can collect your shirt(s).");
}
</script>
Thank you for your time,
Cheers.
Jamie
Maybe this is too obvious and I'm missing something, but why not just add the action attribute to the form?
No need for javascript. If you're using php just add the following code:
<form id="your_id" action="<?=$_SERVER['PHP_SELF']?>">
Basically, this code will set the action to the same page.
Or others suggest, just add an empty action :)
To fix that particular validation error you need to include the action attribute in the form element.
<form id="orderform" action="">
It looks like you're using JavaScript to handle form submission, so you should just be able to leave the action empty, otherwise give it a value that pertains to the form submission php script.
XHTML require that your form include an action that will be called (that is, another script on the server) when the submit button is pressed.
Currently you're only implementing the behaviour in Javascript - if this is disabled then nothing will happen. Ideally you should point to a script, usually the same PHP script as the one generating the form, to handle the submit button press:
<form id="your_id" action="<?=$_SERVER['PHP_SELF']?>">
Then your script should handle the submission in the case that the Javascript didn't.

Categories

Resources