Form using javascript make field required? - javascript

I have a form that uses a javascript file items.js to add new items. So each time form.php is used and the 'add items' buttons is clicked then the new row of fields show to add details.
So for example some of the code is the following to add field item name.
newCell = newRow.insertCell(3);
newCell.innerHTML = '<input class="item_text_area item_name" type="text" name="0_item_' + new_item + '" id="0_item_' + new_items + '" size="20" maxlength="250" />';
How can I edit this .js file to make the Item name field required?
Any help would be appreciated.

Per Jeevan: As you cannot be sure how many items the user submits, I would choose for an approach where all new items have unique class, say dynamicAddedItems.
As Jeevan already said, you can add the following to the form tag to prevent it from submitting if it returns false.
<form onsubmit="return validate();"></form>
With javascript:
function validate(){
var elems = document.getElementsByClassName( 'dynamicAddedItems' );
var allgood = true;
//Loop through all elements with this class
for( var i = 0; i < elems.length; i++ ) {
if( !elems[i].value || !elems[i].value.length ) {
elems[i].className += " error";
allgood = false;
} else {
elems[i].className = "item_text_area item_name dynamicAddedItems";
}
}
//If any element did not meet the requirements, prevent it from being submitted and display an alert
if( !allgood ) {
alert( "Please fill in all the required fields." );
return false;
}
//Otherwise submit the form
return true;
}
This script will add the error class if a field is empty and prevent the form from being submitted. It's up to you how you want to display a field with such a class.

You can use jquery for this. Add a class, in this case 'requiredAttr' to the required fields and then validate on form submit.
<form onsubmit="return validate();">
First Name*: <input class="requiredAttr" type="text" /><br/>
Last Name: <input type="text" /><br/>
<input type="submit" />
</form>
function validate(){
$(".requiredAttr").each(function(){
if($(this).val().length < 1){
alert("please fill in all the required fields.");
$(this).focus();
return false;
}
else{
return true;
}
});
return false;
}
Here is a working fiddle. It also brings the focus on the first un-filled field after the validation alert:
http://jsfiddle.net/YG6mk/2/

Related

JavaScript HTML validation function only works when the form elements are all filled

I'm making sign in form with submit. What I want to do is to alert when there is blank in the form. But the function only works when all of the form are filled. Here's the HTML and JS code. The result is the same using onsubmit inside of the HTML or addEventListener("submit" function name)
HTML : It's basically a form for sign in / ordering.
<form id="registration" method="POST" onsubmit="return validate();" action="phplink">
<p> <label for="custName">Name : </label>
<input type="text" id="cname" name="cname" required="required" /> </p>
</form>
JS :
function validate(event) {
event.preventDefault();
var r = document.getElementById("registration");
var cname = r.cname.value;
var errMsg = "";
if (cname == "") {
errMsg += "Please enter your Name.\n";
}
if (errMsg.length != 0) {
alert(errMsg);
result = false;
}
return result;
}
The validation constrains, such as your required="required" are validated before your browser will trigger a submit event. If the validation fails (a value to a required field is not provided) it will not submit your form.
If you want to do the validation using JavaScript instead of the validation constraint attributes, you either need to remove the required="required" attribute (together with any other similar attributes) or you can add the novalidate attribute to your form to indicate that it should not perform this validation on submit.
If you use the latter, you can still use formElement.reportValidity() to see if all the elements satisfy their validation constraints.
If you add a required attribute to each field that shouldn’t be blank, it’ll prevent form submission with empty fields, like this...
<input type="text" name="username" required>
Hi you have several problem. on submit must pass event => onsubmit="return validate(event);" .
you must first defined result and thats your flag => var result = false .
if you want show alert then input dont need required attribute.
so this is your Fixed Code;
function validate(event) {
event.preventDefault();
var result = true;
var r = document.getElementById("registration");
var cname = r.cname.value;
var errMsg = "";
if (cname == "") {
errMsg += "Please enter your Name.\n";
}
if (errMsg.length != 0) {
alert(errMsg);
result = false;
}
return result;
}

How to remove oninvalid for every input except one using javascript?

I created a form with some input fields and the user needs to fill at least one field and if the user doesn't select any then the error will be shown. I achieve that goal but I need to show my custom require message as invalid. Because of the oninvalid on every input, My code is not working properly but I want this message to show so how can I remove oninvalid from the rest of the input fields rather than the filled one?
<form>
<input name="youtube" oninvalid="this.setCustomValidity('Please fill out at least one social media field')" required/>
<input name="vimeo" oninvalid="this.setCustomValidity('Please fill out at least one social media field')" required/>
<input name="pinterest" oninvalid="this.setCustomValidity('Please fill out at least one social media field')" required/>
<input type="submit" name="submit" value="Submit" id="ls-submit">
</form>
document.addEventListener('DOMContentLoaded', function () {
const inputs = Array.from(document.querySelectorAll('input[name=youtube], input[name=vimeo], input[name=pinterest]'));
const inputListener = e => inputs.filter(i => i !== e.target).forEach(i => i.required = !e.target.value.length, i => i.oninvalid = !e.target.value.length);
inputs.forEach(i => i.addEventListener('input', inputListener));
});
I really don't have an idea what to do. We can also use alert as an error message and I tried that too but didn't get any success.
You could remove oninvalid and required from all inputs and check it instead with javascript:
var inputs = document.querySelectorAll('input');
document.querySelector('button').addEventListener('click', function() {
var valid = false;
for(i = 0; i < inputs.length; i++) {
if ( inputs[i].value != "" ) {
valid = true;
break;
}
}
if (valid) {
document.querySelector("form").submit();
}
else {
alert('Please fill out at least one social media field');
}
});
Working example (with 'alert' instead of 'setCustomValidity'):
var inputs = document.querySelectorAll('input');
document.querySelector('button').addEventListener('click', function() {
for(i = 0; i < inputs.length; i++) {
var valid = false;
if ( inputs[i].value != "" ) {
valid = true;
break;
}
}
if (valid) {
document.querySelector("form").submit();
}
else {
alert('Please fill out at least one social media field');
}
});
<form action="https://stackoverflow.com" method="GET">
<input name="youtube" value="">
<input name="vimeo" value="">
<input name="pinterest" value="">
<button type="button">submit</button>
</form>

How to validate all inputs which exists on page?

All inputs from page
I have this html page which is dynamical created, which contains some divs. Every div-question(0,1,2, etc) contain an input based on which answer type the user chose. I want to validate every single inputs from page and:
If value of one input type number,text,date is != "" alert("something")
else send the value in an array;
If checkbox/radio is not checked alert("something");
I tried something like this:
let nrDiv = document.getElementsByClassName("div-question");
let existInput = nrDiv[0].querySelector("input[type='text']");
let numberInput = nrDiv[0].querySelector("input[type='number']");
if (document.body.contains(existInput)) {
for (let i=0; i < nrDiv.length ;i++) {
let container = document.getElementsByClassName("div-questions" + i + "");
let userInputAnswer = container[0].querySelector("input[type='text']");
if (userInputAnswer.value == "") {
alert("Adaugati un raspuns!")
return;
}
if (userInputAnswer.value != ""){
let answer = {
question: questions[i].textQuestion,
answer: userInputAnswer.value
}
answers.push(answer);
}
}
}
It's working but if I come with another for loop, for input type="number" is not working anymore. I'm getting value null. So if I come with this:
if (document.body.contains(numberInput)) {
for (let i=0; i < nrDiv.length ;i++) {
let container = document.getElementsByClassName("div-questions" + i + "");
let userInputAnswer = container.querySelector("input[type='number']");
if (userInputAnswer.value == "") {
alert("Adaugati un raspuns!")
return;
}
if (userInputAnswer.value != ""){
let answer = {
question: questions[i].textQuestion,
answer: userInputAnswer.value
}
answers.push(answer);
}
}
}
And for the checkbox and radio inputs I don't have any idea. I want something like this:
If all inputs are not empty and minimum one checkbox/radio is checked, send the answer and question in an array else alert("error");
I feel like this is simple once you add the required attribute and/or a pattern.
This is a simple POC:
<form action="">
<input type="text" required>
<input type="number" required>
<input type="checkbox" required>
<input type="radio" required>
<input type="date" required>
<button type="submit">Submit</button>
</form>
Notice that when you click the submit button, it does the verification you want, in this case != "".

onclick for radio button using javascript

I am trying to write this program for this survey I want a user to answer, after they have completed the survey they would go to click on submit and it would display confirmation of their choices. I can't get this to work for the life of me.
Here's my code:
<!DOCTYPE html>
<title> Satisfaction Survey </title>
<script Language ="Javascript">
function testpage() {
errmsg = " ";
confirmmsg = " ";
errflag = false;
if ( document.form1.rdservice[0].checked == true ) {
confirmmsg = confirmmsg + "<br> Overall is very satsified" ;
}
if ( document.form1.rdservice[1].checked == true ) {
confirmmsg = confirmmsg + "<br> Overall is satisfied" ;
}
if ( document.form1.rdservice[2].checked == true ) {
confirmmsg = confirmmsg + "<br> Overall is neutral" ;
}
if ( document.form1.rdservice[3].checked == true ) {
confirmmsg = confirmmsg + "<br> Overall is unsatsified" ;
}
if ( document.form1.rdservice[4].checked == true ) {
confirmmsg = confirmmsg + "<br> Overall is very unsatsified" ;
}
if ( (doucment.form1.rdservice[0].checked == false) &&
(doucment.form1.rdservice[1].checked == false) &&
(doucment.form1.rdservice[2].checked == false) &&
(doucment.form1.rdservice[3].checked == "false") &&
(doucment.form1.rdservice[4].checked == false)) {
errflag = true;
errmsg = errmsg + "<br> You forgot to select an option";
}
}
</script>
<body>
<form name=form1 method="post">
<fieldset>
<legend> Please take a few moments to complete this satisfaction survey. </legend>
<fieldset>
<legend> Overall, how satisfied were you with the product / service? </legend>
<input type="radio" name="rdservice" value="v"> Very Satisfied
<br>
<input type="radio" name="rdservice" value="s"> Satisfied
<br>
<input type="radio" name="rdservice" value="n"> Neutral
<br>
<input type="radio" name="rdservice" value="un"> Unsatisfied
<br>
<input type="radio" name="rdservice" value="vu"> Very Unsatisfied
</fieldset>
<fieldset>
<input type="submit" name="subm1" value="Submit" onclick="testpge()">
<input type="Reset" name="Res1" value="Reset Form">
</fieldset>
</fieldset>
</body>
</form>
</html>
The code is a bit mess, can I suggest to use jquery(https://jquery.com/download/)? It will make your life a lot of easier!
here is the jquery code that you need:
var confirmmsg = "";
var errflag = false;
var errmsg = "";
$.each($('form input[type=radio]'), function() {
if($(this).is(":checked")) {
confirmmsg += "<br> Overall is " + $(this).text();
} else {
errflag = true;
}
});
if (errflag) {
errmsg = "<br> You forgot to select an option";
}
This code takes each input radio element and check if it's checked and then make the confirmmsg and also if one of them it's not checked then the errflag becomes true and also you set up the errmsg
btw, I think you need checkbox instead of radio inputs here
(non jquery approach)
Form inputs that are "button" are simply buttons. You can attach event to those inputs, but they aren't related to submitting form. If you want to make button which will send form you should set "type" attribute to "submit". And then you can verify your form in JavaScript by adding event "onsubmit" to <form> tag, not the button. You can also use "onreset" to catch event if someone press button which cleans form. If you are adding "onsubmit" function, like:
onsumit="return testpage(this);"
you can easy decide inside that function, if form should be send or not. You can do this by returning value. If you return true, form will be send, and if you return false form will not be send. You can also disable sending form by setting "action" attribute of <form> tag to "javascript:void(0);"
In your code i would add "onsubmit" event to <form> tag and i would remove "onclick" from submit button (you are calling function and then posting form) and i also would change function code to:
function testpage(frm)
{
var radioBoxSelected = false;
for(var i=0; i < frm.elements.length;i++)
{
if (frm.elements[i].type == 'radio' && frm.elements[i].checked) {
radioBoxSelected = true;
val = frm.elements[i].value;
// You can move messages to attribute "value" of radio boxes
alert('You have selected: ' + val);
// Below line sets some tag inner content to radiobox "value" attribute
document.getElementById("satisfied_value").innerHTML = val;
// Uncomment if you want send form here
//return true;
}
}
if (!radioBoxSelected) {
alert('Please select option!');
return false;
}
}

How to refresh the form value using JQuery

I have a html form. I want to take the input value (a url), extract a number from the url using regex ( '/[0-9]{5,}/') , and then refresh the form value with the number extracted and appended to another url. If I can't find a number - I just want an error to appear in the form box. All using Jquery to avoid page reload.
This is the existing form
<form id = "submit" method="post">
<label for="link_website_url">Create a short url</label>
<input id="link_website_url" name="link" size="30" type="text" />
<input class="go" name="commit" type="submit" value="Go!" /></form>
$('#submit').submit(function(){
var url = $('#link_website_url').val(); //http://example.com/12345
var num = yourNumExtractorFunction(url); //returns -1 if there is no number extracted
if(num > -1){
$('#link_website_url').val('http://otherdomain.com/' + num); //http://otherdomain.com/12345
}else{
$('#link_website_url').after('<span id="error_link_web_url" class="error">Incorrect format! Please try again.</span>');
return false; //error, so cancel this submit
}
});
If you perform additional validation, cancel the submit even if an individual check passes, clear error messages per check that validates (e.g. $('#error_link_web_url').remove();) and submit after all checks pass:
var checkFailed = false;
$('#submit').submit(function(){
var url = $('#link_website_url').val(); //http://example.com/12345
var num = yourNumExtractorFunction(url); //returns -1 if there is no number extracted
if(num > -1){
$('#link_website_url').val('http://otherdomain.com/' + num); //http://otherdomain.com/12345
$('#error_link_web_url').remove();
}else{
$('#link_website_url').after('<span id="error_link_web_url" class="error">Incorrect format! Please try again.</span>');
checkFailed = true;
}
/*Other checks...*/
if(checkFailed){
return false; //cancel submit
}
});
$('#submit').submit(function(){
var url = $('#link_website_url').value();
var val = <do your processing here>;
$('#link_website_url').value(val);
return false;
});

Categories

Resources