i am doing a mobile application survey form using phonegap and firebase.
My data from the form is inserted to firebase however it only work for textbox and not radio button. is there something wrong with my codes? This is what shown in firebase.
The following is my code
<form id="testForm">
<b style="font-size: 27px;">Survey Form<p></p></b>
<b class=fs>Name of client:</b> <br><input type="text" name="name" id="name"><br>
<b class=fs>Date: </b><br><input type="date" name="date" id="date"><p></p>
<b class=fs>1)Do you worry? In the past month?</b> <p>
<input type="radio" name="q1" value="0" id="q1"> 0
<input type="radio" name="q1" value="1" id="q1"> 1 <p>
<b class=fs>2) Have you been sad or depressed in the past month?</b> <p>
<input type="radio" name="q2" value="0" id="q2"> 0
<input type="radio" name="q2" value="1" id="q2"> 1 <p>
<input type="submit" class="button" value="Submit">
</form>
<script src="https://www.gstatic.com/firebasejs/4.6.2/firebase.js"></script>
<script>
//reference messages collection
var testRef = firebase.database().ref('test');
// listen for form submit
document.getElementById('testForm').addEventListener('submit',submitForm);
function submitForm(e){
e.preventDefault();
var name = getInputVal('name');
var date = getInputVal('date');
var q1 = getInputVal('q1');
var q2 = getInputVal('q2');
saveMessage(name,date,q1,q2);
}
function getInputVal(id){
return document.getElementById(id).value;
}
function saveMessage(name,date,q1,q2){
var newMessageRef = testRef.push();
newMessageRef.set({
screenby:name,
date:date,
q1:q1,
q2:q2,
});
}
</script>
</body>
</html>
Related
As a user when I submit this form
I want a fetch call for each checkbox that is checked
So that I can load information from the API depending on what the selections are.
Using Materialize framework and jquery or plain javascript is fine. Hard question to explain but on form submit I want to bring up information depending on checkbox ticked. Each checkbox should trigger a fetch call to the specific API which will then append data to the new page such as movies availbe on nexflix or amazon prime
<form id= 'selectionForm' action="#">
<p>
<label>
<input type="checkbox" class="filled-in" name="Nexflix" id="Netflix" />
<span>Netflix</span>
</label>
</p>
<p>
<label>
<input type="checkbox" class="filled-in" name="Prime" id="Prime"/>
<span>Amazon Prime Video</span>
</label>
</p>
</form>
Edit : this snippet fetch every checked element and send a request for each one.
<script lang="js" >
document.getElementById('fetch').addEventListener('click', function (e) {
e.preventDefault();
let checkedElements = document.querySelectorAll('.filled-in:checked');
let outputContainer = document.getElementById('output');
for (let e of checkedElements) {
fetch('https://api.publicapis.org/entries').then((r) => r.json()).then( (d) => {
let outputContent = document.createTextNode('The checked element is : '+e.id+'<br>'+d.entries[0].Description)
outputContainer.appendChild(outputContent)
})
}
})
</script>
<form id= 'selectionForm' action="#">
<p>
<label>
<input type="checkbox" class="filled-in" name="Nexflix" id="Netflix" />
<span>Netflix</span>
</label>
</p>
<p>
<label>
<input type="checkbox" class="filled-in" name="Prime" id="Prime"/>
<span>Amazon Prime Video</span>
</label>
</p>
<input type="button" value="Fetch" id="fetch">
<div id="output"></div>
</form>
This is what you are looking for ? This example get Data from an API and display a field bellow the first checkbox :
<script lang="js" >
document.getElementById('Netflix').addEventListener('click', function (e) {
e.preventDefault();
let outputText = '';
let outputContainer = document.getElementById('output');
fetch('https://api.publicapis.org/entries').then((r) => r.json()).then( (d) => {
let outputContent = document.createTextNode(d.entries[0].Description)
outputContainer.appendChild(outputContent)
})
})
</script>
<form id= 'selectionForm' action="#">
<p>
<label>
<input type="checkbox" class="filled-in" name="Nexflix" id="Netflix" />
<span>Netflix</span>
</label>
<div id="output"></div>
</p>
<p>
<label>
<input type="checkbox" class="filled-in" name="Prime" id="Prime"/>
<span>Amazon Prime Video</span>
</label>
</p>
</form>
I have made a quiz in html with some validation, and the next step I would like to undertake is to score this quiz in javascript. My scoring system is all well and works as intended, but I'd like to prevent the form from posting to result.html IF they score 0 on the quiz. I have managed to display an alert when this happens, but upon pressing OK, the result page loads anyway. (The result page is empty for now). I've tried looking at both window.history.back, as well as preventDefault, but I can't help but to think I am not understanding syntax for one or both of these things. I'd like the alert to show, and then the user stay on the same page. I'd also like to stay within vanilla javascript, as well as avoiding inline stuff. Thanks :)
Here is my quiz form:
<form name="quiz" id="quiz" method="post" action="result.html">
<fieldset>
<legend>Student Details</legend>
<p><label for="firstName">Name: </label>
<input type="text" name="firstName" id="firstName" placeholder="First" maxlength="25" required="required" pattern="^[A-Za-z -]+$" title="Please use only letters/hyphens/spaces." />
<input type="text" name="lastName" id="lastName" placeholder="Last" maxlength="25" required="required" pattern="^[A-Za-z -]+$" title="Please use only letters/hyphens/spaces." /></p>
<p><label for="studentID">Student ID: </label>
<input type="text" name="studentID" id="studentID" placeholder="e.g. s123456789" required="required" pattern="(\w{1}\d{6}(\d{3})?)" title="Please enter either 7 or 10 characters, beginning with the letter 's'." /></p>
</fieldset>
<br/>
<fieldset>
<legend>Question 1</legend>
<p><label for="answer1">In what year was the SSH-1 protocol released?</label><br/><br/>
<input type="text" name="answer1" id="answer1" pattern="[0-9]{1,4}" placeholder="e.g. 2018" required="required" title="Please enter a year with up to 4 digits." /></p>
</fieldset>
<br/>
<fieldset>
<legend>Question 2</legend>
<p><label>Who developed the SSH-1 protocol?</label><br/><br/>
<input type="radio" name="answer2" id="answer2_1" value="wuXian" required="required" /><label for="answer2_1">Wu Xian</label><br/>
<input type="radio" name="answer2" id="answer2_2" value="mohammadHaddad" /><label for="answer2_2">Mohammad Haddad</label><br/>
<input type="radio" name="answer2" id="answer2_3" value="tatuYlonen" /><label for="answer2_3">Tatu Ylönen</label><br/>
<input type="radio" name="answer2" id="answer2_4" value="fredrikJohannsen" /><label for="answer2_4">Fredrik Jöhannsen</label></p>
</fieldset>
<br/>
<fieldset>
<legend>Question 3</legend>
<p><label>Select as many SSH <em>protocols</em> as you see.</label><br/><br/>
<input type="checkbox" name="answer3_1" id="answer3_1" value="ssh2" /><label for="answer3_1">SSH-2</label><br/>
<input type="checkbox" name="answer3_2" id="answer3_2" value="openBSD" /><label for="answer3_2">OpenBSD</label><br/>
<input type="checkbox" name="answer3_3" id="answer3_3" value="ssh1" /><label for="answer3_3">SSH-1</label><br/>
<input type="checkbox" name="answer3_4" id="answer3_4" value="openSSH" /><label for="answer3_4">OpenSSH</label></p>
</fieldset>
<br/>
<fieldset>
<legend>Question 4</legend>
<p><label for="answer4">SSH is a: </label><br/><br/>
<select name="answer4" id="answer4" form="quiz" required="required">
<option value="">Please select...</option>
<option value="applicationLayer">Application layer protocol</option>
<option value="transportLayer">Transport layer protocol</option>
<option value="internetLayer">Internet layer protocol</option>
<option value="linkLayer">Link layer protocol</option>
</select></p>
</fieldset>
<br/>
<fieldset>
<legend>Question 5</legend>
<p><label for="answer5">Click on the flag of the country where the SSH-1 protocol was first developed, and then click Submit.</label><br/><br/>
<img src="images/flags.jpg" width="400" height="400" alt="Scandinavian Flags" usemap="#flagsMap" />
<input type="text" name="answer5" id="answer5" value="" readonly="readonly" required="required" /><br/><br/>
<map name="flagsMap">
<area shape="rect" coords="0,0,200,200" alt="Finland" href="#bottom" onClick="document.forms['quiz'].answer5.value='Finland'"/>
<area shape="rect" coords="200,0,400,200" alt="Iceland" href="#bottom" onClick="document.forms['quiz'].answer5.value='Iceland'"/>
<area shape="rect" coords="0,200,200,400" alt="Norway" href="#bottom" onClick="document.forms['quiz'].answer5.value='Norway'"/>
<area shape="rect" coords="200,200,400,400" alt="Sweden" href="#bottom" onClick="document.forms['quiz'].answer5.value='Sweden'"/>
</map></p>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<input type="submit" />
</fieldset>
</form>
And here is my javascript:
"use strict";
function goBack() {
window.history.back();
}
function checkScore() {
var score = 0;
var ans1 = document.getElementById("answer1");
if (ans1.value == "1995") {
score = score + 2;
}
var ans2_3 = document.getElementById("answer2_3");
if (ans2_3.checked == true) {
score = score + 2;
}
var ans3_1 = document.getElementById("answer3_1");
var ans3_2 = document.getElementById("answer3_2");
var ans3_3 = document.getElementById("answer3_3");
var ans3_4 = document.getElementById("answer3_4");
if (ans3_1.checked == true && ans3_2.checked == false && ans3_3.checked ==
true && ans3_4.checked == false) {
score = score + 2;
}
var ans4 = document.getElementById("answer4");
if (ans4.value == "applicationLayer") {
score = score + 2;
}
var ans5 = document.getElementById("answer5");
if (ans5.value == "Finland") {
score = score + 2;
}
if (score == 0) {
alert("You have attempted to submit this quiz, but you have scored 0/10.
Please reconsider your answers, and try to raise your score.");
goBack;
}
}
function init() {
var quiz = document.getElementById("quiz");
quiz.onsubmit = checkScore;
}
window.onload = init;
Two places to change:
The checkscore function itself has to return false when fails:
if (score==0) {
alert('error');
return false;
}
Then the form submit itself needs to return the return value of the function:
quiz.onsubmit=function(){
return checkscore();
}
I know you are trying to avoid writing inline code, but if the above changes were made inline, it's easier to see the difference:
<form ... onsubmit="checkscore();"> <-- this doesn't work
<form ... onsubmit="return checkscore();"> <-- this works
When you do it like this, your function is called when the user submits the form. At this point, it will complete the function, and then proceed to submit, unless told not to.
If your function returns false, it should cancel the submitting currently happening, and keep the user on the page.
Try changing:
if (score == 0) {
alert("You have attempted to submit this quiz, but you have scored 0/10. Please reconsider your answers, and try to raise your score.");
goBack;
}
Into:
if (score == 0) {
alert("You have attempted to submit this quiz, but you have scored 0/10. Please reconsider your answers, and try to raise your score.");
return false;
}
How do you make it calculate using JavaScript/jQuery based on condition:
on radio button 'change' event.
if user clicks "Yes" or "N/A", the value of text boxes with default values next to it will be added and reflected in Total
HTML:
<form>
<fieldset>
<input type="radio" name="remark[]" value="Yes" class="answer">Yes
<input type="radio" name="remark[]" value="No" class="answer">No
<input type="radio" name="remark[]" class="answer">N/A
<input type="text" name="point1" class="score" value="3">
</fieldset>
<fieldset>
<input type="radio" name="remark[]" value="Yes" class="answer">Yes
<input type="radio" name="remark[]" value="No" class="answer">No
<input type="radio" name="remark[]" class="answer">N/A
<input type="text" name="point2" class="score" value="2">
</fieldset>
Total<input type="text" name="total" class="result">
</form>
Vanilla Javascript
Note: these scripts associate with forms that have the class name calc
This script will associate with the form, so if you have multiple instances each form will calculate separately.
Basically for each form select all input's with a value of 'Yes' which are checked, then find the score for that field set and add it to the total
(Demo)
(function(){
"use strict";
function calculate() {
var forms = document.querySelectorAll('.calc'), form, i;
for (i = 0; form = forms[i]; i++) {
var total = 0;
var inputs = form.querySelectorAll('input[value="Yes"]:checked'), input, x;
for (x = 0; input = inputs[x]; x++) {
total += parseFloat(input.parentElement.lastElementChild.value);
}
form.lastElementChild.value = total;
}
}
calculate();
var inputs = document.querySelectorAll('.calc input'), input, x;
for(x = 0; input = inputs[x]; x++) {
input.onchange = calculate;
}
})();
jQuery
If you would like to use jQuery, this is the same script converted to jQuery
(Demo)
(function(){
"use strict";
function calculate() {
$('.calc').each(function(){
var total = 0;
$('input[value="Yes"]:checked', this).each(function(){
total += parseFloat($('input.score', this.parentElement).val());
});
$('input.result', this).val(total);
});
}
calculate();
$('.calc input').on('change', calculate);
})();
Not sure if I understand correctly, but first you'll need a few changes in your markup, radio groups should have different name so it'll be like remark[0] for first group and remark[1] for the second and so on. The "N/A" radios don't seem to have a value so I've added value="NA" to them. So your HTML will look like:
<form>
<fieldset>
<input type="radio" name="remark[0]" value="Yes" class="answer" />Yes
<input type="radio" name="remark[0]" value="No" class="answer" />No
<input type="radio" name="remark[0]" value="NA" class="answer" />N/A
<input type="text" name="point1" class="score" value="3" />
</fieldset>
<fieldset>
<input type="radio" name="remark[1]" value="Yes" class="answer" />Yes
<input type="radio" name="remark[1]" value="No" class="answer" />No
<input type="radio" name="remark[1]" value="NA" class="answer" />N/A
<input type="text" name="point2" class="score" value="2" />
</fieldset>Total
<input type="text" name="total" class="result" />
</form>
Then we just listen to radio's onchange and if Yes or N/A is selected for each group, we have it's value to the total. I used parseInt on values since they're string and it seemed the values were supposed to work as numbers. (2+3 should be 5 and not 23).
$('form input[type=radio]').on('change', function() {
var total = 0;
$('form fieldset').each(function(i) {
var point = parseInt($(this).find('input[type=text]').val());
var val = $(this).children('[name="remark[' + i + ']"]:checked').val();
if(val == "Yes" || val == "NA")
total += point;
});
$('input[name="total"]').val(total);
});
jsfiddle DEMO
I have a code like this and I want to compare in a loop the attribute values of name with user entered input stored in variable "user". How can I do this?
<form>
<input type="radio" name="two">
<input type="radio" name="three">
<input type="radio" name="four">
<input type="radio" name="five">
<input type="radio" name="six">
</form>
See this answer for an example of how to loop through radio buttons in native javascript, quoted here for convenience:
<html>
<head>
<script>
var userChoice;
var setUserChoice = function(event) {
event.preventDefault();
var choices = event.target.userChoice;
for (var i =0; i < choices.length; i++) {
if (choices[i].checked) {
userChoice = choices[i].value;
}
}
event.target.choice.value = userChoice;
}
window.onload = function() {
var form = document.getElementById('userInput');
form.addEventListener('submit', setUserChoice, false);
};
</script>
</head>
<body>
<form id="userInput">
<input type="radio" name="userChoice" id="userChoice_rock" value="rock">Rock</input> </br>
<input type="radio" name="userChoice" id="userChoice_paper" value="paper">Paper</input> </br>
<input type="radio" name="userChoice" id="userChoice_scissors"value="scissors">Scissors</input> </br>
<input type="radio" name="userChoice" id="userChoice_lizard" value="lizard">Lizard</input> </br>
<input type="radio" name="userChoice" id="userChoice_spock" value="spock">Spock</input> </br>
<input type="submit" value="Enter" /></br>
<output name="choice"></output>
</form>
</body>
</html>
You can compare tha values like in this fiddle: http://jsfiddle.net/5wd8p/
HTML
<form action="demo.html" id="myForm">
<form>
<input type="radio" name="two">
<input type="radio" name="three">
<input type="radio" name="four">
<input type="radio" name="five">
<input type="radio" name="six">
</form>
<input type="submit" value="Submit">
</form>
JQuery
$(function () {
// Handler for .ready() called.
var user = "three"; //default value: depends on youur code..
//Loop through each radio element of the DOM
$("input[type=radio]").each(function(){
//Compare values of the "name" attribute and the user var
if (user == $(this).attr("name")){
alert("Same: " + $(this).attr("name"));
}else{
alert("Different: " + $(this).attr("name"));
}
});
});
try this:
document.getElementsByName(user)[0]
Note: I am just learning javascript. So please no jQuery answers yet. I'll get there.
I have 7 forms, all with groups of radio buttons, that appear one-by-one as one button of each form is clicked. Works fine. But by the time I'm done, I may have dozens of forms. There has to be a better way to get the value of a clicked button that creating a getValue for each form. Here's what I've done that works:
<script>
function initdisplay() {
document.getElementById("painLocation").style.display="block";
document.getElementById("painSystem").style.display="none";
document.getElementById("painTemporPatt").style.display="none";
document.getElementById("painIntensDur").style.display="none";
document.getElementById("painEtiology").style.display="none";
document.getElementById("painKav").style.display="none";
}
window.onload = initdisplay;
var painLocationValue = 0;
var painSystemValue = 0;
var painTemporPattValue = 0;
var painIntesDurValue = 0;
var painEtiologyValue = 0;
var painKavValue = 0;
function getPainLocationValue() {
var radioButtons = document.getElementsByName("location");
for (var i = 0; i < radioButtons.length; i++) {
if (radioButtons[i].checked) {
painLocationValue = radioButtons[i].value;
document.getElementById("painLocation").style.display="none";
document.getElementById("painSystem").style.display="block";
alert(painLocationValue);
}
}
}
// ... other similar methods here
function getPainKavValue() {
var radioButtons = document.getElementsByName("kav");
for (var i = 0; i < radioButtons.length; i++) {
if (radioButtons[i].checked) {
painKavValue = radioButtons[i].value;
document.getElementById("painKav").style.display="none";
alert(radioButtons[i].value);
}
}
}
</script>
</head>
Then the HTML looks like this:
<body>
<form id="painLocation" action="">
<p class="formPainCode">Q1: What is the location of your ailment?</p>
<input type="radio" name="location" value="000" onclick="getPainLocationValue()"> Head, Face, Mouth<br><br>
<input type="radio" name="location" value="100" onclick="getPainLocationValue()"> Cervical (neck) Region<br><br>
<input type="radio" name="location" value="200" onclick="getPainLocationValue()"> Upper Shoulder and Upper Limbs<br><br>
<input type="radio" name="location" value="300" onclick="getPainLocationValue()"> Thoracic (chest) Region<br><br>
<input type="radio" name="location" value="400" onclick="getPainLocationValue()"> Abdominal Region<br><br>
<input type="radio" name="location" value="500" onclick="getPainLocationValue()"> Lower Back, Lumbar Spine, Sacrum, Coccyx<br><br>
<input type="radio" name="location" value="600" onclick="getPainLocationValue()"> Lower Limbs<br><br>
<input type="radio" name="location" value="700" onclick="getPainLocationValue()"> Pelvic Region<br><br>
<input type="radio" name="location" value="800" onclick="getPainLocationValue()"> Anal, Perineal, Genital Region<br><br>
<input type="radio" name="location" value="900" onclick="getPainLocationValue()"> More than one location<br><br>
</form>
...
<form id="painKav" action="">
<p class="formPainCode">Q11: On which side of your body is your ailment?</p>
<input type="radio" name="kav" value="R" onclick="getPainKavValue()"> Right<br><br>
<input type="radio" name="kav" value="L" onclick="getPainKavValue()"> Left<br><br>
<input type="radio" name="kav" value="C" onclick="getPainKavValue()"> Center<br><br>
<input type="radio" name="kav" value="M" onclick="getPainKavValue()"> More than one side<br><br>
</form>
</body>
</html>
After another couple of frustrating hours, I dropped my "no jQuery" condition. The rest was simple. I used the following code to detect a click, and get the value of the button clicked. And since I expected some of my forms to include input types other than radio buttons, I changed that as well. At this point, the jQuery looks like this:
<script>
$(document).ready(function () {
$("input").click(function() {
var painCode = $(this).val();
alert("The painCode for this person is " + painCode);
});//end click function
}); //end document ready
</script>
I cleaned up the html. A typical form now looks like this:
<div id="painIntensDur">
<form class="painCodeForm" action="">
<p class="formPainCode">Q4: If you experience pain from your ailment, which of the following best describes its intensity and duration? </p>
<input type="radio" name="intensdur" value=".1" > Mild and less than 1 month<br><br>
<input type="radio" name="intensdur" value=".8" > Mild and 1 to 6 months<br><br>
<input type="radio" name="intensdur" value=".9" > Mild and more than 6 months<br><br>
<input type="radio" name="intensdur" value=".4" > Medium and less than 1 month<br><br>
<input type="radio" name="intensdur" value=".2" > Medium and 1 to 6 months<br><br>
<input type="radio" name="intensdur" value=".3" > Medium and more than 6 months<br><br>
<input type="radio" name="intensdur" value=".7" > Severe and less than 1 month<br><br>
<input type="radio" name="intensdur" value=".5" > Severe and 1 to 6 months<br><br>
<input type="radio" name="intensdur" value=".6" > Severe and more than 6 months<br><br>
<input type="radio" name="intensdur" value=".0" > Not sure<br><br>
</form>
</div>
Thanks again to the excellent advice. I'm sure it will come in handy later.