How to fix form action issue in XHTML 1.0 Strict - javascript

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.

Related

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.

Will not return false, or display the alert for function combine() when true. Does someone see a mistake I don't?

// I apologize for giving the whole code, with omission of the urls, but my code will be returning false just fine, then the next time I try to add a new function, it will no longer return false, and upon removing the new function, it does not return to working again as it did before. I have tried onsubmit=return and onclick=return both.
The other issue is for function combine() in my code. It doesn't ever seem to work, and I have tried numerous different methods. I have tried just alerting with "Test", and the alert doesn't even work.
UPDATED: Now we have it returning false properly for invoices not matching, with alert. It also gives alert for Emails not matching, however it does not return false for emails not matching, and continues to the url. I am showing no errors in the console now. It also does correctly combine and alert to show the invoice and name together.
UPDATE: Now have it working completely. See my final comment below to see how I fixed this last issue. Hope this helps someone!
<!DOCTYPE html>
<!-- // working code except for combining the invoice with the name -->
<head>
<title>INFORMATION FORM</title>
</head>
<!-- // This code compares two fields in a form and submit it -->
<!-- // if they're the same, or not if they're different. -->
<body>
<script type="text/javascript">
function checkInvoice(theform) {
if (theform.invoice1.value != theform.invoice2.value)
{
alert("The INVOICE numbers do not match, please review for mistakes to assure your account gets credited.");
return false;
} else {checkEmail(theform);
}
}
function checkEmail(theform) {
if (theform.EMAIL_1.value != theform.Email.value)
{
alert("The EMAIL addresses you provided do not match. Please correct the EMAIL address and try again.");
return false;
} else {
<!-- // This code combines two fields into the CustRefID-->
function combine()
{
var y=document.getElementById("invoice2").value;
var x=document.getElementById("FName").value;
var InvoiceName = y+""+x;
document.getElementById("CustRefID").value = InvoiceName;
alert(document.getElementById("CustRefID").value);
}
combine(); <!--// this calls the combine function when the email addresses match-->
return true;
}
}
</script>
<form name=theform action= "https://hos###/Index" method ="POST" target="_blank" onsubmit="return checkInvoice(this);" >
<input type="hidden" name="HostedKey" id="HostedKey" value="####" />
<input type="hidden" name="Gateway_ID" id="Gateway_ID" value="#####" />
<input type="hidden" name="IndustryCode" id="IndustryCode" value="2" />
<!-- the next line blank value tells the hosted page to allow the customer to use credit cards as the only allowed payment type. -->
<!-- If you want to only allow more than credit cards, replace “CC” with “” for the value -->
<input type="hidden" name="PaymentType" id="PaymentType" value="CC" />
<!-- the next line allows the hosted page to capture some perhaps useful info to identify the payment. -->
<strong><span style="color: #ff0000;">INVOICE</span></strong> Number: <input type="text" name="invoice1" required id="invoice1" value="" size="40" maxlength="40" />
<br>
Please Confirm your <strong><span style="color: #ff0000;">INVOICE</span></strong> number: <input type="text" name="invoice2" required id="invoice2" value="" size="40" maxlength="40" />
<p>
Patient Full Name (as it appears on your paper bill): <input type="text" name="FName" id="FName" required value="" size="40" maxlength="40" />
<p>
PHONE (###-###-####): <input type="text" pattern="^\d{3}-\d{3}-\d{4}$" name="PhoneNumber" required id="PhoneNumber" value="" />
<p>
<input type="hidden" name="Amount" id="Amount" value="" />
<!-- the next line’s N value tells the hosted page to not display recurring payment fields -->
<input type="hidden" name="RecurringType" id="RecurringType" value="N" />
<input type="hidden" name="RecurringAmount" id="RecurringAmount" value="" />
<!-- the next line defines where users are directed after a successful purchase. It is suggested you create a simple Thankyou page for the site. -->
<input type="hidden" name="RURL" id="RURL" value="http://www.######.com/thankyou/" />
<!-- the next line defines where users are directed after they hit the Cancel button on the TXP Hosted page -->
<input type="hidden" name="CURL" id="CURL" value="http://www.########.com/cancelled/" />
<!-- If AVSRequired equals "Y", Address Line 1 and ZIP Code become required fields on the hosted page -->
<input type="hidden" name="AVSRequired" id="AVSRequired" value="Y"/>
<!-- If CVV2Required is set to "Y", than CVV2 becomes a required field on the hosted page -->
<input type="hidden" name="CVV2Required" id="CVV2Required" value="Y"/>
<!-- If EmailRequired is set to "Y", then Email becomes a required field on the hosted page -->
<input type="hidden" name="EmailRequired" id="EmailRequired" value="Y"/>
<!-- the next line defines enables/disables the ability to receive response data in an POST format. When set to N, no response data is returned to the RURL -->
<input type="hidden" name="PostRspMsg" id="PostRspMsg" value="N"/>
<!-- You can also use a graphic for the button to improve the appearance -->
<p> Enter Your Email Address:<br>
<input type="TEXT" name="EMAIL_1" value="" id=EMAIL_1 required size="40" maxlength="40">
<br>
Please Confirm Your Email Address:
<br>
<input type="TEXT" name="Email" required value= "" size="40" maxlength="40" />
<br>
<input type="hidden" name="CustRefID" id="CustRefID" value="" />
<!-- the next line defines what text is on the button. Replace Submit Payment Now with whatever you desire -->
<p>
<input type="SUBMIT" name="Button" id="Button" value="Make Payment Now" ></p>
</form>
</body>
</html>

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

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
}

Can I recalculate a form field without a reload?

When a field in my form gets focus, I'd like a javascript function to be called that
calculates a value for that field without my putting in a specific button to do that.
Is this possible without causing the form to reload?
I have thought about making the Amount field read-only, and some other ways of doing this, but I'm looking to see if changing the Quantity field could cause the Amount field to change either using onchange in the Quantity field or onfocus in the Amount field.
Purchase Tickets<br>
<script type="text/javascript" language="JavaScript1.2">
<script type="text/javascript" language="JavaScript1.2">
document.write(
'<form name="InvGenPayTickets" action="'+PostURL+'"
onsubmit="return validateForm();" method=GET>');
</script>
<input type=hidden name="TplURL" value="GenPayCCInfo.html">
<input type=hidden name="CancelURL" value="Ooopsie.html">
<input type=hidden name="SuccessURL" value="Joanie.html">
<input type='hidden' name='TransDesc' id='TransDesc'
value="$_POST['TransDesc']; ?>" />
<input type='text' name='Quantity' id='Quantity' /> <br />
Amount<br />
$<input type='text' name='Amount' id='Amount' />
<input type="submit" value="Next">
<br>
</form>
Edit:
Here is the function that won't update. It is called if I use
<input type='text' name='Quantity'
id='Quantity' onchange="return retTotalAmt();" />
but the Amount field does not update. I am not able to update using a calc button either.
<script type="text/javascript" language="JavaScript1.2">
function retTotalAmt()
{
alert("Got here.");
var total_amt
= (document.getElementById('Quantity').value * ticketCost)
+ DonationAmount;
document.getElementById('Amount').value = total_amt;
}
</script>
Per request in comments:
<input type='text' name='Quantity'
id='Quantity' onchange="return retTotalAmt();" />
Edit -- Show Problem
<script type="text/javascript" language="JavaScript1.2">
var ticketCost = 40.00;
function EnterPage()
{
var currentTotalAmount = DonationAmount + ticketCost;
//DonationAmount moved up to ticketCost's scope fixed problem.
var DonationAmount = <?php echo($_POST['DonationAmount']); ?>;
document.getElementById('DonationAmountField').value = DonationAmount.toFixed(2);
document.getElementById('Quantity').value=1;
document.getElementById('Amount').value = currentTotalAmount.toFixed(2);
return;
}
Without using jquery:
<input type='text' name='Amount' id='Amount' onfocus="amountOnFocus();" />
Javascript:
function amountOnFocus() {
amountField = document.getElementById('Amount');
//Do calculations
amountField.value = resultOfCalculations;
}
If you wanted, you could also put a change event listener on the Quantity input so it will calculate when the value of that textbox changes.
EDIT: This onchange event works for me:
Markup:
<input type="text" id="txtChangeMe" onchange="txtChangeMeOnChange();" />
Javascript:
<script type="text/javascript">
function txtChangeMeOnChange() {
alert('changed');
}
</script>
I'm not quite sure what additional information you need, as you seem to be aware of all the ingredients for making this happen: You know that you want to detect an event, you know that you need to call a function, so I'm hoping I haven't missed something about what you're asking. I'm going to assume that you just need to know how to tie all these parts together.
The simplest example might be:
<input type="text" id="Quantity" value="10" onchange="document.getElementById('Amount').value = parseInt(document.getElementById('Quantity').value,10) * 10.0;" />
$<input type="text" id="Amount" value="100" />
though it's worth noting that this does not follow best-practices, which would involve binding an event listener separately.
On the off-chance that you accidentally typed "button" when you meant "field", I will also mention that you can update any other element's innner HTML with the ''innerHTML'' attribute, eg:
<input type="text" id="Quantity" value="10" onchange="document.getElementById('Amount').innerHTML = parseInt(document.getElementById('Quantity').value,10) * 10.0;" />
$<span id="Amount">100</span>
Of course, you can define the actual logic elsewhere, and just use ''onchange="yourFunction();"'' instead of putting everything inline, as well.
I know you mentioned "onchange" and "onfocus", though personally I tend to prefer "onkeyup", so that values will change as the user is typing.
Apologies if I've completely missed the point in your question.
Sure. Use something like this which will fire when quantity change:
$("#Quantity").change(function(){
// perform your calculations here
};
This requires the jQuery framework.
function calcPrice()
{
....
}
<input type='text' name='Quantity' id='Quantity' onchange='calcPrice();'/>
<input type='text' name='Amount' id='Amount' onfocus='calcPrice();'/>
Do you have access to jQuery? If not then you would have to bind an change event to your "quantity" input element to listen for a change of its input. Then you would simply need to modify the contents of the "amount" input.
https://developer.mozilla.org/en-US/docs/DOM/element.addEventListener
var el = document.getElementById("Amount");
el.addEventListener("change", changeAmount);
function changeAmount(){
var quantity = document.getElementById("Quantity");
quantity.value = "SET YOUR VALUE";
}
Try this solution
Html
<div class="form-group row">
<label for="inputQty" class="col-sm-4 col-form-label">Quantity</label>
<div class="col-sm-8">
<input onkeyup="CalculateItem();" onkeydown="CalculateItem();" onchange="CalculateItem();" onfocus="CalculateItem();" value="1" type="number" step="1" min="1" max="9999999" class="form-control" id="inputQty" required>
</div>
</div>
<div class="form-group row">
<label for="inputPrice" class="col-sm-4 col-form-label">Price</label>
<div class="col-sm-8">
<input onkeyup="CalculateItem();" onkeydown="CalculateItem();" onchange="CalculateItem();" onfocus="CalculateItem();" type="number" step="0.1" min="1" max="9999999" class="form-control" id="inputPrice" required>
</div>
</div>
<div class="form-group row">
<label for="inputPriceNoVat" class="col-sm-4 col-form-label">Price (no VAT)</label>
<div class="col-sm-8">
<input readonly type="text" class="form-control" id="inputPriceNoVat">
</div>
</div>
JS
<script type="text/javascript">
function CalculateItem()
{
try {
let inputPriceNoVat = $('#inputPrice').val() * $('#inputQty').val();
$('#inputPriceNoVat').val(inputPriceNoVat);
} catch (e) {
$('#inputPriceNoVat').val(0);
}
}
</script>

jQuery serialize function with multple forms

I'm using the jQuery .serialize function and can't get it to serialize the proper form on submit.
my js code:
function getquerystring(form) {
return $("form").serialize();
}
my forms:
<div class="leave_message_box">
<form name="leave_message_form">
<input type="text" name="clock_code" placeholder="Clock Code" />
<input type="text" name="message" placeholder="Message (Blank for none)"/>
<input type="hidden" name="type" value="leave_message" />
<input value="Leave Message" type="button" onclick='JavaScript:xmlhttpPost("clockin.php", "leave_message_form")'></p>
</form>
</div>
<div class="outside_job_box">
<form name="outside_job_form">
<input type="text" name="clock_code" placeholder="Clock Code" />
<input type="text" name="message" placeholder="Message (Blank for none)"/>
<input type="hidden" name="type" value="ouside_job" />
<input value="Outside Job" type="button" onclick='JavaScript:xmlhttpPost("clockin.php", "outside_job_form")'></p>
</form>
</div>
I must be doing something wrong in passing the variable. the full code # pastie. The function I have does work, however, its always the last form that gets submitted.
Using this code:
$("form")
will find all the <form> elements in your document.
Given that form is a string containing the name of the form, what you want instead is this:
$("form[name='" + form + "']")
Looking at your supplied code, I have this suggestion. Instead of passing the form name to your function, why not just pass the form itself?
<button onclick="xmlhttpPost('blah', this.form)">
You also don't need to put javascript: in the onclick, onfocus, onwhatever properties.
I would suggest putting an ID attribute on the form and then using that ID as an explicit selector for jQuery:
<div class="outside_job_box">
<form id="outside_job_form" name="outside_job_form">
<input type="text" name="clock_code" placeholder="Clock Code" />
<input type="text" name="message" placeholder="Message (Blank for none)"/>
<input type="hidden" name="type" value="ouside_job" />
<input value="Outside Job" type="button" onclick='JavaScript:xmlhttpPost("clockin.php", "outside_job_form")'></p>
</form>
</div>
Then you would select and serialize it like this;
var f = $("#outside_job_form").serialize();
Not only making your code more effecient but more readable, in my opinion.
If the sole purpose is to encode simple text into URL format then use encodeURIComponent().

Categories

Resources