Why does handleChange not fire correctly in react.js? - javascript

I am working on a project where I have created a form in react.js with radio buttons but handleChange event is not firing the correct value of selected radio button. When I select male the formData object still has an empty value of gender, when I select it again the value of gender in formData gets updated to 0 which is equal to female. Please help me know what is the problem with my code.
import React from "react"
function Questions(props) {
const [formData, setFormData] = React.useState({
age: "",
gender: "",
polyuria: "",
polydipsia: "",
weight_loss: "",
weakness: "",
polyphagia: "",
genital_thrush: "",
visual_blurring: "",
itching: "",
irritability: "",
delayed_healing: "",
partial_paresis: "",
muscle_stiffness: "",
alopecia: "",
obesity: ""
})
function handleChange(event) {
const name = event.target.name
const value = event.target.value
setFormData(prevFormData => ({
...prevFormData,
[name]: value
}))
console.log(formData)
}
return (
<div>
<h1>Here will be Questions</h1>
<div className="form">
<p id="age" name="age">How old are you?</p>
<input type="number" min="1.20" max="5" htmlFor="age" value={formData.age} name="age"
onChange={handleChange}/>
<p id="gender">What is your gender?</p>
<input type="radio" id="male" name="gender" value="1" htmlFor="gender"
onChange={handleChange} checked={formData.gender === "1"}/>Male
<input type="radio" id="female" name="gender" value="0" htmlFor="gender"
onChange={handleChange} checked={formData.gender === "0"}/>Female
<p>Do you suffer from Polyuria?</p>
<p>If you are unfamiliar, read about Polyuria here</p>
<label><input type="radio" id="yes" name="polyuria" value="1" onChange={handleChange} checked={formData.polyuria === "1"}/>Yes</label>
<label><input type="radio" id="no" name="polyuria" value="0" onChange={handleChange} checked={formData.polyuria === "0"}/>No</label>
<p>Do you suffer from Polydipsia?</p>
<p>If you are unfamiliar, read about Polydipsia here</p>
<label><input type="radio" id="yes" name="polydipsia" value="1" onChange={handleChange}/>Yes</label>
<label><input type="radio" id="no" name="polydipsia" value="0" onChange={handleChange}/>No</label>
<p>Have you noticed sudden weight loss in yourself?</p>
<label><input type="radio" id="yes" name="weight_loss" value="1" onChange={handleChange}/>Yes</label>
<label><input type="radio" id="no" name="weight_loss" value="0" onChange={handleChange}/>No</label>
<p>Do you feel more weakness than usual throughout the day?</p>
<label><input type="radio" id="yes" name="weakness" value="1" onChange={handleChange}/>Yes</label>
<label><input type="radio" id="no" name="weakness" value="0" onChange={handleChange}/>No</label>
<p>Do you suffer from Polyphagia?</p>
<label><input type="radio" id="yes" name="polyphagia" value="1" onChange={handleChange}/>Yes</label>
<label><input type="radio" id="no" name="polyphagia" value="0" onChange={handleChange}/>No</label>
<p>Do you suffer from Genital Thrush?</p>
<label><input type="radio" id="yes" name="genital_thrush" value="1" onChange={handleChange}/>Yes</label>
<label><input type="radio" id="no" name="genital_thrush" value="0" onChange={handleChange}/>No</label>
<p>Have you noticed your vision blurring?</p>
<label><input type="radio" id="yes" name="visual_blurring" value="1" onChange={handleChange}/>Yes</label>
<label><input type="radio" id="no" name="visual_blurring" value="0" onChange={handleChange}/>No</label>
<p>Do you duffer from unusual itching on your body?</p>
<label><input type="radio" id="yes" name="itching" value="1" onChange={handleChange}/>Yes</label>
<label><input type="radio" id="no" name="itching" value="0" onChange={handleChange}/>No</label>
<p>Do you experience unusual irritability/ mood swings?</p>
<label><input type="radio" id="yes" name="irritability" value="1" onChange={handleChange}/>Yes</label>
<label><input type="radio" id="no" name="irritability" value="0" onChange={handleChange}/>No</label>
<p>Have you noticed delayed healing of wounds/ scars?</p>
<label><input type="radio" id="yes" name="delayed_healing" value="1" onChange={handleChange}/>Yes</label>
<label><input type="radio" id="no" name="delayed_healing" value="0" onChange={handleChange}/>No</label>
<p>Do you suffer from Partial paresis?</p>
<label><input type="radio" id="yes" name="partial_paresis" value="1" onChange={handleChange}/>Yes</label>
<label><input type="radio" id="no" name="partial_paresis" value="0" onChange={handleChange}/>No</label>
<p>Do you suffer from muscle stiffness?</p>
<label><input type="radio" id="yes" name="muscle_stiffness" value="1" onChange={handleChange}/>Yes</label>
<label><input type="radio" id="no" name="muscle_stiffness" value="0" onChange={handleChange}/>No</label>
<p>Do you suffer from Alopecia?</p>
<label><input type="radio" id="yes" name="alopecia" value="1" onChange={handleChange}/>Yes</label>
<label><input type="radio" id="no" name="alopecia" value="0" onChange={handleChange}/>No</label>
<p>Are you obese?</p>
<label><input type="radio" id="yes" name="obesity" value="1" onChange={handleChange}/>Yes</label>
<label><input type="radio" id="no" name="obesity" value="0" onChange={handleChange}/>No</label>
<button>Predict</button>
</div>
<button onClick={props.toggleBack}>Back</button>
</div>
)
}
export default Questions

change your handle function to this
function handleChange(event) {
const name = event.target.name
const value = event.target.value
const updatedData = {...formData,[name]:value}
setFormData(updatedData)
console.log(formData)
}
currently your state update and render is not aligned.

Related

Adding form field values together into hidden field on form submit (js or jquery)

this seems super simple to me, but I just can't figure it out today.
I've developed a basic quiz, and want to add the answers of the quiz together to create a "score". Based on the score I'll return different results on the confirmation page.
Here's a basic example of the form:
<form id="quiz" method="post" name="quiz" action="url">
<label for="field1">Question 1</label>
<label><input name="question1" value="1" type="radio">Answer 1</label>
<label><input name="question1" value="4" type="radio">Answer 2</label>
<label><input name="question1" value="9" type="radio">Answer 3</label>
<label for="field2">Question 2</label>
<label><input name="question2" value="1" type="radio">Answer 1</label>
<label><input name="question2" value="4" type="radio">Answer 2</label>
<label><input name="question2" value="9" type="radio">Answer 3</label>
<label for="field3">Question 3</label>
<label><input name="question3" value="1" type="radio">Answer 1</label>
<label><input name="question3" value="4" type="radio">Answer 2</label>
<label><input name="question3" value="9" type="radio">Answer 3</label>
<input value="See your Results" type="submit">
</form>
I tried building out some javascript to add these values together, but it wasn't even beginning to work - here's my attempt in case you're curious:
function generateScore(){
var maturityScore = document.forms[0].question1.value + document.forms[0].question2.value + document.forms[0].question1.value;
document.forms[0].maturityLevel.value = maturityScore;
}
document.forms[0].addEventListener('submit') = generateScore
Can anyone point me in the right direction? Happy to use javascript or jquery to do this. Note that I can't edit the form html - it's being generated by the MAP I'm using (and is way ugly - the version I posted above is simplified for readability).
Thank you!
Following code will be helpful to you,
$('#quiz').on('submit',function(){
var score = parseInt($('input[name=question1]:checked').val())+
parseInt($('input[name=question2]:checked').val())+
parseInt($('input[name=question3]:checked').val());
alert('submit'+score);
//score can be assigned to any field you need
//$('#maturityLevel').val(score);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="quiz" method="post" name="quiz" action="url">
<label for="field1">Question 1</label>
<label><input name="question1" value="1" type="radio">Answer 1</label>
<label><input name="question1" value="4" type="radio">Answer 2</label>
<label><input name="question1" value="9" type="radio">Answer 3</label>
<label for="field2">Question 2</label>
<label><input name="question2" value="1" type="radio">Answer 1</label>
<label><input name="question2" value="4" type="radio">Answer 2</label>
<label><input name="question2" value="9" type="radio">Answer 3</label>
<label for="field3">Question 3</label>
<label><input name="question3" value="1" type="radio">Answer 1</label>
<label><input name="question3" value="4" type="radio">Answer 2</label>
<label><input name="question3" value="9" type="radio">Answer 3</label>
<input value="See your Results" type="submit">
</form>
Make sure to answer all the 3 question. Otherwise you have to do the proper validations before parsing using parseInt.

JavaScript Quiz Valadition

I seem to be having some trouble validating a 4 question multiple choice quiz in JavaScript. Right now if none of the answers are selected the alert pops up, but if even only one answer is selected the alert doesn't pop. I'm running my function as an onclick for a submit button. I'm fairly new to JavaScript and JQuery but have other programming experience, so The problem is probably something simple but I cant see it.
The function is:
function quiz1(){
if (!$("input[#name=q1]:checked").val() ||
!$("input[#name=q2]:checked").val() ||
!$("input[#name=q3]:checked").val() ||
!$("input[#name=q4]:checked").val() ||
!$("input[#name=q5]:checked").val()
) {
alert("You're not done yet!");
}
}
The html is:
<p class="question">1. What is the answer to this question?</p>
<ul class="answers">
<input type="radio" name="q1" value="a" id="q1a"><label for="q1a">Answer 1</label><br/>
<input type="radio" name="q1" value="b" id="q1b"><label for="q1b">Answer 2</label><br/>
<input type="radio" name="q1" value="c" id="q1c"><label for="q1c">Answer 3</label><br/>
<input type="radio" name="q1" value="d" id="q1d"><label for="q1d">Answer 4</label><br/>
</ul>
<p class="question">2. What is the answer to this question?</p>
<ul class="answers">
<input type="radio" name="q2" value="a" id="q2a"><label for="q2a">Answer 1</label><br/>
<input type="radio" name="q2" value="b" id="q2b"><label for="q2b">Answer 2</label><br/>
<input type="radio" name="q2" value="c" id="q2c"><label for="q2c">Answer 3</label><br/>
<input type="radio" name="q2" value="d" id="q2d"><label for="q2d">Answer 4</label><br/>
</ul>
<p class="question">3. What is the answer to this question?</p>
<ul class="answers">
<input type="radio" name="q3" value="a" id="q3a"><label for="q3a">Answer 1</label><br/>
<input type="radio" name="q3" value="b" id="q3b"><label for="q3b">Answer 2</label><br/>
<input type="radio" name="q3" value="c" id="q3c"><label for="q3c">Answer 3</label><br/>
<input type="radio" name="q3" value="d" id="q3d"><label for="q3d">Answer 4</label><br/>
</ul>
<p class="question">4. What is the answer to this question?</p>
<ul class="answers">
<input type="radio" name="q4" value="a" id="q4a"><label for="q4a">Answer 1</label><br/>
<input type="radio" name="q4" value="b" id="q4b"><label for="q4b">Answer 2</label><br/>
<input type="radio" name="q4" value="c" id="q4c"><label for="q4c">Answer 3</label><br/>
<input type="radio" name="q4" value="d" id="q4d"><label for="q4d">Answer 4</label><br/>
</ul>
<div class="submit">
<input type="submit" onclick="quiz1()" value="Check Answers">
</div>
You have some syntax errors in there.
before:
function quiz1(){
if (!$("input[#name=q1]:checked").val() ||
!$("input[#name=q2]:checked").val() ||
!$("input[#name=q3]:checked").val() ||
!$("input[#name=q4]:checked").val() ||
!$("input[#name=q5]:checked").val()
) {
alert("You're not done yet!");
}
}
After:
function quiz1(){
if (!$("input[name='q1']:checked").val() ||
!$("input[name='q2']:checked").val() ||
!$("input[name='q3']:checked").val() ||
!$("input[name='q4']:checked").val()
) {
alert("You're not done yet!");
}
}
so with jquery when you want to reference a name you have to type it just like the name attribute in the html that is true with any attribute selector E.G.(data='', ng-someting=''...) and also you had one to many inputs in there XD
here is a jsfiddle

JavaScript to create a global radio button for all subsequent radio buttons?

I have this set of labels and radio buttons that look like this:
Entertainment: <input type="radio" name="entertainment" id="entertainment" value="0" checked/>
<input type="radio" name="entertainment" id="entertainment" value="1" />
<input type="radio" name="entertainment" id="entertainment" value="2" /><br />
Radio: <input type="radio" name="radio" id="radio" value="0" checked/>
<input type="radio" name="radio" id="radio" value="1" />
<input type="radio" name="radio" id="radio" value="2" /><br />
Dancing: <input type="radio" name="dancing" id="dancing" value="0" checked/>
<input type="radio" name="dancing" id="dancing" value="1" />
<input type="radio" name="dancing" id="dancing" value="2" /><br />
Music: <input type="radio" name="music" id="music" value="0" checked/>
<input type="radio" name="music" id="music" value="1" />
<input type="radio" name="music" id="music" value="2" /><br />
Television: <input type="radio" name="tv" id="tv" value="0" checked/>
<input type="radio" name="tv" id="tv" value="1" />
<input type="radio" name="tv" id="tv" value="2" /><br />
Film: <input type="radio" name="film" id="film" value="0" checked/>
<input type="radio" name="film" id="film" value="1" />
<input type="radio" name="film" id="film" value="2" /><br />
Theatre: <input type="radio" name="theatre" id="theatre" value="0" checked/>
<input type="radio" name="theatre" id="theatre" value="1" />
<input type="radio" name="theatre" id="theatre" value="2" />
The idea is that the three 'Entertainment' radio buttons at the top control all the radio buttons below. A 'global switch', if you will, to save people time. Does anyone know the necessary JavaScript/jQuery to accomplish this? I can't find a correct example online.
$(':radio[name=entertainment]').change(function() {
$(this).nextAll(':radio[value="'+ this.value +'"]').prop('checked', true);
$(this).nextAll(':radio[value!="'+ this.value +'"]').prop('checked', false);
});
Working sample
Note
ids should be unique.

Select one Form Checkbox

I've an HTML form that I've put together...
There is a question "Can you attend?" with a "Yes" and "No" checkbox.
Obviously who submits the form will either attend or not, so I would like for the form to only allow one checkbox to be selected of the two.
Here's the HTML:
<p>Can you attend?</p>
<label>
<input type="checkbox" name="attendance" value="checkbox" id="Yes" />
Yes</label>
<label>
<input type="checkbox" name="attendance" value="checkbox" id="No" />
No</label>
What does my code need to be? I'm guessing some JavaScript?
Thank you
And thus the radio was born :-)
<p>Can you attend?</p>
<label>
<input type="radio" name="attendance" value="checkbox" id="Yes" />
Yes</label>
<label>
<input type="radio" name="attendance" value="checkbox" id="No" />
No</label>
Demo: http://jsbin.com/oreped/

jQuery Quiz compare correct answer in array

My HTML
<div class="questions">
<p>Q1</p>
<label><input name="q1" id="q1-a" type="radio" />Q1 ans A</label>
<label><input name="q1" id="q1-b" type="radio" />Q1 ans B</label>
<label><input name="q1" id="q1-c" type="radio" />Q1 ans C</label>
</div>
<div class="questions hide">
<p>Q2</p>
<label><input name="q2" id="q1-a" type="radio" />Q2 ans A</label>
<label><input name="q2" id="q1-b" type="radio" />Q2 ans B</label>
<label><input name="q2" id="q1-c" type="radio" />Q2 ans C</label>
</div>
<div class="questions hide">
<p>Q3</p>
<label><input name="q3" id="q1-a" type="radio" />Q3 ans A</label>
<label><input name="q3" id="q1-b" type="radio" />Q3 ans B</label>
<label><input name="q3" id="q1-c" type="radio" />Q3 ans C</label>
</div>
Check
MY JS
$("#checkAns").click(function(){
}
Here are the array of answer which I want to compare
answers: { q1: 'a', q2: 'b', q3: 'a'}
If user trigger radio button then it will show alert if is Correct or Wrong then it will return true; if wrong false then this is the time it will show another question for answering
I do want to avoid if else in checking the user answer is this possible?
First, don't forget to add value on each radio button. Also id is not really needed here, except you need to do something on each radio button:
<div>
<label><input name="q1" type="radio" value="a" />Q1 A</label>
<label><input name="q1" type="radio" value="b" />Q1 B</label>
<label><input name="q1" type="radio" value="c" />Q1 C</label>
</div>
Then for checking answers, you can use this:
var answers = {q1 : 'a', q2 : 'b', q3 : 'a'};
$('#checkAns').click(function(e) {
$.each(answers, function(question, answer) {
if($('input:radio[name="' + question + '"]:checked').val() == answer)
alert(question + ': True');
else
alert(question + ': False!');
});
e.preventDefault();
});
Updated answer :
HTML & CSS
I think you don't need an anchor to click, because this time the script check the answer as soon as the radio button is triggered.
<style type="text/css">
.hide { display:none; }
</style>
<div class="questions">
<p>Q1</p>
<label><input type="radio" name="q1" value="a" />Q1 A</label>
<label><input type="radio" name="q1" value="b" />Q1 B</label>
<label><input type="radio" name="q1" value="c" />Q1 C</label>
</div>
<div class="questions hide">
<p>Q2</p>
<label><input type="radio" name="q2" value="a" />Q2 A</label>
<label><input type="radio" name="q2" value="b" />Q2 B</label>
<label><input type="radio" name="q2" value="c" />Q2 C</label>
</div>
<div class="questions hide">
<p>Q3</p>
<label><input type="radio" name="q3" value="a" />Q3 A</label>
<label><input type="radio" name="q3" value="b" />Q3 B</label>
<label><input type="radio" name="q3" value="c" />Q3 C</label>
</div>
Javascript using jQuery
var answers = {q1: 'a', q2: 'b', q3: 'a'};
$('input:radio').click(function() {
var container = $(this).parents('div');
var question = $(this).attr('name');
var answer = $(this).val();
alert(answers[question] == answer);
container.addClass('hide');
container.next().removeClass('hide');
});
Just modify the script as you need. Hope this time is right.. :P

Categories

Resources