javascript to check if user has inputted [closed] - javascript

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I have a 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" />
</form>
I need some sort of validation javascript that:
Checks if user entered a message id and checked one of the radio buttons. (So message id and radio group are required fields)
Display an error message if any of the required fields is not set.
Block form submit until required fields are entered.
Can anyone help?

You will have to do a validation before submit.
Add an on submit event handler (that will be called when the form is submitted) to the form:
You can do this in two ways:
<form method="post" action="sendmail.php" name="Email form" onsubmit=validate()>
OR
in the <script> part:
window.onload = init;
function init()
{
document.forms["Email form"].onsubmit = function()
{
validate();
return false;
};
}
Now write the validate function itself (same for both options above):
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.
}
}

UPDATE. Now it should work.
// Register onsubmit callback function (this will be called when the user submit his data).
document.forms[0].onsubmit = validate;
function validate() {
var message = document.getElementsByTagName('input')[0].value,
radioButtons = document.getElementsByTagName('input'),
oneRadioChecked = false;
// check that message is not empty
if (message.length === 0) {
alert("no message inserted");
return false;
}
// check that at least one radio has been checked
for (var i = 0; i < radioButtons.length && !oneRadioChecked; i++) {
oneRadioChecked = (radioButtons[i].type === "radio" &&radioButtons[i].checked);
}
if (!oneRadioChecked) {
alert("no radio button checked");
return false;
}
}

Related

Conditionally required form field (Checkbox)

I already checked multiple sites and posts regarding this topic, but couldn't find an answer yet. I simply want to fire the following JS code if someone clicked a specific Checkbox in my form:
function updateRequirements() {
var escortWrapper = document.querySelector(".elementor-field-type-html .elementor-field-group .elementor-column .elementor-field-group-field_ceffa28 .elementor-col-100");
if (escortWrapper.style.display != 'none') {
document.getElementById('escort').required = true;
} else {
document.getElementById('escort').required = false;
}
}
You can check and test that for yourself on the following site:
Advelio Website
If you click on the second checkbox field, there is a field appearing where you can type in your name. And this field is currently optional, but I want to make this required if someone clicked the second checkbox.
You can do it like this:
function updateRequirements() {
const btn = document.getElementById('escort');
btn.required = !btn.required;
}
document.querySelector("#requireCheck").addEventListener('click', updateRequirements);
<form>
<input type="checkbox" id="requireCheck">
<label for="requireCheck">Should the the other input be required?</label>
<br>
<input type="text" id="escort">
<input type="submit" value="submit">
</form>
I simplified the function updateRequirements for the scope of this answer, but it can be changed to anything or any condition.
You have to have event listener for click event and if you dont have create one and wrote the function with logic what to do if is click

need help about Php or Javascript Validation

I dont know how to do a self validation within the page.
I have a php file contains a checkbox and a lot of textboxes. What i would like to do is that, what the user will check on the checkbox will require the textboxes to be filled up. I tried to validate using my statement in php but it always redirect to another page before it validates everything, what i want is that when the user click the submit button, it will trigger the whole page and validate those that should be filled up.
user will check any of the checkbox
then it has a corresponding condition that will make the textboxes required to be filled in!
Hope you guys can help me. I dont know how to do it. javascript or anything? I need solution and show me please.
Codes are like this:
Test 1 <input name="chkbox[]" type="checkbox" value="1"><br>
Test 2 <input name="chkbox[]" type="checkbox" value="2"><br>
Test 3 <input name="chkbox[]" type="checkbox" value="3"><br>
Test 4 <input name="chkbox[]" type="checkbox" value="4"><br>
Test 5 <input name="chkbox[]" type="checkbox" value="5"><br>
<br><br>
Name <input name="txt1" type="text"><br>
Address <input name="txt2" type="text"><br>
Number <input name="txt3" type="text"><br>
Age <input name="txt4" type="text"><br>
Two options for this (all in javascript).
The first, as requested is validating when the user tries to submit.
document.addEventListener("DOMContentLoaded", function (event) {
var isValid = false;
document.querySelector("#formid").addEventListener("submit", function(e){
var _selector = document.querySelectorAll('input[type=checkbox]:checked');
var checked = _selector.length;
for(var i = 0; i<checked; i++){
if (_selector[i].checked) {
if(!document.querySelector('input[name=txt'+ _selector[i].value +']').value)
break;
}
}
if(checked == i)
isValid = true;
if(!isValid){
alert('at least one field is empty');
e.preventDefault(); //stop form from submitting
}
});
});
the second uses an eventlistener to add and remove the required field.
document.addEventListener("DOMContentLoaded", function (event) {
var _selector = document.querySelectorAll('input[type=checkbox]');
for(var i = 0; i<_selector.length; i++){
_selector[i].addEventListener('change', function (event) {
if (event.target.checked) {
document.querySelector('input[name=txt'+ event.target.value +']').required = true;
} else {
document.querySelector('input[name=txt'+ event.target.value +']').required = false;
}
});
}
});
Then you can style the required fields to show which needs to be filled:
:required{border: red solid 1px;}

Javascript: redirect to new page based on radio button choice

What I am trying to do is redirect to a new page if the "yes" button is clicked. I already have a prompt set up if they click "no". However, there is a form (name and email) that needs to be filled out for this to work. If they do not fill out these details, I want a prompt to arise telling the user that they need to fill them out before they can proceed.
I am fairly new to javascript so any tips or explanations would be greatly appreciated.
Below is the html code
<input type="radio" name="radio" id="yes"><strong>Yes, I agree.</strong>
<br>
<input type="radio" name="radio" id="no" checked="checked"><strong>No, I do not agree. </strong><br>
<br>
If you agree, please enter your full name and email address in the spaces below and press submit.
<br>
<form> Full Name:<input type="text" name="fullname"></form>
<br>
<form> Email Address:<input type="text" name="email"></form>
<br>
<br>
<form action="endPage.jsp" id="form">
<input type="submit" id="submit" value="Submit" name="submit" />
</form>
And the javascript code
var submitBtn = document.getElementById("submit");
var termsChk = document.getElementById("yes");
var formFrm = document.getElementById("emailField");
var formFrm = document.getElementById("nameField");
submitBtn.addEventListener("click", function() {
if (termsChk.checked === true && formFrm)
{
alert("Checked!");
formFrm.submit();
} else {
alert("Please Contact Spearhead Mining Corporation: projects#spearheadmining.com to discuss your options for project submittal!");
}
return false;
});
Use window.confirm() with the spcific message to user and use window.location() to redirect to the new url.
result = window.confirm("Message to user");
if(result) {
window.location = "new url";
} else {
//do the rest of logic
}
For a more specific answer it might help if you posted the code for yes and no buttons, as well as the HTML code for the form. That being said the way you would generally handle this is in the code for the yes button you run whatever client side validations you need to run, in this case checking if the name and email fields aren't empty, then displaying your error message instead of redirecting if everything is not valid.
For instance in your yes handler
if(document.getElementById('emailField').value == null || document.getElementById('namefield') == null){
/*error handling code goes here*/
return
}
else{
/*redirection code goes here*/
}

how to keep the filled data remain after a incomplete form submit? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
<html>
<head><script type="text/javascript">
function pa(){
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var email = document.getElementById('email').value;
if(fname==""||lname==""||email=="")
alert("Please, Compelete the form...");}
</script>
</head> <body>
<form onsubmit="pa()">
E-mail Address*<input id="email" value="" name="email" type="text">
First Name*<input id="fname" value="" name="fname" type="text">
Last Name*<input id="lname" value="" name="lname" type="text">
<input type="submit" value="Register">
</form>
</body>
</html>
Hi,above is my code which is causing some problem .i.e,When i press submit button and if the form is incomplete then it has a alert box showing "Please complete the form...".
After i press "ok" the filled data are refreshed.I want to keep the filled data. I have no idea for this problem.I want my data should remain if the form is incompletely submitted.
pls help me with this
I think you have to prevent the submit event to be forwarded. Try with:
if (fname==""|| ...) {
alert('...');
return false;
}
Regards
parascus
You need to add return false; to your onsubmit function. The problem is that the onsubmit function runs before the page posts the form. This function can return a true or false boolean indicating whether to repost the page. In your case, you are not returning either, so the page "submits" and reposts and all the user data is gone.
For Example:
<form onsubmit="return pa();">
...
</form>
And in the pa function:
function pa() {
...
if( some conditional ) {
return true;
} else {
return false;
}
}
Hope this helps.
instead of <form onsubmit="pa()"> use <form onsubmit=" return pa()">. in your code return false after u post a alert.this should fix your problem
Here is on approach to helping you out.
1.Connect jQuery to your page.
2.Place an ID selector on your form element like this...
<form id="myform">
3.Then add the following script code to your page
$(function() {
$('#myform').submit(function () {
pa();
return false;
});
});

Checkbox js toggling incorrectly

I have a check box in my registration form like this:
<form name="reg" id="reg" method="post">
<input type="checkbox" onclick="return validate('tos')" name="tos"/>
</form>
And I am using JS to check if its ticked, and if so, display a green tick in the form. However, its not actually ticking the check box when its clicked but it is loading the green tick.
Additionally, clicking it a second time doesn't remove the green tick which it should, because the user effectively unticked the check box.
So my JS is this:
function validate (type){
output = [];
var x = document.getElementById("reg");
if (type == 'tos'){
div = 'result_tos';
input = x.elements[4].checked;
if (input){
output.push('<img src="correct.png"/>');
} else {
output.push('You must agree to our terms of service in order to join !');
}
document.getElementById(div).innerHTML = (output.join('')); //display result
}
}
The following jsfiddle is a slightly modified version of your code that seems to be working fine. I don't think your error is here. (I'm not familiar with elements; is that IE specific? I changed that to work on other browsers.)
http://jsfiddle.net/QnDAg/1/
I would approach this as below. Pass a reference to the element from the listener.
<form name="reg" id="reg" method="post">
<input type="checkbox" onclick="return validate(this)" name="tos">
</form>
<script type="text/javascript">
function validate(el) {
// you don't really need a reference to the form,
// but here's how to get it from the element
var form = el.form;
if (el.name == 'tos') {
if (el.checked) {
// show pass graphic (green tick?)
} else {
// hide checkbox and show text
}
}
}
</script>
Swapping between displaying the tick and text should be done by setting a class value, that way you can change it to whatever you want in the markup and the script just toggles the two.
This is probably how I would suggest you do this, which is more complex than the example given, but I'm struggling a little bit with the intended flow and the flow the OP is using:
Mock HTML
<form name="reg" id="reg" method="post">
<input type="checkbox" id="agree" name="agree"/> Agreement<br/>
<input type="checkbox" id="ok" name="ok"/> Ok<br/>
<input type="checkbox" id="tos" name="tos"/> TOS<br/>
<button name="submit" type="submit">Submit Validation</button>
</form>
<h1>Display Output</h1>
<div id="display"></div>​
Iterating Validation
function validate (){
var display = document.getElementById('display'),
output = [],
checks = ['agree','ok','tos'],
check,
msg;
while (check = document.reg[checks.pop()]) {
if (!check.checked) {
switch (check.name) {
case 'agree':
msg = 'You must AGREE!';
break;
case 'ok':
msg = 'You must OK!';
break;
case 'tos':
msg = 'You must TOS!';
break;
}
output.push(msg);
}
}
if (output.length == 0) {
output = [
'You have successfully validated!',
'<img src="http://goo.gl/UohAz"/>'
];
}
display.innerHTML = output.join('<br>');
return false;
}
And don't forget the window.onload when you attach the event handler. Below isn't necessarily the preferred preferred method, but it's cleaner than inline handlers like onclick="validate()".
window.onload = function(){
document.reg.onsubmit = validate;
};
http://jsfiddle.net/bj5rj/2

Categories