The radio button doesn't react when I click on it, what could be the problem? - html

So I have a simple form with a few inputs and two radio buttons, but when I click any of them, they seem like they don't react. What could be the problem?
import { useState } from "react";
import uuid from "react-uuid";
import "./style.css";
export default function LargeForm() {
const [people, setPeople] = useState([]);
const [newUser, setNewUser] = useState({
id: uuid(),
firstName: "",
lastName: "",
sex: "",
dateOfBirth: "",
email: "",
contact: "",
password: ""
});
const handleChange = (value, type) => {
setNewUser((prev) => {
return { ...prev, [type]: value };
});
};
const handleSubmit = (e) => {
e.preventDefault();
if (
newUser.firstName &&
newUser.lastName &&
newUser.dateOfBirth &&
newUser.email &&
newUser.contact &&
newUser.password
) {
setPeople([...people, newUser]);
setNewUser({
firstName: "",
lastName: "",
sex: "",
dateOfBirth: "",
email: "",
contact: "",
password: ""
});
} else {
console.log("Error!");
}
};
return (
<>
<form className="container" autoComplete="off" onSubmit={handleSubmit}>
<div>
<label htmlFor="firstName" className="label">
First name:{" "}
</label>
<input
type="text"
id="firstName"
name="firstName"
className="input"
value={newUser.firstName}
onChange={(e) => handleChange(e.target.value, "firstName")}
/>
<br />
<label htmlFor="lastName" className="label">
Last name:{" "}
</label>
<input
type="text"
id="lastName"
name="lastName"
className="input"
value={newUser.lastName}
onChange={(e) => handleChange(e.target.value, "lastName")}
/>
<br />
<label htmlFor="sex" className="label">
Sex:
</label>
<input
type="radio"
id="male"
name="sex"
value={newUser.sex}
onChange={(e) => handleChange(e.target.value, "sex")}
/>
 <label for="male">Male</label> {" "}
<input
type="radio"
id="female"
name="sex"
value={newUser.sex}
onChange={(e) => handleChange(e.target.value, "sex")}
/>
<label for="female">Female</label>
<br />
<label htmlFor="dateOfBirht" className="label">
Date of birth:{" "}
</label>
<input
type="date"
id="dateOfBirht"
name="dateOfBirht"
className="input"
value={newUser.dateOfBirth}
onChange={(e) => handleChange(e.target.value, "dateOfBirth")}
/>
<br />
<label htmlFor="email" className="label">
Email:{" "}
</label>
<input
type="email"
id="Email"
name="Email"
className="input"
value={newUser.email}
onChange={(e) => handleChange(e.target.value, "email")}
/>
<br />
<label htmlFor="contact" className="label">
Contact:{" "}
</label>
<input
type="text"
id="contact"
name="contact"
className="input"
value={newUser.Contact}
onChange={(e) => handleChange(e.target.value, "contact")}
/>
<br />
<label htmlFor="password" className="label">
Password:{" "}
</label>
<input
type="password"
id="password"
name="password"
className="input"
value={newUser.password}
onChange={(e) => handleChange(e.target.value, "password")}
/>
</div>
<br />
<button type="submit" className="btn">
Submit
</button>
</form>
{people.map((person) => {
return (
<div className="list" key={person.id}>
{person.firstName}
<br />
{person.lastName}
<br />
{person.sex}
<br />
{person.dateOfBirth}
<br />
{person.email}
<br />
{person.contact}
<br />
{person.password}
</div>
);
})}
</>
);
}
The CodeSandbox link is given below.
https://codesandbox.io/s/learning-react-5vj5g?file=/src/useReducer/exampleForm/LargeForm.js

In your code you are setting handleSubmit to be called on onClick of the form. That means anything that you do on that form HTML element it will be a click event first.
It is a small change from onClick to onSubmit
...
<form className="container" autoComplete="off" onSubmit={handleSubmit}>
...
Also the part where you define radio inputs, you should use checked state of that input and set value to be the desired value for that radio input:
<label htmlFor="sex" className="label">
Sex:
</label>
<input
type="radio"
id="male"
name="sex"
value='male'
checked={newUser.sex === 'male'}
onChange={(e) => handleChange(e.target.value, "sex")}
/>
 <label for="male">Male</label> {" "}
<input
type="radio"
id="female"
name="sex"
value='female'
checked={newUser.sex === 'female'}
onChange={(e) => handleChange(e.target.value, "sex")}
/>
<label for="female">Female</label>

You must use checked attribute to specify which item is checked. And use value property to set the value of any radio item. You also define onClick attribute on Form tag that it's incorrect and you must use onSubmit instead of that.
This is the correct link:
https://codesandbox.io/s/learning-react-forked-4wic3

change onClick to onSubmit. it'll work

Related

How to make google Autofill correct address inputs

When I click autofill, It only fills the first input. Is there a way to make it autofill, the other inputs. I am using reactjs.
<div className={`${styles.formGroup} ${styles.address}`}>
<label className={styles.label} htmlFor="address">
Address
</label>
<input
value={address}
onChange={(e) => setAddress((prev) => e.target.value)}
className={styles.input}
type="text"
id="address"
name="address"
required
/>
</div>
<div className={`${styles.formGroup} ${styles.address}`}>
<label className={styles.label} htmlFor="address">
Apartment
</label>
<input
value={apartment}
onChange={(e) => setApartment((prev) => e.target.value)}
className={styles.input}
type="text"
id="address"
name="address"
required
/>
</div>
<div className={`${styles.formGroup} `}>
<label className={styles.label} htmlFor="governorate">
Governorate
</label>
<Select
options={governorates}
value={governorate}
onChange={(e) => setGovernorate((prev) => e)}
styles={{
control: (baseStyles, state) => ({
...baseStyles,
borderRadius: "4px",
padding: "4.6px",
}),
}}
/>
</div>
How do I make it so that it automatically fills the other inputs

Jquery checkbox checked when i add text value input

How can I toggle a checkbox by using a text input check and check automatically if it exists in the list?
For example :
if you write 222 in the input with id=222 will be checked
if already checked it will be unchecked
if is not found an alert will be shown
$(document).ready(function() {
$('#Scan').on('keypress', function(e) {
if (e.which == 13) {
Scan = $('#Scan').val();
//if value exsit in the list -> checked
//if value checked -> dechecked
//if value not exist -> alert not exist
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="Scan" name="Scan" type="text" autocomplete="off" placeholder="Tracking Number" autofocus>
<br/>
<input class="custom-control-input" type="checkbox" id="111" value="111">
<label for="111" class="custom-control-label">111</label>
<br/>
<input class="custom-control-input" type="checkbox" id="222" value="222">
<label for="222" class="custom-control-label">222</label>
<br/>
<input class="custom-control-input" type="checkbox" id="333" value="333">
<label for="333" class="custom-control-label">333</label>
<br/>
<input class="custom-control-input" type="checkbox" id="444" value="444">
<label for="444" class="custom-control-label">444</label>
<br/>
<input class="custom-control-input" type="checkbox" id="555" value="555">
<label for="555" class="custom-control-label">555</label>
You can check if your result collection has elements in it by using .length.
$(document).ready(function() {
$('#Scan').on('keypress', function(e) {
if (e.which == 13) {
Scan = $('#Scan').val();
target = $(`#${Scan}`);
if (target.length) {
target.prop('checked', !target.prop('checked'));
} else {
alert("Not found");
}
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="Scan" name="Scan" type="text" autocomplete="off" placeholder="Tracking Number" autofocus>
<br/>
<input class="custom-control-input" type="checkbox" id="111" value="111">
<label for="111" class="custom-control-label">111</label>
<br/>
<input class="custom-control-input" type="checkbox" id="222" value="222">
<label for="222" class="custom-control-label">222</label>
<br/>
<input class="custom-control-input" type="checkbox" id="333" value="333">
<label for="333" class="custom-control-label">333</label>
<br/>
<input class="custom-control-input" type="checkbox" id="444" value="444">
<label for="444" class="custom-control-label">444</label>
<br/>
<input class="custom-control-input" type="checkbox" id="555" value="555">
<label for="555" class="custom-control-label">555</label>
Reference for template literals, just in case.
Here is an example using your conditions specified in question.
My alert is not a true js alert as that will halt any further input changes, so i've created an alert function to show if [name="scan"] input value exists in your checkbox input ids.
See comments in my script...
// create input ids array
let input_ids = [];
// for each checkbox type input id
$('[type="checkbox"]').each(function() {
// get the input id
let input_id = $(this).attr('id');
// add input id to input ids array
input_ids.push(input_id);
});
// on input change in doc for elem [name="scan"]
$(document).on('input', '[name="scan"]', function(e) {
// [name="scan"] current input val
let val = e.target.value;
// if val exist in input ids array
if ($.inArray(val, input_ids) >= 0) {
// get this input by id
let $input = $('#' + e.target.value);
// if input is checked
if ($input.prop('checked')) {
// uncheck input
$input.prop('checked', false);
} else {
// else check input
$input.prop('checked', true);
}
} else {
// run alert
alert(e);
}
// stop propagation
e.stopPropagation();
});
// not found alert
function alert(e) {
// activate alert class
$('.alert').addClass('active');
// time out to hide
setTimeout(function() {
// remove class
$('.alert').removeClass('active');
}, 1000);
}
.alert {
position: fixed;
top: 10px;
right: 10px;
background: red;
padding: .25rem .5rem;
opacity: 0;
transition: all .5s ease;
color: #fff;
}
.alert.active {
opacity: 1
}
<input name="scan" type="text" autocomplete="off" placeholder="Tracking Number" autofocus />
<br />
<input class="custom-control-input" type="checkbox" id="111" />
<label for="111" class="custom-control-label">111</label>
<br />
<input class="custom-control-input" type="checkbox" id="222" />
<label for="222" class="custom-control-label">222</label>
<br />
<input class="custom-control-input" type="checkbox" id="333" />
<label for="333" class="custom-control-label">333</label>
<br />
<input class="custom-control-input" type="checkbox" id="444" />
<label for="444" class="custom-control-label">444</label>
<br />
<input class="custom-control-input" type="checkbox" id="555" />
<label for="555" class="custom-control-label">555</label>
<div class="alert">Not found</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I wouldn't use jQuery, but if you insist:
$(function(){
const scan = $('#Scan'), cci = $('.custom-control-input');
let scanVal;
scan.on('input', ()=>{
let scanVal = scan.val(), good;
cci.each((i, n)=>{
if(scanVal === $(n).val()){
n.checked = !n.checked; good = true;
}
});
if(good === undefined && scanVal.length > 2){
alert('Never use Alert');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="Scan" name="Scan" type="text" autocomplete="off" placeholder="Tracking Number" autofocus>
<br/>
<input class="custom-control-input" type="checkbox" id="111" value="111">
<label for="111" class="custom-control-label">111</label>
<br/>
<input class="custom-control-input" type="checkbox" id="222" value="222">
<label for="222" class="custom-control-label">222</label>
<br/>
<input class="custom-control-input" type="checkbox" id="333" value="333">
<label for="333" class="custom-control-label">333</label>
<br/>
<input class="custom-control-input" type="checkbox" id="444" value="444">
<label for="444" class="custom-control-label">444</label>
<br/>
<input class="custom-control-input" type="checkbox" id="555" value="555">
<label for="555" class="custom-control-label">555</label>

Few field values are not showing up in the final output, i'm using nodejs

index.html
<form action="http://127.0.0.1:5555/sign" method="POST">
<div class="main">
<div class="name-container">
<input type="text" class="input" placeholder="First Name" id="fname" />
<input type="text" class="input" placeholder="Last Name" id="lname" />
</div>
<div class="gender_date">
<div class="gen">
<input type="radio" name="gender" value="male" id="male" />
<label for="male">Male</label>
<input type="radio" name="gender" value="female" id="female" />
<label for="female">Female</label>
<input type="radio" name="gender" value="other" id="other" />
<label for="other">Other</label>
</div>
<div class="date-con">
<input type="date" class="input" id='date' name="bday" />
</div>
</div>
</div>
</form>
the post request works properly but the names aren't showing up.
back-end nodejs file => serve.js
const express = require("express");
const fs = require("fs");
const bodyParser = require("body-parser");
const app = express();
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.get("/sign", (req, res) => {
res.send("Hello");
});
app.post("/sign", urlencodedParser, (req, res) => {
res.send(req.body);
let student = req.body;
let students = [];
students.push(student);
let data = JSON.stringify(students, null, 2);
fs.writeFile("./file.json", data, err => console.log("success"));
console.log(students);
});
const PORT = 5555;
app.listen(PORT, err => {
console.log(`Server Running at port: ${PORT}`);
});
file.json: Output
[
{
"gender": "male",
"bday": "1999-07-05"
}
]
The value from "First Name" and "Last Name" fields aren't showing up in the final output.
No matter what I change I couldn't get it to work properly.
Thank you in advance.
Try it
<form action="http://127.0.0.1:5555/sign" method="POST">
<div class="main">
<div class="name-container">
<input type="text" class="input" placeholder="First Name" name="fname" />
<input type="text" class="input" placeholder="Last Name" name="lname" />
</div>
<div class="gender_date">
<div class="gen">
<input type="radio" name="gender" value="male" id="male" />
<label for="male">Male</label>
<input type="radio" name="gender" value="female" id="female" />
<label for="female">Female</label>
<input type="radio" name="gender" value="other" id="other" />
<label for="other">Other</label>
</div>
<div class="date-con">
<input type="date" class="input" id='date' name="bday" />
</div>
</div>
</div>
</form>

My password validation doesn't execute properly

So I'm trying to make a password verification with JS, it used to work (making the text box red when the passwords were not the same(OnKeyUp)) but wouldn't make the button block the actual register.
if you can have a look at my code i'd be really grateful thank you.
function auth() {
var password = document.getElementById("password");
var password2 = document.getElementById("Repassword")
var PassDont = document.getElementById("passDont")
if (password.value != password2.value()) {
PassDont.innerHTML = "<h3> Passwords Don't match </h3>";
password2.style.backgroundColor = "#ff3232";
return false;
} else {
password2.style.backgroundColor = "#8fff89";
PassDont.innerHTML = " "
}
}
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="Server">
<div id="container">
<h1 class="RegHead">Registeration</h1>
<label class="input-label" for="username">username</label>
<input class="user-input" type="text" id="username" name="user_name" pattern="[A-Za-z0-9]+" maxlength="12" title="Username should be in English and numbers, 12 letters max" required autocomplete="off" />
<br />
<label class="input-label" for="password">Password:</label>
<input class="user-input" type="password" id="password" name="password" pattern=".{6,12}" required title="Password have to contain between 6 to 12 letters" required autocomplete="off" />
<br />
<label class="input-label" for="Re-password">Re-enter Password:</label>
<input class="user-input" type="password" id="Repassword" name="repassword" onkeyup="return auth();" autocomplete="off" />
<br />
<asp:Button runat="server" Text="Register" OnClick="OnSubmitClick" OnClientClick="return auth();" />
<span id="passDont"></span>
</div>
</asp:Content>
if (password.value != password2.value())
to
if (password != password2)

Get array of object in AngularJS

I am using directive to add HTML div dynamically on the click of button.
How can I bind the model to controller scope object?
How can populate the scope object with enter data in dynamically added div?
How can I get list of object while click on save button.
Please find the code that I tried to add html div dynamically, but doesn't have any idea how to bind the entered data to scope object.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script type="text/javascript">
function FlatMember() {
this.firstName = '';
this.lastName = '';
this.emailId = '';
this.panNo = '';
this.phoneNo = '';
this.profileImage = ''
}
angular.module('myApp', []);
angular.module('myApp').controller('FlatMemberController', function ($scope) {
$scope.flatMembers = [];
$scope.addFlatMember = function() {
$scope.flatMembers.push(new FlatMember());
};
$scope.SaveFlatMember = function(){
console.log($scope.flatMembers);
}
});
angular.module('myApp').directive('memberInformation', function(){
return {
restrict: 'A',
template: '<div style="margin-top: 50px;">\
<div>\
<p>\
<label>First Name </label>\
<input type="text" id="firstName" /> \
<label>Last Name </label> <input type="text" id="lastName" />\
</p>\
<p>\
<label>Email </label> <input type="email" id="emailId"/>\
</p>\
<p>\
<label>PAN Number </label> <input type="text" id="panNo" data-ng-minlength="10"/>\
</p>\
<p>\
<label>Mobile </label> <input type="text" data-ng-minlength="10" id="phoneNo" />\
</p>\
</div> </div>',
replace: true,
transclude: false,
scope: {
memberInfo: '=memberInformation'
}
};
});
</script>
</head>
<body ng-app="myApp">
<div ng-controller="FlatMemberController">
<button ng-click="addFlatMember()">Add new Member</button>
<div ng-repeat="flatMember in flatMembers"member-information="flatMember"></div>
<button ng-click="SaveFlatMember()">Save Member</button>
</div>
</body>
</html>
Your template is missing the ng-model bindings:
angular.module('myApp').directive('memberInformation', function(){
return {
restrict: 'A',
template: '<div style="margin-top: 50px;">\
<div>\
<p>\
<label>First Name </label>\
<input type="text" id="firstName" name="firstName" ng-model="memberInfo.firstName" /> \
<label>Last Name </label> <input type="text" id="lastName" name="lastName" ng-model="memberInfo.lastName" />\
</p>\
<p>\
<label>Email </label> <input type="email" id="emailId" name="emailId" ng-model="memberInfo.emailId" />\
</p>\
<p>\
<label>PAN Number </label> <input type="text" id="panNo" data-ng-minlength="10" name="panNo" ng-model="memberInfo.panNo" />\
</p>\
<p>\
<label>Mobile </label> <input type="text" data-ng-minlength="10" id="phoneNo" name="phoneNo" ng-model="memberInfo.phoneNo" />\
</p>\
</div> </div>',
replace: true,
transclude: false,
scope: {
memberInfo: '=memberInformation'
}
};
});