Am trying to prevent certain user ids from emails to submit form, like a blacklist, for example denieduser1#domain.com and take denieduser1 and when the user submits the form then appears a bootstrap alert saying something is wrong, the problem is that if you click on the button again the form is submitted without doing validation again, if I remove the part where styles are applied and use an alert then it works so here is the code am using:
For the form:
<form id="contact" method="post" class="form" role="form" onsubmit="return validate()" action="m41lS3nd.php">
The validation code:
function validate(){
e.preventDefault;
var rejectList = [ "denied1" , "denied2" ]; //List of Blacklisted emails or domains
var emailValue = $('#email').val(); // To Get Value (can use getElementById)
var splitArray = emailValue.split('#'); // To Get Array
if(rejectList.indexOf(splitArray[0]) >= 0) //Check if contains any unwanted emails
{
// Means it has the rejected domains
document.getElementById("notification").style.display = "block"; //If unwanted emails are detected will show an alert
document.getElementById("notification").style.marginTop = "5px";
return false;
}else
var contactform = document.getElementById("contact"); //If good email is entered then get the form name and submits the form
contactform.submit();
return true;
}
The bootstrap alert:
<!--Notification for invalid emails such as spam or unsolicited emails-->
<div id="notification" class="alert alert-warning alert-dismissible fade in" role="alert" style="display: none;">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<strong>Oops!</strong>There is something wrong with your email, your reference code is: BL1SE.
</div>
The Submit Button:
<button class="btn btn btn-md" type="submit">Send Message <i class="fa fa-paper-plane fa-1x" style="color: white;"></i></button>
I took the code and adapted from this post but cannot comment or contact author and don't know what am doing wrong: Code for validation
It looks like your Javascript syntax is incorrect because e.preventDefault(); is referring to a nonexistent variable. I suspect your Javascript console is reporting the error.
I would also strongly recommend adding {} as appropriate after the else. I'd guess that's not going to behave exactly the way you think. Formatted to show the difference:
} else
var contactform = document.getElementById("contact");
contactform.submit();
return true;
compared with:
} else {
var contactform = document.getElementById("contact");
contactform.submit();
}
return true;
If you added another else/if condition that does not return then you will hit contactform.submit(); without having declaring and initializing contactform.
Related
I am trying to create a simple google search bar in my website. It works fine. However, I am accounting for user error, and for some reason I cannot re-enable my submit button once it is clicked, under the condition that no input is provided. Please see Javascript code below.
const text = document.querySelector("#search");
const msg = document.querySelector(".msg");
document.querySelector(".google-form").addEventListener('submit', onclick)
function onclick(e) {
if (text.value === '' || text.value === null) {
e.preventDefault();
msg.classList.add('error');
msg.innerHTML = 'Please enter a proper search query';
setTimeout(() => msg.remove(), 3000);
document.querySelector("#button").disabled = false; // <-- This method doesn't seem to work.
}
}
<div class="google-form">
<div class="msg"></div>
<form id="my-form" action="https://www.google.com/search">
<input id="search" type="text" name="q" placeholder="Enter Search">
<button id="button" type="submit">Submit</button>
</form>
</div>
As you can see, if no text is input, it will let the user know they will need to enter an actual search query. However, after that point, the submit button just wont work again.
I tried using .querySelector().disabled = false; , as well as .removeAttribute("disabled"), but nothing is working. What exactly am I missing here, to re-activate the submit button once it was clicked with no input?
Your button works just fine. You just remove the complete element and then the msg = document.querySelector(".msg"); doesn't find anything. In addition i would leave the timeout out and let the message there until the user writes something.
You should do it like that:
const text = document.querySelector("#search");
const msg = document.querySelector(".msg");
document.querySelector(".google-form").addEventListener('submit', onclick)
function onclick(e) {
msg.innerHTML= '';
if (text.value === '' || text.value === null) {
e.preventDefault();
msg.classList.add('error');
msg.innerHTML = 'Please enter a proper search query';
document.querySelector("#button").disabled = false; // <-- This method doesn't seem to work.
}
}
<div class="google-form">
<div class="msg"></div>
<form id="my-form" action="https://www.google.com/search">
<input id="search" type="text" name="q" placeholder="Enter Search">
<button id="button" type="submit">Submit</button>
</form>
</div>
When button type is set on submit value, it will send the information to the server anyway. (not if you use preventDefault() method!)
My suggestion is to change button type to button and then write an onclick event for it and check the validation there , if everything was right then call for form submit event!
This is how you can prevent incorrect information from being sent into the server side and avoid the errors that it can cause.
I am trying to add error message handling in Javascript but am having trouble. If a user inputs a state that is not two characters in length, I am trying to have it output an error message. I also am including my renderBarChart function too if that helps.
js
stateSubmitButton.addEventListener("click", function(event) {
event.preventDefault();
state = stateUserInput.value.toUpperCase();
let stateFeedbackElem = document.querySelector("#stateFeedback");
if (state.length == 2) {
stateUserInput.setCustomValidity("");
stateFeedbackElem.textContent = "";
renderBarChart(state);
state = "";
} else {
stateUserInput.setCustomValidity("Please enter a two letter abbreviated state.");
stateFeedbackElem.textContent = "Please enter a two letter abbreviated state.";
state = "";
}
})
html
<form class="form" novalidate>
<label for="state-input">State:</label>
<input name="state" type="text" id="state-input" placeholder="(i.e. WA)">
<button type="submit" id="state-submit" class="btn btn-dark btn-lg ml-2">Submit</button>
<div id="stateFeedback" class="invalid-feedback"></div>
</form>
I noticed a couple of problems.
You have set novalidate on your form, which means .setCustomValidity() error will not be shown as validation will not be performed.
If the novalidate attribute is set on the <form> element, interactive
validation of the constraints doesn't happen.
-- Constraint validation
If stateUserInput is the #state-input input, .textContent should work, and the text should be set. But it is probably not shown as the invalid-feedback class has CSS property display: none;. You need to add a d-block class or use invalid-feedback element as shown in Bootstrap examples.
And just a note, prefer to add an event listener on the form and listen for the SubmitEvent instead of the click event on the submit button.
Here is a form
<cfoutput>
<form name = "xrefform"
id = "xrefform"
action = ""
method = "post"
onsubmit = "return submitx('#coltop#', '#col#')">
</cfoutput>
There are two different way to submit it:
1) when you want the data in the form to be placed in a MySql Table
2) when you want the data to be deleted from the Mysql Table
For the first case I have
<input type = "Submit"
name = "SubmitXref"
class = "submitbut"
value = "Submit"
onclick = "aasubmit('xref2.cfm')">
with corresponding javascript:
function aasubmit(target) {
document.xrefform.action = target;
}//end function aasubmit
This works fine.
For the delete case I have
<input type = "Submit"
id = "delbut"
class = "onoffbut"
value = "delete"
onclick = "aasubmit('repdel.cfm')">
This has a problem, which is that the submitx() javascript runs, and in this case I don't want it to.
I find references that say using the document.form.submit() method will avoid running the onsubmit function. But I can't figure out how to indicate the action.
Can someone show me how to do this?
After fussing around some more I found the answer:
For the delete button --which needs to evade the onsubmit script --here is the HTML:
<input type = "button"
id = "delbut"
value = "Delete this item"
onclick = "buttonsubmit('xrefdel.cfm', 'xrefform')">
And here is the javascript.
function buttonsubmit(target, source) {
var q = document.getElementById(source);
q.action = target;
q.submit();
}
This works perfectly. The ordinary submit honors the onsubmit script, the delete button skips it.
Let's outline your requirements:
One form
Two submit buttons
No JavaScript submit.
If you give each of the submit buttons a name, then you can have a single action page and check which button was clicked.
name="doUpdate" or name="doDelete"
The only name key that will exist in the form scope is whichever submit button was clicked. Use structKeyExists() to check and process accordingly.
Of course, you probably want to use onsubmit="return validateForm()" to call a validation function. If you click on "delete", you might want the user to confirm that was what they wanted to do before processing it. The function validateForm() just needs to return true or false, so you'll still avoid the JavaScript submit().
Do something like this in the form:
<input name="action" value="save" id="action" type="hidden">
<button type="submit" class="button button-basic-green" onclick="document.getElementById('action').value='save';"><span class="fa fa-save"></span> Save</button>
<button type="submit" class="button button-basic" onclick="document.getElementById('action').value='reload';"><span class="fa fa-repeat"></span> Save & Reload</button>
<button type="submit" class="button button-basic" onclick="document.location.href='./';return false;"><span class="fa fa-arrow-circle-o-left"></span> Cancel</button>
Note the default action of "save". Gets you something like:
Then in the singular form-action page, check to see what the form.action is and process accordingly.
<cfif form.action eq "reload">
<cfset loc="page.cfm?id=#form.id#">
<cfelse>
<cfset loc="./">
</cfif>
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>
I am using credit card validation in my cartridge project to validate the card type and card number.Everything is working fine, but whenever I got the validation error in alert box and when I click OK it doesn't stop on that page but refer me to the next page,Thus I am getting an error or not my order is got placed.
Here is my code.
<input type="submit" class="btn btn-large btn-primary" onClick="cardchk();" value="{% trans "Next" %}">
function cardchk()
{
var card_typ=$("input[name='card_type']:checked")[0].value;
//alert(card_typ);
if(card_typ=='Visa')
{
var cardname = 'Visa';
}
else
{
var cardname = 'MasterCard';
}
//alert(cardname);
var cardnumber = document.getElementById('id_card_number').value;
if(!checkCreditCard (cardnumber, cardname)){
alert(ccErrors[ccErrorNo]);
return false;
}
}
However I have returned false in my function but on getting error it refer me to the confirmation page but I want as normally validation do to stop processing the request whenever I got the error
Thanks !
you need
onClick="return cardchk();"
not just
onClick="cardchk();"
nb. I don't see here that you are using jquery validate