Im running a form in a webshop that looks like this:
<form>
<input type="number" name="quantity" value="" required = "required" />
<input type="radio" name="homeDelivery" value="" required = "required" checked="true" />
<input type="radio" name="homeDelivery" value="" required = "required" />
<input type="submit" value="buy" name="submitBuy" class="buy formConfirm" />
</form>
After the submit button is pressed I run a simple error check in php from the info I get from $_POST. I have an array called $errors, if my error check finds any errors it adds them to my array, else not, and if the array stays empty til the end, my form will submit the data, else not.
I do however want to have a JS confirmbox after pressing submit, that will only popup if there are no errors in the actual form. So to my actual question:
Is it possible to check in javascript code if my $errors variable is empty? Something that works like this:
if(empty($errors)) {
//run code
}
If it is possible Id like my javascript code to look something like this(I think you get the idea);
$('.buyConfirm').on('click', function(){
if (errors == NULL) {
return confirm('Are you sure?');
}
else {
return false;
}
});
Any help is appreciated,
Cheers!
You need to output your PHP var as a JS array, best using json_encode, and then consume that in your condition
<script>
var errors = <?php echo json_encode($errors); ?>;
if (errors.length < 1) {
if (confirm("Are you sure?")) {
// User has no errors and has confirmed
} else {
// User has no errors but did not confirm
}
} else {
// User has errors
}
</script>
Related
I would appreciate your help on this one. I tried to use code from other questions, but unfortunately it doesn't work.
I am trying to prevent a form from submitting and show an alert ("Select dates so continue")if two specific fields are empty. In this case "checkin" & "checkout"
This is the code for the first input field:
<input type="text" id="checkin" readonly="true" name="checkin" class="form-control search-input" placeholder="Check-in date" data-provide="datepicker-inline" data-date-orientation="bottom" data-date-autoclose="true" data-date-start-date="now" data-date-format="<?php echo $javascriptLocal ?>" data-date-language="<?php echo $language ?>"required>
<div class="input-group-addon search-icon-right" onclick="$('#checkin')[0].focus()" onfocus="$('#checkin')[0].focus()">
Code for the second field:
<input type="text" readonly="true" id="checkout" name="checkout" class="form-control search-input" placeholder="Check-out date" data-provide="datepicker-inline" data-date-orientation="bottom" data-date-autoclose="true" data-date-start-date="now" data-date-format="<?php echo $javascriptLocal ?>" data-date-language="<?php echo $language ?>"/>
<div class="input-group-addon search-icon-right" onclick="$('#checkout')[0].focus()" onfocus="$('#checkout')[0].focus()">
I tried to achieve it with this javascript:
<script type="text/javascript">
function empty() {
var x;
x = document.getElementById("checkout").value;
if (x == "") {
alert("Select dates to continue");
return false;
};
}
</script>
However, this does not work. Could your please help me?
EDIT:
This is the Javascript that seems to interfere with my code: Any suggestions?
<script>$(document).ready(function(){$(".gotop").on("click",function(){$("html, body").animate({scrollTop:$("body").offset().top},1000)});$("#child").on("change",function(){var a=$(this).val();if(a<=0){$(".child-age-1-container").fadeOut("slow");$(".child-age-2-container").fadeOut("slow");$(".child-age-3-container").fadeOut("slow");$(".child-age-4-container").fadeOut("slow");$("#child-age-1").val(0);$("#child-age-2").val(0);$("#child-age-3").val(0);$("#child-age-4").val(0)}else{if(a==1){$(".child-age-1-container").fadeIn("slow");$(".child-age-2-container").fadeOut("slow");$(".child-age-3-container").fadeOut("slow");$(".child-age-4-container").fadeOut("slow");$("#child-age-2").val(0);$("#child-age-3").val(0);$("#child-age-4").val(0)}else{if(a==2){$(".child-age-1-container").fadeIn("slow");$(".child-age-2-container").fadeIn("slow");$(".child-age-3-container").fadeOut("slow");$(".child-age-4-container").fadeOut("slow");$("#child-age-3").val(0);$("#child-age-4").val(0)}else{if(a==3){$(".child-age-1-container").fadeIn("slow");$(".child-age-2-container").fadeIn("slow");$(".child-age-3-container").fadeIn("slow");$(".child-age-4-container").fadeOut("slow");$("#child-age-4").val(0)}else{if(a>=4){$(".child-age-1-container").fadeIn("slow");$(".child-age-2-container").fadeIn("slow");$(".child-age-3-container").fadeIn("slow");$(".child-age-4-container").fadeIn("slow")}}}}}});$("#checkin").datepicker().on("changeDate",function(){var a=$("#checkin").datepicker("getDate");a.setDate(a.getDate()+2);$("#checkout").datepicker("setDate",a);$("#checkout")[0].focus()});$(".btn-hotel-search").on("click",function(a){a.preventDefault();var j=$("#search-form");var g=$("#child-age-1").val();var f=$("#child-age-2").val();var e=$("#child-age-3").val();var d=$("#child-age-4").val();var b;var c=$("#child").val();var h="";for(b=1;b<=c;b++){h+=$("#child-age-"+b).val()+","}h=h.substr(0,h.length-1);j.append($('<input type="hidden" name="childages">').val(h));j.get(0).submit()})});</script>
Use HTML5 required attribute on the input elements, the form wont be submitted if the fields are empty. to learn more about html5 validation please visit
http://www.the-art-of-web.com/html/html5-form-validation/
You can try like this:
$('form').on("submit",function(e) {
e.stopPropagation();
e.stopImmediatePropagation();
alert('Stopped');
})
Or by button
$('#submitButton').on("click",function(e) {
e.preventDefault();
alert('Stopped');
})
First thing you can do is mark your checkout field as required, jsut like checkin this would help.
Second you can trace your values with temporary alerts while debugging, this helped me a lot when looking for javascript issues.
Third you can try to use a strict comparaison operator and be a bit more specific with the function return values as such
<script type="text/javascript">
function empty() {
var x = document.getElementById("checkin").value;
var y = document.getElementById("checkout").value;
if (x === "" || y === "") {
alert("Select dates to continue");
return false;
};
return true;
}
</script>
You can try something like this in javascript
if(!x){
alert('Stopped');
}
In Javascript every variable can be evaluated as a boolean, so this will generally catch things that are empty, null, or undefined.
Hope it help
Just change it to
if (!x) {
alert("Select dates so continue");
return false;
}
This will check if variable is null, empty, or undefined
use the "required" attribute for the specific input tag
just give input type="submit" below that
<input type="number"
name="stock"
required
onChange={(e)=>{this.setState({ quantity: e.target.value , number: val.qty})}}/>
<input type="submit" />
WORKS PERFECT!!!
So I have this jQuery for my form:
frm.submit(function(event) {
validateForm();
if(validateForm()) {
$(this).submit();
} else {
event.preventDefault();
}
});
It does sort of work, but I get JS <error> (and it doesn't say anything else in the console about it), I think the reason is that the function has to go through the validation again? Kind of like a circular dependency.
Can you show me a better way to do the exact thing that I'm trying to achieve here please?
Validate and show errors if filled in the wrong way;
Submit the form if everything is ok
Something like this maybe?
HTML -
<input type="text" id="name" />
<input type="tel" id="phone" />
<button type="button" id="submit">Submit</button>
<div id="errors"></div>
JS -
const user = {}
$('#submit').click(function(){
// validating form
if(!$('#name').val()) {
$('#errors').text('invalid value in "name" field')
return;
}
if(!$('#phone').val()) {
$('#errors').text('invalid value in "phone" field')
return;
}
$('#errors').text('');
user.phone = $('#phone').val();
user.name = $('#name').val();
// form submission goes here
});
Logic -
Once a function returns, the execution of anything else after the return expression itself, is prevented.
If you don't return anything, the interpreter will continue to the next expression.
This gives you the option of manipulating elements and handle errors just before returning and stopping the function from continuing to run.
function validateForm(){
if (input.val().isok && select.val().ispresent){
form.submit();
}else{
show_errors();
}
}
why not that way?
In PHP, if the text input "cmtx_comment" is empty, on form submit I show a javascript alert. After I press OK in the alert, the values entered by the user in all fields in the form are gone. How can I keep the user entered values, without adding code to the value of the input elements (something like <input type="text" name="something" value="<?php echo $_GET['something'];?>"> ?
if (empty($cmtx_comment)) { //if comment value is empty
echo <<<EOD
<script>
alert('Please enter a comment!');
</script>
EOD;
return false;
} else { //if comment entered
do stuff
Have you tried localStorage and form validation?
HTML:
<form method="post" action="" onSubmit="return saveComment();">
<input type="text" name="cmtx_comment" id="cmtx_comment" value="" />
<input type="submit" value="Save" />
</form>
JavaScript:
document.getElementById("cmtx_comment").value = localStorage.getItem("comment");
function saveComment() {
var comment = document.getElementById("cmtx_comment").value;
if (comment == "") {
alert("Please enter a comment in first!");
return false;
}
localStorage.setItem("comment", comment);
alert("Your comment has been saved!");
location.reload();
return false;
//return true;
}
Example
On first page load, you are presented with:
If you don't enter a comment, you get the alert:
If you do enter a comment, you get a different alert:
The page will then refresh (or post, simply un-comment the return true, and comment the location.reload), and you will still see the contents you posted the first time.
Once again the novice JS is back again with a question. I want a confirmation tickbox at the end of my form before allowing the user to send me their details and if it's not ticked then they can't submit the form. I've had a look on here and tried using different examples of coding but I just find it all very confusing after looking at 10 or 20 pages of different code. Here is what I've written so far, from what I can make out my form just skips over my checkbox validation code which is obviously what I don't want to happen:
<head>
<script>
function validate (){
send = document.getElementById("confirm").value;
errors = "";
if (send.checked == false){
errors += "Please tick the checkbox as confirmation your details are correct \n";
} else if (errors == ""){
alert ("Your details are being sent)
} else {
alert(errors);
}
}
</script>
</head>
<body>
<div>
<label for="confirm" class="fixedwidth">Yes I confirm all my details are correct</label>
<input type="checkbox" name="confirm" id="confirm"/>
</div>
<div class="button">
<input type="submit" value="SUBMIT" onclick="validate()"/>
</div>
I would just enable/disable your button based on the checkbox state. Add an ID to your button, (i'll pretend the submit button has an id of btnSubmit)
document.getElementById("confirm").onchange = function() {
document.getElementById("btnSubmit").disabled = !this.checked;
}
Demo: http://jsfiddle.net/tymeJV/hQ8hF/1
you are making send be confirm's value.
send = document.getElementById("confirm").value;
This way send.checked will not work. Because you are trying to get the attribute checked from a value (probably, string).
For the correct use, try this:
send = document.getElementById("confirm");
sendValue = send.value;
sendCheck = send.checked;
Then you can test with
if (sendCheck == false){ //sendCheck evaluate true if checkbox is checked, false if not.
To stop form from submitting, return false; after the error alerts.
Here the complete code - updated to work correctly (considering the <form> tag has id tesForm):
document.getElementById("testForm").onsubmit = function () {
var send = document.getElementById("confirm"),
sendValue = send.value,
sendCheck = send.checked,
errors = "";
//validate checkbox
if (!sendCheck) {
errors += "Please tick the checkbox as confirmation your details are correct \n";
}
//validate other stuff here
//in case you added more error types above
//stacked all errors and in the end, show them
if (errors != "") {
alert(errors);
return false; //if return, below code will not run
}
//passed all validations, then it's ok
alert("Your details are being sent"); // <- had a missing " after sent.
return true; //will submit
}
Fiddle: http://jsfiddle.net/RaphaelDDL/gHNAf/
You don't need javascript to do this. All modern browsers have native form validation built in. If you mark the checkbox as required, the form will not submit unless it is checked.
<form>
<input type="checkbox" required=""/>
<button type="submit">Done</button>
</form>
<form method="post" action="sendmail.php" name="Email_form">
Message ID <input type="text" name="message_id" /><br/><br/>
Aggressive conduct <input type="radio" name="conduct" value="aggressive contact" /><br/><br/>
Offensive conduct <input type="radio" name="conduct" value="offensive conduct" /><br/><br/>
Rasical conduct <input type="radio" name="conduct" value="Rasical conduct" /><br/><br/>
Intimidating conduct <input type="radio" name="conduct" value="intimidating conduct" /><br/><br/>
<input type="submit" name="submit" value="Send Mail" onclick=validate() />
</form>
window.onload = init;
function init()
{
document.forms["Email_form"].onsubmit = function()
{
validate();
return false;
};
}
function validate()
{
var form = document.forms["Email_form"]; //Try avoiding space in form name.
if(form.elements["message_id"].value == "") { //No value in the "message_id"
box
{
alert("Enter Message Id");
//Alert is not a very good idea.
//You may want to add a span per element for the error message
//An div/span at the form level to populate the error message is also ok
//Populate this div or span with the error message
//document.getElementById("errorDivId").innerHTML = "No message id";
return false; //There is an error. Don't proceed with form submission.
}
}
}
</script>
Am i missing something or am i just being stupid?
edit***
sorry i should add! the problem is that i want the javascript to stop users going to 'sendmail.php' if they have not entered a message id and clicked a radio button... at the moment this does not do this and sends blank emails if nothing is inputted
You are using
validate();
return false;
...which means that the submit event handler always returns false, and always fails to submit. You need to use this instead:
return validate();
Also, where you use document.forms["Email form"] the space should be an underscore.
Here's a completely rewritten example that uses modern, standards-compliant, organised code, and works:
http://jsbin.com/eqozah/3
Note that a successful submission of the form will take you to 'sendmail.php', which doesn't actually exist on the jsbin.com server, and you'll get an error, but you know what I mean.
Here is an updated version that dumbs down the methods used so that it works with Internet Explorer, as well as includes radio button validation:
http://jsbin.com/eqozah/5
You forgot the underscore when identifying the form:
document.forms["Email_form"].onsubmit = ...
EDIT:
document.forms["Email_form"].onsubmit = function() {
return validate();
};
function validate() {
var form = document.forms["Email_form"];
if (form.elements["message_id"].value == "") {
alert("Enter Message Id");
return false;
}
var conduct = form.elements['conduct']; //Grab radio buttons
var conductValue; //Store the selected value
for (var i = 0; i<conduct.length; i++) { //Loop through the list and find selected value
if(conduct[i].checked) { conductValue = conduct[i].value } //Store it
}
if (conductValue == undefined) { //Check to make sure we have a value, otherwise fail and alert the user
alert("Enter Conduct");
return false;
}
return true;
}
return the value of validate. Validate should return true if your validation succeeds, and false otherwise. If the onsubmit function returns false, the page won't change.
EDIT: Added code to check the radio button. You should consider using a javascript framework to make your life easier. Also, you should remove the onclick attribute from your submit input button as validation should be handled in the submit even, not the button's click
Most obvious error, your form has name attribute 'Email_form', but in your Javascript you reference document.forms["Email form"]. The ironic thing is, you even have a comment in there not to use spaces in your form names :)