Checkboxs leading to a fetch call to produce data - javascript

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>

Related

Use javascript with POST method

sorry for that, but I need your help on something :
I need to get my values in javascript, as it was filled in my form, and I have no clue how to do it, as whenever I tried to search, it was made for people with at least some understanding of javascript. I have none, but tried my best, the results of my efforts are here :
function validateForm() {
var x = form.('form').elements["sexe"];
if (x == null) {
alert("Un sexe doit être sélectionné");
return false;
}
}
I need to get it done by POST method, as get isn't allowed :
<form action="Monformulairedereferencement." method="post" id="sexe" name="form">
<div id="BlueBorder1">
sexe
<input type="radio" id="Homme" name="sexe" value="Homme" aria-checked="true">
<label for="Homme">Homme</label>
<input type="radio" id="Femme" name="sexe" value="Femme" aria-checked="true">
<label for="Femme">Femme</label>
<input type="radio" id="Autre" name="sexe" value="Autre" aria-checked="true">
<label for="Autre">Autre</label>
</div>
<div>
<label for="civilite">civilite</label>
<select name="civilite" id="civilite">
<option value="M.">M.</option>
<option value="Mme.">Mme.</option>
</select>
</div>
<div>
<label for="nom">nom</label>
<input type="text" id="nom" name="nom" minlength="2">
</div>
<div id="BlueBorder2">
<label for="email">email</label>
<input type="email" id="email">
</div>
<div>
<label for="telephone">telephone</label>
<input type="tel" id="telephone" name="telephone">
</div>
<div>
<label for="website">website</label>
<input type="url" name="website" id="website">
</div>
<div id="BlueBorder3">
<label for="datedenaissance">date de naissance</label>
<input type="date" id="datedenaissance" name="date de naissance">
</div>
<div>
hobbies
<input type="checkbox" id="Jeuxvideo" name="hobbies">
<label for="Jeuxvideo">Jeux video</label>
<input type="checkbox" id="Cinema" name="hobbies">
<label for="Cinema">Cinema</label>
<input type="checkbox" id="Lecture" name="hobbies">
<label for="Lecture">Lecture</label>
<input type="checkbox" id="Sport" name="hobbies">
<label for="Sport">Sport</label>
<input type="checkbox" id="Informatique" name="hobbies">
<label for="Informatique">Informatique</label>
</div>
<input id="token" name="token" type="hidden" value="my first website">
<div>
<label for="validation">validation</label>
<input type="submit" value="Envoyer le formulaire" id="validation">
If you have any clue of what isn't working or anything, then I'll gladly accept it. My only goal is to improve and I'm currently very bad.
Have a nice day and thanks for passing by :)
To get a value of a text input in JS, you need to get this input then get its value.
So for example: <input type="text" id="nom" name="nom" minlength="2">
to get this input value in JS, you have to follow 2 steps:
Assign the input element to variable -> let nom = document.getElementById('nom');
Get the value of this input element -> let nomValue = nom.value;
The previous approach can be applied to any text input (text, password, email, ...), textarea, & select menu
For checkboxes or radio buttons, you need to check if they are checked or not, for example: <input type="radio" id="Homme" name="sexe" value="Homme" > to check this, follow 2 steps:
Assign checkbox or radio button to a variable -> let Homme = document.getElementById('Homme');
Check if this checkbox or radio button is checked -> if (Homme.checked) {console.log('Checked')} else {console.log('Checked')}
For simple validation approach for your code, follow this snippet:
<!-- HTML Form -->
<form action="x.php" method="post" id="sexe" name="form">
<input type="text" id="nom" name="nom" minlength="2">
<input type="radio" id="Homme" name="sexe" value="Homme">
<input type="submit" value='Send' >
</form>
<!-- Validation Script -->
<script>
// Get Form Itself
let myForm = document.getElementById('sexe');
// Add Event To Form On Submit, Trigger The Validation Funcntion
myForm.addEventListener('submit', validateForm)
// Validate Form Function
function validateForm(e) {
// Get All Inputs In Your Form
let nom = document.getElementById('nom'); // Text Input
let Homme = document.getElementById('Homme'); // Radio Input
// Check Text Input Value If Not Empty
if(nom.value === '') {
// Prevent Form Submition
e.preventDefault();
// Alert Error Message
alert('Name Can Not Be Empty');
}
// Check If Radio Button Not Checked
else if (!Homme.checked) {
// Prevent Form Submition
e.preventDefault();
// Alert Error Message
alert('Radio Button Is Required');
}
// If The Previous Two Validation Steps Is Done And No Errors, The Form Will Be Sent
}
</script>
In my view, the easiest way to grab the value from the form is to use addEventListners with Submit event. It looks likes an element.addEventListner('submit',function);
var forms = document.getElementsByTagName('form'); //we have selected whole form
function formSubmitted(){
const emails = document.getElementsById('email');//select the email section
let emailValue = emails.value // it will give you the value of email after submitting
}
forms.addEventListner('submit',formSubmitted);//eventlistern which run after submiting the data in form

How to assign input radio value to a textarea content?

I have this form:
<form>
<input type="radio" id="option-1" name="name" value="Hello! I would like to talk to John"><label for="option-1">John</label>
<input type="radio" id="option-2" name="name" value="Hello! I would like to talk to Maria"><label for="option-2">Maria</label>
<input type="radio" id="option-3" name="name" value="Hello! I would like to talk to Kennedy"><label for="option-3">Kennedy</label>
<input type="radio" id="option-4" name="name" value="Hello! I would like to talk to Adam"><label for="option-4">Adam</label>
</form>
And I have this other form with an textarea:
<form>
<textarea id="textarea-field" placeholder='Type your message here...' required/>
</form>
I would like to know if there is any simple way to assign the value of the chosen input inside the textarea content right when user click one of these input.
A more feasible and easiest way would be do this way by making sure you assign an id to your form which will ensure that you are only selecting Input[type=radio] from that form and not every input on your page.
Also use textContent to assign a value to your textArea. Using innerHTML is not recommended.
We need to use forEach function to loop through all the input which we will find using querySelectorAll function (which returns all nodes list) and then use we can addEventListener to make sure that we listen to change events on your input and assign the value of the checked radio button to your textArea
Live Demo:
//get all radio buttons
let getRadios = document.querySelectorAll('#myForm > input[type="radio"]');
//get text area
let getTextArea = document.querySelector('#textarea-field');
//Loop through the radio button
getRadios.forEach(function(radio) {
radio.addEventListener('change', function() {
getTextArea.textContent = this.value //assign value to textArea
})
})
<form id="myForm">
<input type="radio" id="option-1" name="name" value="Hello! I would like to talk to John"><label for="option-1">John</label>
<input type="radio" id="option-2" name="name" value="Hello! I would like to talk to Maria"><label for="option-2">Maria</label>
<input type="radio" id="option-3" name="name" value="Hello! I would like to talk to Kennedy"><label for="option-3">Kennedy</label>
<input type="radio" id="option-4" name="name" value="Hello! I would like to talk to Adam"><label for="option-4">Adam</label>
<br>
<br>
<textarea id="textarea-field" placeholder='Type your message here...' required>
</textarea>
</form>
If you give each of your input a class purely for this script below it should work.
<script>
// GIVE EACH OF YOUR INPUTS A CLASS OF .input
// THEN ADD THIS SCRIPT
$(document).ready(function(){
$('.input').click(function(e) {
var text = $( this ).val();
$('#textarea-field').val( text );
});
});
</script>
You can do it this way
const radios = document.querySelectorAll('input');
const textarea = document.querySelector('#textarea-field');
radios.forEach(radio => {
radio.addEventListener('change', ({
target
}) => textarea.innerHTML = target.value);
});
<form>
<input type="radio" id="option-1" name="name" value="Hello! I would like to talk to John"><label for="option-1">John</label>
<input type="radio" id="option-2" name="name" value="Hello! I would like to talk to Maria"><label for="option-2">Maria</label>
<input type="radio" id="option-3" name="name" value="Hello! I would like to talk to Kennedy"><label for="option-3">Kennedy</label>
<input type="radio" id="option-4" name="name" value="Hello! I would like to talk to Adam"><label for="option-4">Adam</label>
<textarea id="textarea-field" placeholder='Type your message here...' required></textarea>
</form>
Add a Custom Class to input where you want to put Radio Button
The Code below Gets the Value of clicked input radio button and sets in the TextArea Field.
$('.radiobuttoninput').click(function() {
$('#textarea-field').val($(this).val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input class="radiobuttoninput" type="radio" id="option-1" name="name" value="Hello! I would like to talk to John"><label for="option-1">John</label>
<input class="radiobuttoninput" type="radio" id="option-2" name="name" value="Hello! I would like to talk to Maria"><label for="option-2">Maria</label>
<input class="radiobuttoninput" type="radio" id="option-3" name="name" value="Hello! I would like to talk to Kennedy"><label for="option-3">Kennedy</label>
<input class="radiobuttoninput" type="radio" id="option-4" name="name" value="Hello! I would like to talk to Adam"><label for="option-4">Adam</label>
</form>
<br>
<form>
<textarea id="textarea-field" placeholder='Type your message here...' required> </textarea>
</form>
If you don't want to use any libraries then you can also use vanilla to do this. Nothing to explain here so I will just show you.
HTML file:
<form name="form">
<input type="radio" name="rate" value="1"/>i am 1
<input type="radio" name="rate" value="2"/>i am 2
<input type="radio" name="rate" value="3"/>i am 3
</form>
<textarea value="" id="ta"></textarea>
You don't need id for the form or radio boxes. Just declare a name. That would do the trick.
JavaScript file:
document.form.onclick = function() {
var v = document.form.rate.value;
var t = document.getElementById("ta");
t.value = v;
}
Let me know if it worked.

Mobile application form using phonegap and firebase

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>

Submit form data to Highcharts addPoint method to dynamically update form

I currently have a chart pulling in data from a local JSON file. I now need to submit data via a form to update the chart dynamically. I know Highcharts has an addPoint method which should work, just need some guidance on how to pass my form data to this method.
<form id="add_data">
<p>
<input type="date" name="date" id="human" value="date" />
</p>
<p>
<input type="integer" name="amount" id="amount" value="amount" />
</p>
<p>
<input type="radio" name="request_type" id="human" value="human" />
<label for="human">Human</label>
</p>
<p>
<input type="radio" name="request_type" id="good" value="good" />
<label for="good">Good</label>
</p>
<p>
<input type="radio" name="request_type" id="bad" value="bad" />
<label for="bad">Bad</label>
</p>
<p>
<input type="radio" name="request_type" id="whitelist" value="whitelist" />
<label for="whitelist">Whitelist</label>
</p>
<input id="submit" type="submit" value="Submit">
</form>
The Highcharts docs use this as an example, which is what I am trying to use, but instead of hard coding the data I need to pass in my form data. I think...if I am totally off please let me know. Any help is appreciated.
$('#add_data input:radio[name=request_type]').click(function() {
$index = $('#add_data input:radio[name=request_type]').index(this);
});
$('#submit').click(function() {
var chart = $('#container').highcharts(),
amount = parseFloat($('#amount').val());
chart.series[$index].addPoint(amount);
});
In your click action you need to extract values from inputs. For example if you need to add point with value from input AMOUNT it should be used like:
$('#submit').click(function() {
var chart = $('#container').highcharts(),
point = parseFloat($('#amount').val());
chart.series[0].addPoint(point);
i += 1;
});

jQuery: ajax content is loading in wrong div class

I have a jQuery vote script that allows a user to vote on a poll that is displayed on a page. On a particular page there are many polls being displayed (via forms) and the jQuery grabs the values of the inputs in a particular form and send the data over to a query.php page.
This is what a sample poll page looks like:
QUESTION 1:<br />
<div class="poll_area">
<div id="poll">
<form method="POST" action="" class="poll_query">
<input type="hidden" value="favorites" name="page" />
<input type="hidden" value="user1" name="to" />
<input type="hidden" name="pid" value="1"/>
<input name="" type="radio" value="yes" /> Yes<br />
<input name="" type="radio" value="no" /> No<br />
</form>
</div>
<div class="result"> </div>
</div>
QUESTION 2:<br />
<div class="poll_area">
<div id="poll">
<form method="POST" action="" class="poll_query">
<input type="hidden" value="favorites" name="page" />
<input type="hidden" value="user2" name="to" />
<input type="hidden" name="pid" value="2"/>
<input name="" type="radio" value="yes" /> Yes<br />
<input name="" type="radio" value="no" /> No<br />
</form>
</div>
<div class="result"> </div>
</div>
And this is the jQuery Script I'm running:
var ajax_load = "<img src='images/ajax-loader.gif' alt='loading...' />";
$("form.poll_query > input[type='radio']").click(function(e) {
e.preventDefault();
var form= $(this).closest("form");
var pid = $("input[name='pid']", form).val();
var ans = $(this).val();
var page = $("input[name='page']", form).val();
var to = $("input[name='to']", form).val();
$(this).closest("#poll").html(ajax_load);
$.post(
"query.php?module=vote",
{answer: ans, pid: pid, to: to, page: page},
function(responseText){
$("#poll").hide(0,function() {
$(".result").html(responseText).fadeIn(1500);
});
},
"html"
);
});
When voting in the first poll everything renders correctly. The 'responseText' that is returned is displayed in the page where it is supposed to. But for every subsequent poll on the page the 'ajax_load' loads correctly where it is supposed to but the 'responseText' is loaded in the .result class of the FIRST poll.
This is what the page initially looks like:
Question 1?
o YES
o NO
Question 2?
o YES
o NO
if a particular user votes on question 2 this is what the page should look like:
Question 1?
o YES
o NO
Question 2
o YES : XXXXXXXXX 60%
o NO : XXXXXX 40%
Instead this is what actually happens (even though the user voted on question 2):
Question 1?
o YES : XXXXXXXXX 60%
o NO : XXXXXX 40%
Question 2
o YES
o NO
But if the user votes on question 1 the results is loaded properly:
Question 1?
o YES : XXXXXXXXX 60%
o NO : XXXXXX 40%
Question 2
o YES
o NO
I've tried changing $(".result").html(responseText).fadeIn(1500); to $(this).closest(".result").html(responseText).fadeIn(1500);
But still no luck.
You have duplicate element IDs for poll. You should use a class instead, then make your selectors in the callback more precise. You're on the right track with $(this).closest().
You'll need to do something like:
var pollArea = $(this).closest(".poll_area");
$.post(... , function(responseText) {
pollArea.find(".poll").hide(0,function() {
pollArea.find(".result").html(responseText).fadeIn(1500);
});
Note that the .poll and .result selectors are now scoped by the .poll_area that encloses the clicked radio button.
I'd suggest using an element based on an ID rather than a class. Therefore wrap each question into a div with a unique ID
<div id="q1">
QUESTION 1:<br />
<div class="poll_area">
<div id="poll">
<form method="POST" action="" class="poll_query">
<input type="hidden" value="favorites" name="page" />
<input type="hidden" value="user1" name="to" />
<input type="hidden" name="pid" value="1"/>
<input name="" type="radio" value="yes" /> Yes<br />
<input name="" type="radio" value="no" /> No<br />
</form>
</div>
<div class="result"> </div>
</div>
$("#q1 .result").html('...');

Categories

Resources