How do I validate "textarea" after checkbox is checked with javascript - javascript

I've made a form with few questions. Each question has checkboxes or radio buttons, depending on what type of question it is (how many answers can there be).
Then I've started making a validation function, to be able to check if the user went through the whole form.
I am unsure how to make a validation function that would only trigger if a certain answer is picked (certain checkbox is checked, would trigger the function to check for textarea and check its content).
The code I've got so far can be found here.
The code is also available below:
// main function for checking the validation of answer
function Validation() {
if(!ValidateForm()) {
document.getElementById("errorBox").innerHTML = "Please check that you correctly answered the question";
return false;
} else {
document.getElementById("errorBox").innerHTML = "";
return true
}
}
// will check the checkbox to see if checked,
// the "console.log" is there just because of previous problems, don't mind it
function ValidateForm() {
var k = document.getElementsByName('Knowledge');
for (var l = 0; l<k.length; l++) {
if (k[l].checked) {
console.log(k[l])
return true;
}
}
}
// this was supposed to be the code to do the following:
// if the checkbox is checked, it would check for textarea
// if the textarea is there, check if it has any content
// if not, return false ---> sends message from the main function
var k = document.getElementsByName('Knowledge');
for(var i = 0; i<k.length; i++) {
if (k[6].checked) {
}
}
<form id="frmForm" name="frmForm" action="#" method="post" onsubmit="return Validation()">
<div class="row" style="margin-top: 20px;">
<div class="col-sm-12">
<div class="form-group">
<p>
<b>3. This is a question, Lorem ipsum dolor sit amet?</b>
</p>
<p style="margin-left: 16px;">
(please choose one or more answers to continue)
</p>
<div style="margin-left: 35px;">
<input type="checkbox" id="Knowledge1" name="Knowledge" value="physical" >
<label for="Knowledge1" style="font-weight:normal">answer 1<br>
<input type="checkbox" id="Knowledge2" name="Knowledge" value="music" >
<label for="Knowledge2" style="font-weight:normal">answer 2<br>
<input type="checkbox" id="Knowledge3" name="Knowledge" value="nature" >
<label for="Knowledge3" style="font-weight:normal">answer 3</label><br>
<input type="checkbox" id="Knowledge4" name="Knowledge" value="society" >
<label for="Knowledge4" style="font-weight:normal">answer 4</label><br>
<input type="checkbox" id="Knowledge5" name="Knowledge" value="other" >
<label for="Knowledge5" style="font-weight:normal">answer 5 + explain
<input type="text" placeholder=" . . ." border=""/></label><br>
</div>
</div>
</div>
</div>
<div class="row" style="margin-top: 50px">
<div class="col-sm-3 col-sm-offset-3">
<div class="form-group">
<button type="submit" id="Submit" name="Submit" class="btn btn-default">! ANSWER !</button>
</div>
</div>
</div>
<div id="errorBox" style="margin-bottom:50px; color: red"></div>
</form>

If you want to keep it generic, add a data attribute to the checkboxes that required additional text and make your validation check that data attribute:
<input type="checkbox" id="Knowledge5" name="Knowledge" value="other" data-explain="Knowledge5text">
<input id="Knowledge5text" type="text" placeholder="..." border=""/>
.
if (checkboxElement.dataset.explain) {
console.log('answer requires an explanation');
var textFieldElement = document.getElementById(k[i].dataset.explain);
if (!textFieldElement .value) {
console.log('no answer found:', textFieldElement .value);
return false;
}
}
Here is the complete example. Side note: Avoid single-character variable names for anything but loop variables, it makes understanding code more difficult
// main function for checking the validation of answer
function Validation() {
if(!ValidateForm()) {
document.getElementById("errorBox").innerHTML = "Please check that you correctly answered the question";
return false;
} else {
document.getElementById("errorBox").innerHTML = "";
return true
}
}
// will check the checkbox to see if checked,
// the "console.log" is there just because of previous problems, don't mind it
function ValidateForm() {
var k = document.getElementsByName('Knowledge');
for (var i = 0; i < k.length; i++) {
if (k[i].checked) {
if (k[i].dataset.explain) {
console.log('answer requires an explanation');
var textField = document.getElementById(k[i].dataset.explain);
if (!textField.value) {
console.log('no answer found:', textField.value);
return false;
}
}
return true;
}
}
}
<form id="frmForm" name="frmForm" action="#" method="post" onsubmit="return Validation()">
<div class="row" style="margin-top: 20px;">
<div class="col-sm-12">
<div class="form-group">
<p>
<b>3. This is a question, Lorem ipsum dolor sit amet?</b>
</p>
<p style="margin-left: 16px;">
(please choose one or more answers to continue)
</p>
<div style="margin-left: 35px;">
<input type="checkbox" id="Knowledge1" name="Knowledge" value="physical" >
<label for="Knowledge1" style="font-weight:normal">answer 1<br>
<input type="checkbox" id="Knowledge2" name="Knowledge" value="music" >
<label for="Knowledge2" style="font-weight:normal">answer 2<br>
<input type="checkbox" id="Knowledge3" name="Knowledge" value="nature" >
<label for="Knowledge3" style="font-weight:normal">answer 3</label><br>
<input type="checkbox" id="Knowledge4" name="Knowledge" value="society" >
<label for="Knowledge4" style="font-weight:normal">answer 4</label><br>
<input type="checkbox" id="Knowledge5" name="Knowledge" value="other" data-explain="Knowledge5text">
<label for="Knowledge5" style="font-weight:normal">answer 5 + explain
<input id="Knowledge5text" type="text" placeholder=" . . ." border=""/></label><br>
</div>
</div>
</div>
</div>
<div class="row" style="margin-top: 50px">
<div class="col-sm-3 col-sm-offset-3">
<div class="form-group">
<button type="submit" id="Submit" name="Submit" class="btn btn-default">! ANSWER !</button>
</div>
</div>
</div>
<div id="errorBox" style="margin-bottom:50px; color: red"></div>
</form>

Related

Trying to disable button if text hasn’t being input and one of three check box hasn’t been checked in JavaScript

I am trying to disable a button that requires both an input of text being typed and one of three checkboxes being checked. The text is a user name and the checkbox is a difficulty of either easy, medium, or hard. Currently, my function only works if one of the requirements is met. So if the text has been inputted the button is enabled and the same with the checkboxes.
startButton.addEventListener('click', startQuiz);
function disableButton() {
if (document.getElementById("username").value === "") {
document.getElementById("start-btn").disabled = true;
}
if (document.getElementsByName("difficulty").checked) {
document.getElementById("start-btn").disabled = true;
}
else {
document.getElementById("start-btn").disabled = false;
}
}
<div>
<label for="username">Enter your Username</label>
<input type="text" name="username" id="username" onkeyup="disableButton()" placeholder="Enter Username">
</div>
<div id="difficulty" class="center">
<div>
<input type="radio" name="difficulty" id="easy-diff" onclick="disableButton()">
<label for="easy-diff">Easy</label>
</div>
<div>
<input type="radio" name="difficulty" id="medium-diff" onclick="disableButton()">
<label for="medium-diff">Medium</label>
</div>
<div>
<input type="radio" name="difficulty" id="hard-diff" onclick="disableButton()">
<label for="hard-diff">Hard</label>
</div>
</div>
<button id="start-btn" type="submit" class="btn" disabled>Start</button>
every time the value changed, check both input
let diffChecked = false;
let startButton = document.querySelector('#start-btn');
let username = document.querySelector('#username');
let difficulty = document.querySelectorAll('[name="difficulty"]');
username.addEventListener('input', function() {
validateInput();
})
difficulty.forEach(function(item) {
item.addEventListener('click', function() {
diffChecked = true;
validateInput();
})
})
function validateInput() {
if (username.value && diffChecked) {
startButton.disabled = false;
} else {
startButton.disabled = true
}
}
<div>
<label for="username">Enter your Username</label>
<input type="text" name="username" id="username" placeholder="Enter Username">
</div>
<div id="difficulty" class="center">
<div>
<input type="radio" name="difficulty" id="easy-diff">
<label for="easy-diff">Easy</label>
</div>
<div>
<input type="radio" name="difficulty" id="medium-diff">
<label for="medium-diff">Medium</label>
</div>
<div>
<input type="radio" name="difficulty" id="hard-diff">
<label for="hard-diff">Hard</label>
</div>
</div>
<button id="start-btn" type="submit" class="btn" disabled>Start</button>
Instead of a div you must use the Semantic HTML form, that will do the job for you without even writing javascript code.
<form id="difficulty" class="center">
<div>
<input type="radio" name="difficulty" id="easy-diff" required>
<label for="easy-diff">Easy</label>
</div>
<div>
<input type="radio" name="difficulty" id="medium-diff" required>
<label for="medium-diff">Medium</label>
</div>
<div>
<input type="radio" name="difficulty" id="hard-diff" required>
<label for="hard-diff">Hard</label>
</div>
<button type="submit">Enviar</button>
</form>
Inside a form tag, the submit button only works with all required inputs does not have an undefined value.
And you may call your function startQuiz as an action, if you want.
The action attribute specifies where to send the form-data when a form is submitted.
<form id="difficulty" class="center" action="startQuiz()">

Handling multiple form submit

I'm a newbie learning new stuff. I'm trying to handle two forms, but can't figure out how to handle the second form differently. It uses 1st forms handle no matter what. Here's the code:
<div class="body questionnaire-container">
<div class="content">
<h2 id="questionNumero"></h2>
<p id="question"></p>
<form class="form" id="question-form">
<div>
<input type="radio" name="question" id="answerA" value="A">
<label class="answerA"></label>
</div>
<div>
<input type="radio" name="question" id="answerB" value="B">
<label class="answerB"></label>
</div>
<div>
<input type="radio" name="question" id="answerC" value="C">
<label class="answerC"></label>
</div>
<div>
<input type="radio" name="question" id="answerD" value="D">
<label class="answerD"></label>
</div>
<button type="submit" id="submit" class="submit">Next</button>
</form>
</div>
<div class="barre-progression">
<h2>Progrès</h2>
<progress class="progression" value="0" max="10">
</div>
</div>
<div class="body weaponquestionnaire-container">
<div class="content">
<h2 id="questionNumero"></h2>
<p id="question"></p>
<form class="form" id="questionweap-form">
<div>
<input type="radio" name="question" id="answerA" value="A">
<label class="answerA"></label>
</div>
<div>
<input type="radio" name="question" id="answerB" value="B">
<label class="answerB"></label>
</div>
<div>
<input type="radio" name="question" id="answerC" value="C">
<label class="answerC"></label>
</div>
<div>
<input type="radio" name="question" id="answerD" value="D">
<label class="answerD"></label>
</div>
<button type="submit" id="chuj" class="questionweap-form">Next</button>
</form>
</div>
<div class="barre-progression">
<h2>Progrès</h2>
<progress class="progression" value="0" max="10">
</div>
</div>
// Handle Form Submits
$("#question-form").submit(function (e) {
e.preventDefault();
alert( "It's broken again!" );
if (questionNumber != nbQuestionToAnswer) {
//question 1 to 9: pushing answer in array
closeAll();
userAnswer.push($('input[name="question"]:checked').val());
questionNumber++;
openQuestionnaire();
} else {
// question 10: comparing arrays and sending number of good answers
userAnswer.push($('input[name="question"]:checked').val());
var nbGoodAnswer = 0;
for (i = 0; i < nbQuestionToAnswer; i++) {
if (userAnswer[i] == goodAnswer[i]) {
nbGoodAnswer++;
}
}
closeAll();
if (nbGoodAnswer >= nbAnswerNeeded) {
openResultGood();
} else {
openResultBad();
}
}
return false;
});
$("#questionweap-form").submit(function (e) {
e.preventDefault();
alert( "It worked, finally." );
if (questionNumber != nbQuestionToAnswer) {
//question 1 to 9: pushing answer in array
closeAll();
userAnswer.push($('input[name="question"]:checked').val());
questionNumber++;
openQuestionnaireWeapon();
} else {
// question 10: comparing arrays and sending number of good answers
userAnswer.push($('input[name="question"]:checked').val());
var nbGoodAnswer = 0;
for (i = 0; i < nbQuestionToAnswer; i++) {
if (userAnswer[i] == goodAnswer[i]) {
nbGoodAnswer++;
}
}
closeAll();
if (nbGoodAnswer >= nbAnswerNeeded) {
openResultGood();
} else {
openResultBad();
}
}
return false;
});
It keeps submitting the "question-form", even when trying to submit "questionweap-form"
I've looked for any tips for hours any couldn't find anything, so any help would be appreciated!

How to restrict multiple inputs with checkbox?

I have a form with 6 inputs, the inputs are grouped by two and I enable/disable them using a checkbox like in this fiddle.
How do I restrict the search? For example, I need to let the user know they need to fill both inputs if they select the check1 checkbox, or if they selected checkboxes check1 and check2 that they need to fill all 4 inputs. Right now I have this:
if( (check1.checked || check2.checked || check3.checked) ){
if($scope.tolPositivaDim1 == '' || $scope.tolNegativaDim1 == '' ||
$scope.tolPositivaDim2 == '' || $scope.tolNegativaDim2 == '' ||
$scope.tolPositivaDim3 == '' || $scope.tolNegativaDim3 == ''){
console.log(''Need to fill all inputs);
} else
console.log('Something');
} else {
console.log('Need to check at least one');
}
But with this it doesn't let me search until I have filled the six inputs. Is there a way to do this without having to do an if for each specific case?:
if(check1.checked) || if(check1.checked && check2.checked).....
You could improve the code to work with any number of such checkbox & double input combinations. Then define a handler for the form's submit event, and check that inputs are not empty when they are not disabled. If one of those is empty return false, so to cancel the submission.
Some of the code below uses ES6 features. If you cannot use those, it should not be hard to translate the idea to ES5:
var checks = [...document.querySelectorAll('[id^=checkDimension]')],
positivaDims = [...document.querySelectorAll('[id^=tolPositivaDim')],
negativaDims = [...document.querySelectorAll('[id^=tolNegativaDim')];
checks.forEach(function (check, i) {
check.onchange = function() {
positivaDims[i].disabled = !checks[i].checked;
negativaDims[i].disabled = !checks[i].checked;
}.bind(i);
// call the above code also on page load, so to initialise the disabled
// properties correctly:
check.onchange();
});
document.forms[0].onsubmit = function (e) {
if (positivaDims.concat(negativaDims).some(function (input) {
// if for any non-disabled input the value is blank...
return !input.disabled && input.value == '';
})) {
alert('All inputs are required.');
// cancel form submission (either of the two methods below will do it)
e.preventDefault();
return false;
}
}
<form class="" method="post">
<div class="form-group col-sm-12">
<div class="col-sm-4">
<div class="checkbox">
<label><input type="checkbox" id="checkDimension1"> Dimension 1</label>
</div>
</div>
<div class="col-sm-4">
<input type="text" class="form-control" id="tolPositivaDim1" placeholder="0.03" ng-model="tolPositivaDim1">
</div>
<div class="col-sm-4">
<input type="text" class="form-control" id="tolNegativaDim1" placeholder="0.03" ng-model="tolNegativaDim1">
</div>
</div>
<div class="form-group col-sm-12">
<div class="col-sm-4">
<div class="checkbox">
<label><input type="checkbox" id="checkDimension2"> Dimension 2</label>
</div>
</div>
<div class="col-sm-4">
<input type="text" class="form-control" id="tolPositivaDim2" placeholder="0.03" ng-model="tolPositivaDim2">
</div>
<div class="col-sm-4">
<input type="text" class="form-control" id="tolNegativaDim2" placeholder="0.03" ng-model="tolNegativaDim2">
</div>
</div>
<div class="form-group col-sm-12">
<div class="col-sm-4">
<div class="checkbox">
<label><input type="checkbox" id="checkDimension3"> Dimension 3</label>
</div>
</div>
<div class="col-sm-4">
<input type="text" class="form-control" id="tolPositivaDim3" placeholder="0.03" ng-model="tolPositivaDim3">
</div>
<div class="col-sm-4">
<input type="text" class="form-control" id="tolNegativaDim3" placeholder="0.03" ng-model="tolNegativaDim3">
</div>
</div>
<button type="submit" class="btn btn-default pull-right" >Search</button>
<button class="btn btn-default pull-right">Cancel</button>
</form>
The same is also available in this fiddle.

Creating Forms in Javascript-Length is undefined

So I feel silly asking this question, but am currently a high school student in Coding that needs help. We're working on a project with the same requirements for all people, so I took some code that worked for my friend to use for a form; however, I keep running in the problem that my 'length is undefined' and therefore, will not do what I want it to. My code is below:
HTML:
What toppings do you like on your ice-cream?
<div class="checkbox">
<label>
<input name="food" type="checkbox" value="Whip Cream">Whip Cream
</label>
</div>
<div class="checkbox">
<label>
<input name="food" type="checkbox" value="Sprinkles">Sprinkles
</label>
</div>
<div class="checkbox">
<label>
<input name="food" type="checkbox" value="Fruit">Fruit
</label>
</div>
<div class="checkbox">
<label>
<input name="food" type="checkbox" value="Hot Fudge/Caramel">Hot Fudge/Caramel
</label>
</div>
<div class="checkbox">
<label>
<input name="food" type="checkbox" value="Other">Other
</label>
</div>
<input name="Submit" type="Submit" value="Submit">
<div id="r">
</div>
Script:
var form = document.forms.example;
//This points to the form called "example" in HTML
form.addEventListener("submit",nameDisplay,false);
function nameDisplay(event) {
event.preventDefault();
var person = {
name: form.username.value,
}
var text = "<p> Mmmm..." + person.name +" sounds yummy!</p>";
document.getElementById("result").innerHTML = text;
}
var l = [];
for(i = 0; i < form.food.length; i++) {
if(form.food[i].checked) {
l.push(form.food[i].value);
}
console.log("loop");
}
console.log(l);
person.food = l;
console.log(person.food);
var text = "<p>You like" + person.food.join(",") + "on your ice-cream.</p>";
document.getElementById("r").innerHTML = text;
NOTE: I have two forms, hence the first part of javascript, but I thought maybe the problem lies within one thing is overriding another and what not or I'm missing something. I am only having problems with the ice-cream one though. Please help! Thanks in advance!
Below is the working version of your code
Issues found:
form tag was missing
There was no username input yet person needed it
The code you added
after your friend's was outside the nameDisplay function
There was no "result" div
Other concerns you may want to review
Is there a need to wrap your input's in divs?
No need for the food variable
I'd love to see the loop replaced with a filter and some
Bro, are you sure im not doing your homework?
var form = document.forms.example; //This points to the form called "example" in HTML
form.addEventListener("submit", nameDisplay, false);
function nameDisplay(event) {
var food = [];
for (i = 0; i < form.food.length; i++) {
if (form.food[i].checked) {
food.push(form.food[i].value);
}
}
var text = "<p>You like " + food.join(",") + " on your ice-cream.</p>";
document.getElementById("r").innerHTML = text;
}
<h3>What would you like on your Ice Cream?</h3>
<form id="example">
<div class="checkbox">
<label>
<input name="food" type="checkbox" value="Whip Cream">Whip Cream
</label>
</div>
<div class="checkbox">
<label>
<input name="food" type="checkbox" value="Sprinkles">Sprinkles
</label>
</div>
<div class="checkbox">
<label>
<input name="food" type="checkbox" value="Fruit">Fruit
</label>
</div>
<div class="checkbox">
<label>
<input name="food" type="checkbox" value="Hot Fudge/Caramel">Hot Fudge/Caramel
</label>
</div>
<div class="checkbox">
<label>
<input name="food" type="checkbox" value="Other">Other
</label>
</div>
<input name="Submit" type="Submit" value="Submit">
<div id="r">
</div>
</form>

Saving checked box value as 0 or 1 in the database from Ajax POST

So I have a few columns in the database which I have configured as TINYINT. I have the same number of check boxes as well on the front end.
Here's my HTML,
<script type="text/x-handlebars" id="project">
<div class="row">
<div class="span6">
<div class="well well-small">
<p style="text-align: center">
You can create a new Project by filling this simple form.
</p>
<p style="text-align: center"> Project Name should be minimum 10 characters & There's no limit on
Project Description.
</p>
</div>
<form class="form-horizontal">
<div class="control-group">
<label class="control-label" for="projectname">Project Name: </label>
<div class="controls">
<input type="text" name="projectname" id="projectname" required
title="Project Name is Required!" pattern="[A-z ]{10,}"
placeholder="Enter Project Name"/>
</div>
</div>
<div class="control-group">
<label class="control-label" for="projectdesc">Project Description:</label>
<div class="controls">
<textarea rows="3" id="projectdesc" name="projectdesc" placeholder="Enter Project Desc"
required="Description Required"></textarea>
</div>
</div>
<div class="control-group">
<label class="control-label">Roles:</label>
<div class="controls">
<label class="checkbox">
<input type="checkbox" name="roles" id="script" value="false"> Script
</label>
<label class="checkbox">
<input type="checkbox" name="roles" id="design" value="false"> Design
</label>
<label class="checkbox">
<input type="checkbox" name="roles" id="writer" value="false"> Writer
</label>
<label class="checkbox">
<input type="checkbox" name="roles" id="storyboard" value="false"> Storyboard
</label>
<label class="checkbox">
<input type="checkbox" name="roles" id="workbook" value="false"> Workbook
</label>
<br>
<button class="btn"
{{action 'createNew'}}>Add Project</button>
</div>
</div>
</form>
</div>
</div>
</script>
And here's what I am doing,
function(event) {
$(":text, input[type='checkbox'], textarea").each(function() {
if ($(this).val() === "") {
alert("Empty Fields!");
event.preventDefault();
} else {
App.Project.createNew();
alert("Project Created");
event.preventDefault();
}
});
}
And the Ajax POST,
dataString = {
'projectname' : $("#projectname").val(),
'projectdesc' : $("#projectdesc").val(),
'script' : $('input.roles[type="checkbox"]:checked', this).val()
};
console.log('check');
$.ajax({
type : "POST",
url : "http://ankur.local/users/createNewProject",
data : dataString,
dataType : "json",
success : function(data) {
console.log('success');
alert('');
}
});
return false;
You can see from my code that I am trying to grab the checked value of the textbox which I want to store in the database as 0 or 1 or True or False perhaps? Moreover I want to have a condition that out of the given checkboxes, at least one should be checked.
'script' : $('input.roles[type="checkbox"]:checked', this).val()
How can I achieve my objective?
Condition for checking at least one checkbox is checked
if($('input[type="checkbox"]:checked').length > 0)
{
//do your work
}else
{
alert("Please check any checkbox");
return false;
}
do this check prior to posting your data.
Get the value for saving in database
//will give the value attribute of selected checkbox
// true/false in this case
var value = $('input[type="checkbox"]:checked').val();
//for getting value in 1 or 0 from the above variable.
var value1 = value ? 1 : 0;
For saving all check box values.
var all_values= "";
$('input[type="checkbox"]').each(function(){
var value = $(this).is(":checked") ;
all_values = all_values + "~" + value ;
});
send the value of all_values to your code, use split to get all the values.

Categories