Get Input fields of a form equal to the value entered by the user - react-hooks

I want the input fields in form equal to the number entered by the user in react. But I am not sure how to do that I know that it will require looping but i can't figure out the approach.
Here is the code for my form
import React, { useEffect, useState } from "react";
import './roominfo.css';
import { ImBin } from 'react-icons/im';
import { useNavigate } from 'react-router-dom'
import RoomInfoService from '../services/RoomInfoService';
const RoomInfo = () => {
const [rooms, setRooms] = useState('');
const [updated, setUpdated] = useState(rooms)
const handleInput = (event) =>{
setRooms(event.target.value);
}
const handleClick = () =>{
setUpdated(rooms);
}
return (
<>
<div className='heading'>
<h1 style={{ marginBottom: '50px' }}>Enter Your PG Room Details</h1>
</div>
<form>
<div className="form-inline" style={{ marginBottom: '50px' }}>
<label>Enter total number of rooms: </label>
<input type="number" name="total_no_of_rooms" id= "myText" style={{ width: '90px'}} onChange={handleInput} />
<button type="button" className="button add" value={rooms} onClick={handleClick}>Get Rooms</button>
<p>Total Rooms:{updated}</p>
</div>
</form>
<div>
<form>
<div className="form-inline" style={{ borderBottom: '1px solid black' }}>
<label>Sharing Number</label>
<select id="shared_no" name="shared_no" title="no of shared rooms" >
<option value="">---Select---</option>
<option value="1">Single Sharing</option>
<option value="2">Two Bed Sharing</option>
<option value="3">Three Bed Sharing</option>
<option value="4">Four Bed Sharing</option>
<option value="5">Five Bed Sharing</option>
</select>
<label> No of Rooms:</label>
<input type="number" name="no_of_rooms" ></input>
<label> Rent per month:</label>
<input type="number" style={{ width: '100px' }} name="rent_per_month"></input>
<label> Total Capacity:</label>
<input type="number" style={{ width: '50px' }} name="total_capacity" ></input>
<label> Vacancy:</label>
<input type="number" style={{ width: '50px' }} name="vacancy"></input>
</div>
<div className="button-section">
<button className="button add" type="button">Add</button>
<button className="button submit" type="submit">Submit</button>
</div>
</form>
</div>
</>
)
}
export default RoomInfo
Can Please someone help me
Should I map it like
formValues.map((element,rooms) =>(
//form details)}
Also how to uniquely submit them. Thank you

Related

How do I show a message by opening a kendo popup?

In my form, there are 3 input values ​​in the period line. If all of them are empty or zero, I want to give a warning in the kendo popup before clicking the button.If a non-zero value is entered for any of them, it will not give an error.
3 input values for period in form
My code is as below :
<form id="formPlan" onsubmit="return hasValue()" class="form-horizontal form-group-sm" data-toggle="validator">
<div class="form-group required">
<label for="inPeriod" class="control-label col-xs-3">#ln.label_period:</label>
<div class="col-xs-4 input">
<div class="row">
<div class="col-xs-4">
<input type="number" id="inPeriod_day" name="Period" class="form-control" max="365" step="any" maxlength="2" style="width:100%">
</div>
<div class="col-xs-4">
<input type="number" id="inPeriod_hour" name="PeriodHour" class="form-control" max="23" step="any" maxlength="2">
</div>
<div class="col-xs-4">
<input type="number" id="inPeriod_minute" name="PeriodMinute" class="form-control" max="59" step="any" maxlength="2">
</div>
</div>
</div>
</form>
<div id="popup">Periods can't be blank!</div>
<script>
$("#popup").kendoPopup({
animation: {
close: {
effects: "fadeOut zoom:out",
duration: 300
},
open: {
effects: "fadeIn zoom:in",
duration: 300
}
}
});
function hasValue() {
var period = document.forms["formPlan"]["Period"].value;
var periodhour = document.forms["formPlan"]["PeriodHour"].value;
var periodminute = document.forms["formPlan"]["PeriodMinute"].value;
if (!period && !periodhour && !periodminute) {
$("#popup").data("kendoPopup").open();
return false;
}
return true;
}
</script>

Laravel Vue, pass data in form from component after submit

i need a little help about how to get values from a component that is in a form.
This is the form also a photo: form
`
<form #submit.prevent="form.patch(route('profile.update.account'))" class="mt-6 space-y-6">
<div>
<InputLabel for="adresa" value="Adresa" />
<TextInput
id="adresa"
type="text"
class="mt-1 block w-full"
v-model="form.adresa"
required
autofocus
autocomplete="adresa"
/>
<InputError class="mt-2" :message="form.errors.adresa" />
</div>
<DropdownCountries
id="tara"
v-model="form.tara"
required
autocomplete="Romania"
/>
<div class="flex items-center gap-4">
<PrimaryButton :disabled="form.processing">Save</PrimaryButton>
<Transition enter-from-class="opacity-0" leave-to-class="opacity-0" class="transition ease-in-out">
<p v-if="form.recentlySuccessful" class="text-sm text-gray-600">Saved.</p>
</Transition>
</div>
</form>
`
There is the component also a photo: dropdown
`
<template>
<div class="container">
<div class="row justify-content-center" style="margin: 20px 0px 20px 0px;">
<div class="col-md-8">
<div class="card">
<div class="card-body">
<div class="form-group">
<select name="tara" class='form-control' v-model='country' #change='getStates()'>
<option value='0' >Select Country</option>
<option v-for='data in countries' :value='data.id'>{{ data.name }}</option>
</select>
</div>
<div class="form-group">
<select name="judet" class='form-control' v-model='state' #change='getCities()'>
<option value='0' >Select State</option>
<option v-for='data in states' :value='data.id'>{{ data.name }}</option>
</select>
</div>
<div class="form-group">
<select name="oras" class='form-control' v-model='city'>
<option value='0' >Select City</option>
<option v-for='data in cities' :value='data.id'>{{ data.name }}</option>
</select>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data(){
return {
country: 180,
countries: [],
state: 0,
states: [],
city: 0,
cities: [],
}
},
methods:{
getCountries: function(){
axios.get('/api/tari')
.then(function (response) {
this.countries = response.data;
}.bind(this));
},
getStates: function() {
axios.get('/api/judete/' + this.country).then(function(response){
this.states = response.data;
}.bind(this));
},
getCities: function() {
axios.get('/api/orase/' + this.state).then(function(response) {
this.cities = response.data
}.bind(this));
}
},
created: function(){
this.getCountries()
}
}
</script>
`
My problem is that when i press Save button for submitting the form the values from dropdowns are not applied: response
I've been looking on internet for 2 hours can someone explain me why is that.
You should check this: v-model and child components?
This should answer your question. Let me know if you need more informaiton of how passing v-model values works.

I can't take matchId (f.k.) correctly in actionresult from a list in partial view with javascript

I am having a problem to getting correct matchId (foreign key) from partial view. There is 5 value and first one always coming true. Others always comes 0. But from console.log it always comes as true.
Can someone please help me? Many thanks.
here is my main page:
#model IEnumerable<match>
#{
ViewData["Title"] = "Home Page";
}
<head>
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
<style>
.accordion {
background-color: #eee;
color: #444;
cursor: pointer;
padding: 18px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 15px;
transition: 0.4s;
}
.active, .accordion:hover {
background-color: #ccc;
}
.panel {
padding: 0 18px;
display: none;
background-color: white;
overflow: hidden;
}
</style>
</head>
<body>
<h4>Title List:</h4>
<table class="table table-hover">
#foreach (var item in Model)
{
<tr>
<td id="item_title">
<button class="accordion" id="title" onclick="myFunction(#item.Id)">#Html.DisplayFor(modelItem => item.title)</button>
<div class="panel">
<p id="modelId" hidden>#Html.DisplayFor(modelItem => item.Id)</p>
<p>#Html.DisplayFor(modelItem => item.context)</p>
#await Html.PartialAsync("Create", item.Exams#*, Exams*#)
</div>
</td>
</tr>
}
</table>
<script>
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function () {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.display === "block") {
panel.style.display = "none";
} else {
panel.style.display = "block";
}
});
}
//document.getElementById("title").addEventListener("click", myFunction);
//document.querySelectorAll('.accordion').forEach(link => this.addEventListener('click', myFunction))
//let buttonn = document.querySelector("accordion");
function myFunction(val) {
//document.getElementById("matchId").value = document.getElementById("modelId").innerHTML;
document.getElementById("matchId").value = val;
console.log("value"+document.getElementById("matchId").value);
}
//document.getElementById("matchId").value = document.getElementById("modelId").innerHTML;
//console.log(document.getElementById("matchId").innerHTML);
//console.log(document.getElementById("matchId").value);
document.getElementById("match_title").value = document.getElementById("title").innerHTML;
//console.log(document.getElementById("match_title").value);
//function displayAnswer1() {
// if (document.getElementById('option-11').checked) {
// document.getElementById('block-11').style.border = '3px solid limegreen'
// document.getElementById('result-11').style.color = 'limegreen'
// document.getElementById('result-11').innerHTML = 'Correct!'
// }
// if (document.getElementById('option-12').checked) {
// document.getElementById('block-12').style.border = '3px solid red'
// document.getElementById('result-12').style.color = 'red'
// document.getElementById('result-12').innerHTML = 'Incorrect!'
// showCorrectAnswer1()
// }
// if (document.getElementById('option-13').checked) {
// document.getElementById('block-13').style.border = '3px solid red'
// document.getElementById('result-13').style.color = 'red'
// document.getElementById('result-13').innerHTML = 'Incorrect!'
// showCorrectAnswer1()
// }
// if (document.getElementById('option-14').checked) {
// document.getElementById('block-14').style.border = '3px solid red'
// document.getElementById('result-14').style.color = 'red'
// document.getElementById('result-14').innerHTML = 'Incorrect!'
// showCorrectAnswer1()
// }
//}
//function showCorrectAnswer1() {
// let showAnswer1 = document.createElement('p')
// showAnswer1.innerHTML = 'Show Corrent Answer'
// showAnswer1.style.position = 'relative'
// showAnswer1.style.top = '-180px'
// showAnswer1.style.fontSize = '1.75rem'
// document.getElementById('showanswer1').appendChild(showAnswer1)
// showAnswer1.addEventListener('click', () => {
// document.getElementById('block-11').style.border = '3px solid limegreen'
// document.getElementById('result-11').style.color = 'limegreen'
// document.getElementById('result-11').innerHTML = 'Correct!'
// document.getElementById('showanswer1').removeChild(showAnswer1)
// })
//}
</script>
</body>
Here is partial view page:
#model language_exam.Models.Exams
#using (Html.BeginForm("Create", "Home", FormMethod.Post))
{
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="card border-info">
<div class="card-header bg-info text-white">Question 1</div>
<div class="card-body">
<div>
<div class="form-group">
<input asp-for="matchId" class="form-control" type="number" id="matchId" name="matchId" hidden/>
<input hidden #*asp-for="match_title"*# id="match_title" name="match_title" />
</div>
<input asp-for="question_1_text" id="question_1_text" name="question_1_text" class="form-control" type="text" placeholder="input a question" />
<p>choose a radio button for determine a correct answer</p>
</div>
<div class="form-check" id='block-11'>
<label for='option-11'>
A)<input asp-for="answer_1_a_text" class="form-control" type="text" id="answer_1_a_text" name="answer_1_a_text" placeholder="input an answer" />
</label>
<span id='result-11'></span>
</div>
<div class="form-check" id='block-12'>
<label for='option-12'>
B)<input asp-for="answer_1_b_text" class="form-control" type="text" id="answer_1_b_text" name="answer_1_b_text" placeholder="input an answer" />
</label>
<span id='result-12'></span>
</div>
<div class="form-check" id='block-13'>
<label for='option-13'>
C)
<input asp-for="answer_1_c_text" class="form-control" type="text" id="answer_1_c_text" name="answer_1_c_text" placeholder="input an answer" />
</label>
<span id='result-13'></span>
</div>
<div class="form-check" id='block-14'>
<label for='option-14'>
D)
<input asp-for="answer_1_d_text" class="form-control" type="text" id="answer_1_d_text" name="answer_1_d_text" placeholder="input an answer" />
</label>
<span id='result-14'></span>
</div>
<div>
please click for choose the correct answer
<select asp-for="correct_1_answer" id="correct_1_answer" name="correct_1_answer">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
</div>
<a id='showanswer1'></a>
</div>
</div>
<br />
<div class="card border-info">
<div class="card-header bg-info text-white">Question 2</div>
<div class="card-body">
<div>
<input asp-for="question_2_text" class="form-control" type="text" id="question_2_text" name="question_2_text" placeholder="input a question" />
<p>choose a radio button for determine a correct answer</p>
</div>
<div class="form-check" id='block-11'>
<label for='option-11'>
A)
<input asp-for="answer_2_a_text" class="form-control" type="text" id="answer_2_a_text" name="answer_2_a_text" placeholder="input an answer" />
</label>
<span id='result-11'></span>
</div>
<div class="form-check" id='block-12'>
<label for='option-12'>
B)
<input asp-for="answer_2_b_text" class="form-control" type="text" id="answer_2_b_text" name="answer_2_b_text" placeholder="input an answer" />
</label>
<span id='result-12'></span>
</div>
<div class="form-check" id='block-13'>
<label for='option-13'>
C)
<input asp-for="answer_2_c_text" class="form-control" type="text" id="answer_2_c_text" name="answer_2_c_text" placeholder="input an answer" />
</label>
<span id='result-13'></span>
</div>
<div class="form-check" id='block-14'>
<label for='option-14'>
D)
<input asp-for="answer_2_d_text" class="form-control" type="text" id="answer_2_d_text" name="answer_2_d_text" placeholder="input an answer" />
</label>
<span id='result-14'></span>
</div>
<div>
please click for choose the correct answer
<select asp-for="correct_2_answer" id="correct_2_answer" name="correct_2_answer">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
</div>
<a id='showanswer1'></a>
</div>
</div>
<br />
<div class="card border-info">
<div class="card-header bg-info text-white">Question 3</div>
<div class="card-body">
<div>
<input asp-for="question_3_text" class="form-control" type="text" id="question_3_text" name="question_3_text" placeholder="input a question" />
<p>choose a radio button for determine a correct answer</p>
</div>
<div class="form-check" id='block-11'>
<label for='option-11'>
A)
<input asp-for="answer_3_a_text" class="form-control" type="text" id="answer_3_a_text" name="answer_3_a_text" placeholder="input an answer" />
</label>
<span id='result-11'></span>
</div>
<div class="form-check" id='block-12'>
<label for='option-12'>
B)
<input asp-for="answer_3_b_text" class="form-control" type="text" id="answer_3_b_text" name="answer_3_b_text" placeholder="input an answer" />
</label>
<span id='result-12'></span>
</div>
<div class="form-check" id='block-13'>
<label for='option-13'>
C)
<input asp-for="answer_3_c_text" class="form-control" type="text" id="answer_3_c_text" name="answer_3_c_text" placeholder="input an answer" />
</label>
<span id='result-13'></span>
</div>
<div class="form-check" id='block-14'>
<label for='option-14'>
D)
<input asp-for="answer_3_d_text" class="form-control" type="text" id="answer_3_d_text" name="answer_3_d_text" placeholder="input an answer" />
</label>
<span id='result-14'></span>
</div>
<div>
please click for choose the correct answer
<select asp-for="correct_3_answer" id="correct_3_answer" name="correct_3_answer">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
</div>
<a id='showanswer1'></a>
</div>
</div>
<br />
<div class="card border-info">
<div class="card-header bg-info text-white">Question 4</div>
<div class="card-body">
<div>
<input asp-for="question_4_text" class="form-control" type="text" id="question_4_text" name="question_4_text" placeholder="input a question" />
<p>choose a radio button for determine a correct answer</p>
</div>
<div class="form-check" id='block-11'>
<label for='option-11'>
A)
<input asp-for="answer_4_a_text" class="form-control" type="text" id="answer_4_a_text" name="answer_4_a_text" placeholder="input an answer" />
</label>
<span id='result-11'></span>
</div>
<div class="form-check" id='block-12'>
<label for='option-12'>
B)
<input asp-for="answer_4_b_text" class="form-control" type="text" id="answer_4_b_text" name="answer_4_b_text" placeholder="input an answer" />
</label>
<span id='result-12'></span>
</div>
<div class="form-check" id='block-13'>
<label for='option-13'>
C)
<input asp-for="answer_4_c_text" class="form-control" type="text" id="answer_4_c_text" name="answer_4_c_text" placeholder="input an answer" />
</label>
<span id='result-13'></span>
</div>
<div class="form-check" id='block-14'>
<label for='option-14'>
D)
<input asp-for="answer_4_d_text" class="form-control" type="text" id="answer_4_d_text" name="answer_4_d_text" placeholder="input an answer" />
</label>
<span id='result-14'></span>
</div>
<div>
please click for choose the correct answer
<select asp-for="correct_4_answer" id="correct_4_answer" name="correct_4_answer">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
</div>
<a id='showanswer1'></a>
</div>
</div>
<br />
<button type='submit' class="btn btn-info btn-block">Submit</button>
}
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Here is partial views actionresult:
[HttpPost]
public ActionResult Create(Exams exam)
{
Exams question_for_fill = new Exams();
question_for_fill.match = exam.match;
question_for_fill.Id = exam.Id;
question_for_fill.creator = User.Identity.Name;
question_for_fill.matchId = exam.matchId;
question_for_fill.question_1_text = exam.question_1_text;
question_for_fill.question_2_text = exam.question_2_text;
question_for_fill.question_3_text = exam.question_3_text;
question_for_fill.question_4_text = exam.question_4_text;
question_for_fill.correct_1_answer = exam.correct_1_answer;
question_for_fill.correct_2_answer = exam.correct_2_answer;
question_for_fill.correct_3_answer = exam.correct_3_answer;
question_for_fill.correct_4_answer = exam.correct_4_answer;
question_for_fill.creator = User.Identity.Name;
question_for_fill.answer_1_a_text = exam.answer_1_a_text;
question_for_fill.answer_1_b_text = exam.answer_1_b_text;
question_for_fill.answer_1_c_text = exam.answer_1_c_text;
question_for_fill.answer_1_d_text = exam.answer_1_d_text;
question_for_fill.answer_2_a_text = exam.answer_2_a_text;
question_for_fill.answer_2_b_text = exam.answer_2_b_text;
question_for_fill.answer_2_c_text = exam.answer_2_c_text;
question_for_fill.answer_2_d_text = exam.answer_2_d_text;
question_for_fill.answer_3_a_text = exam.answer_3_a_text;
question_for_fill.answer_3_b_text = exam.answer_3_b_text;
question_for_fill.answer_3_c_text = exam.answer_3_c_text;
question_for_fill.answer_3_d_text = exam.answer_3_d_text;
question_for_fill.answer_4_a_text = exam.answer_4_a_text;
question_for_fill.answer_4_b_text = exam.answer_4_b_text;
question_for_fill.answer_4_c_text = exam.answer_4_c_text;
question_for_fill.answer_4_d_text = exam.answer_4_d_text;
question_for_fill.created_date = DateTime.Now;
db.Exams.Add(question_for_fill);
db.SaveChanges();
return RedirectToAction("examslist");
}
when I click this first one, I can get correct value from actionresult in edit as matchId. But when I click the others matchId comes 0.
The reason why it worked for the first one but not other one is that you set <input asp-for="matchId" class="form-control" type="number" id="matchId" name="matchId" hidden/> in your partial view, and this will cause a result that there are several elements all have id matchId, then in your click event, it will always set value for the first one.
The solution is that you need to set matchId before load the view.
Here's my test model, I think you when can get Id before load the view, you can get matchId as well, so you don't need to set value in your click event. Or in other words, you don't need to use myFunction here.
public IActionResult Privacy()
{
List<PageModel> list = new List<PageModel>
{
new PageModel{ Id="1", context = "context1",title="title1",exams = new Exams{matchId="1",question_1_text="question1",answer_1_a_text="opt1a",answer_1_b_text="opt1b",correct_1_answer="answer1" } },
new PageModel{ Id="2", context = "context2",title="title2",exams = new Exams{matchId="2",question_1_text="question2",answer_1_a_text="opt2a",answer_1_b_text="opt2b",correct_1_answer="answer2" } },
new PageModel{ Id="3", context = "context3",title="title3",exams = new Exams{matchId="3",question_1_text="question3",answer_1_a_text="opt3a",answer_1_b_text="opt3b",correct_1_answer="answer3" } }
};
return View(list);
}
public class PageModel
{
public string Id { get; set; }
public string context { get; set; }
public Exams exams { get; set; }
public string title { get; set; }
}
public class Exams
{
public string matchId { get; set; }
public string question_1_text { get; set; }
public string answer_1_a_text { get; set; }
public string answer_1_b_text { get; set; }
public string correct_1_answer { get; set; }
}

Unable to bind the Radio button and checkbox data on button click in react hooks

I am having a form, When I submit the data it is going to server and I displayed the data in a table..
In the Table I am having edit button, When clicked on Edit button, the data should bind to the Form.
Here I am unable to bind the Inputs fields, but not the Radio and Checkboxes...
const Form = () => {
const [data, setdata] = useState({
"UserName" : "",
"dropDown" :"",
"gender" : "",
"checking" :""
})
const [update, setUpdate] = useState([])
const handleChange =(e)=>{
if(e.target.name !=="gender" && e.target.name !=="checking"){
setdata({...data,[e.target.name]:e.target.value});
}else if(e.target.name ==="gender"){
let allgenders = document.getElementsByName("gender");
allgenders.forEach((allradio)=>{
if(allradio.checked){
setdata({...data,[e.target.name]:e.target.value});
}
})
}else if(e.target.name ==="checking"){
let getallCheckboxes =[];
let allCheckboxes =document.getElementsByName("checking");
allCheckboxes.forEach((allchecks)=>{
if(allchecks.checked){
getallCheckboxes.push(allchecks.value)
}
});
setdata({...data,[e.target.name]:getallCheckboxes});
}
}
useEffect(() => {
getAllData();
}, [])
const handleSubmit=(e)=>{
e.preventDefault();
// setUpdate({...data,update});
// console.log(data);
axios.post('http://localhost:3000/users',data).then((res)=>{
// console.log("user added successfully");
getAllData();
handleClear();
})
}
const getAllData=()=>{
axios.get('http://localhost:3000/users').then((res)=>{
setUpdate(res.data);
})
}
const deleteUser=(dating)=>{
console.log(dating);
axios.delete('http://localhost:3000/users/'+dating.id).then(res=>{
getAllData();
})
}
This is the Funtions for Edit and update,Here I am able to bind the Inputs fields, but not the Radio and Checkboxes...
const editUser=(userData)=>{
setdata(userData)
}
const handleEdit=()=>{
console.log(data);
axios.put('http://localhost:3000/users/'+data.id,data).then(res=>{
getAllData();
})
}
return (
<React.Fragment>
<h1>LordShiva</h1>
<div className="container mt-3">
<div className="row">
<div className="col-md-6">
<div className="card">
<div className="card-header bg-success text-white">
<h4>Form</h4>
<form>
<div className="form-group">
<input type="text" className="form-control" placeholder='UserName' name="UserName" value={data.UserName} onChange={handleChange} />
</div>
<div className="form-group">
<input name="phone" className="form-control" placeholder='PhoneNumber' name="PhoneNumber" value={data.PhoneNumber} onChange={handleChange} />
</div>
<div className="form-group">
<input name="email" className="form-control" placeholder='Email' value={data.email} onChange={handleChange} />
</div>
<div className="form-group">
<select name="dropDown" value={data.dropDown} onChange={handleChange} className="form-control" >
<option value=""></option>
<option value="Reactjs">ReactJS</option>
<option value="JS">JavaScript</option>
<option value="csCSSs">CSS</option>
<option value="HTML">HTML</option>
</select>
</div>
<div class="form-row">
<div className="form-group col-md-6">
<label className="font-weight-bold">Gender : </label>
<span className="font-weight-bold" > Male <input type="radio" name="gender" value={data.gender} onChange={handleChange}/></span>
<span className="font-weight-bold" > Female <input type="radio" name="gender" value={data.gender} onChange={handleChange} /></span>
</div>
<div class="form-check col-md-6">
<label class="form-check-label" for="gridCheck">Course</label><br />
<input type="checkbox" value="HTML" name="checking" value={data.checking} onChange={handleChange} /> HTML <br />
<input type="checkbox" value="JavaScript" name="checking" value={data.checking} onChange={handleChange} /> JavaScript <br />
<input type="checkbox" value="ReactJS" name="checking" value={data.checking} onChange={handleChange} /> ReactJS <br />
<input type="checkbox" value="CSS" name="checking" value={data.checking} onChange={handleChange} /> CSS <br />
</div>
<div className="form-row">
<button className="btn btn-cyan" type="button" onClick={handleSubmit}>Submit</button>
<button className="btn btn-cyan" type="button" onClick={handleEdit}>UpdateData</button>
</div>
</div>
</form>
</div>
</div>
</div>
<div className="col-md-12">
<div className="card mt-5">
<div className="card-header blue-gradient text-white">
<h4>FormDetails</h4>
<div>
<div className="row mt-3">
<div className="col">
<div className="table table-hover table-striped text-center table-primary">
<thead className="bg-dark text-white font-weight-bold">
<tr>
<th>UserName</th>
<th>DropDownValue</th>
<th>Gender</th>
<th>CheckboxValue</th>
<th>EDIT</th>
<th>DELETE</th>
</tr>
</thead>
<tbody>
{
update.map(emp => {
return(
<tr>
<td>{emp.UserName} </td>
<td>{emp.gender}</td>
<td>{emp.checking}</td>
<td><button className="btn btn-cyan font-weight-bold" onClick={()=>{editUser(emp)}}>Edit</button></td>
<td><button className="btn btn-green font-weight-bold" onClick={()=>{deleteUser(emp)}}>Delete</button></td>
</tr>
)
})
}
</tbody>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</React.Fragment >
)
}
Change state to
const [data, setdata] = useState({
UserName: "",
dropDown: "",
gender: null,
checking: []
});
Update the handler to access the radio and checkbox id attributes
const handleChange = (e) => {
if (e.target.name !== "gender" && e.target.name !== "checking") {
setdata({ ...data, [e.target.name]: e.target.value });
} else if (e.target.name === "gender") {
let allgenders = document.getElementsByName("gender");
allgenders.forEach((allradio) => {
if (allradio.checked) {
setdata({ ...data, [e.target.name]: e.target.id }); // <-- grab input id
}
});
} else if (e.target.name === "checking") {
let getallCheckboxes = [];
let allCheckboxes = document.getElementsByName("checking");
allCheckboxes.forEach((allchecks) => {
if (allchecks.checked) {
getallCheckboxes.push(allchecks.id); // <-- grab checkbox id
}
});
setdata({ ...data, [e.target.name]: getallCheckboxes });
}
};
Update/add handleClear to reset the state
handleClear = () => {
setdata({
UserName: "",
dropDown: "",
gender: null,
checking: []
});
};
Add id properties and change the value prop to checked and pass a boolean value
<label className="font-weight-bold">Gender : </label>
<span className="font-weight-bold">
<label>
Male
<input
id="male"
type="radio"
name="gender"
checked={data.gender === "male"}
onChange={handleChange}
/>
</label>
</span>
<span className="font-weight-bold">
<label>
Female
<input
id="female"
type="radio"
name="gender"
checked={data.gender === "female"}
onChange={handleChange}
/>
</label>
</span>
...
<label class="form-check-label" for="gridCheck">
Course
</label>
<br />
<label>
<input
id="HTML"
type="checkbox"
name="checking"
checked={data.checking.includes("HTML")}
onChange={handleChange}
/>
HTML
</label>
<br />
<label>
<input
id="JavaScript"
type="checkbox"
name="checking"
checked={data.checking.includes("JavaScript")}
onChange={handleChange}
/>
JavaScript
</label>
<br />
<label>
<input
id="ReactJS"
type="checkbox"
name="checking"
checked={data.checking.includes("ReactJS")}
onChange={handleChange}
/>
ReactJS
</label>
<br />
<label>
<input
id="CSS"
type="checkbox"
name="checking"
checked={data.checking.includes("CSS")}
onChange={handleChange}
/>
CSS
</label>

Vue js vee validate password confirmation always false

I'm trying to use vee validate to verify the password using this code.
<div>
<input type="password"
placeholder="Password"
v-model="password"
v-validate="'required|min:6|max:35|confirmed'"
name="password" />
</div>
<div>
<span>{{ errors.first('password') }}</span>
</div>
<div>
<input type="password"
placeholder="Confirm password"
v-model="confirmPassword"
v-validate="'required|target:password'"
name="confirm_password" />
</div>
<div>
<span>{{ errors.first('confirm_password') }}</span>
</div>
But it always says The password confirmation does not match.
What went wrong in my code?
Your password input must have ref="password" - that's how vee-validate finds the target:
<input v-validate="'required'" ... ref="password"> (Thanks, Ryley).
confirmed:{target} - Input must have the same value as the target
input, specified by {target} as the target field’s name.
Also, there's an error with your Vee Validate syntax, change target: to confirmed:
v-validate="'required|target:password'"
should be
v-validate="'required|confirmed:password'"
Have a look at the basic example below, it will check for two things:
Does the second input field have any input value?
If yes, does the second input value match the first input value?
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
}
})
body {
background: #20262E;
padding: 15px;
font-family: Helvetica;
}
#app {
width: 60%;
background: #fff;
border-radius: 10px;
padding: 15px;
margin: auto;
}
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.17/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vee-validate/2.1.1/vee-validate.js"></script>
<script>
Vue.use(VeeValidate);
</script>
<div id="app">
<form id="demo">
<!-- INPUTS -->
<div class="input-group">
<h4 id="header"> Enter Password</h4>
<div class="input-fields">
<input v-validate="'required'" name="password" type="password" placeholder="Password" ref="password">
<input v-validate="'required|confirmed:password'" name="password_confirmation" type="password" placeholder="Password, Again" data-vv-as="password">
</div>
</div>
<!-- ERRORS -->
<div class="alert alert-danger" v-show="errors.any()">
<div v-if="errors.has('password')">
{{ errors.first('password') }}
</div>
<div v-if="errors.has('password_confirmation')">
{{ errors.first('password_confirmation') }}
</div>
</div>
</form>
</div>
Further reading: https://baianat.github.io/vee-validate/guide/rules.html#confirmed
Below code works for me: https://logaretm.github.io/vee-validate/advanced/cross-field-validation.html#targeting-other-fields
<template>
<ValidationObserver>
<ValidationProvider rules="required|password:#confirm" v-slot="{ errors }">
<input type="password" v-model="password" />
<span>{{ errors[0] }}</span>
</ValidationProvider>
<ValidationProvider name="confirm" rules="required" v-slot="{ errors }">
<input type="password" v-model="confirmation" />
<span>{{ errors[0] }}</span>
</ValidationProvider>
</ValidationObserver>
</template>
<script>
import { extend } from 'vee-validate';
extend('password', {
params: ['target'],
validate(value, { target }) {
return value === target;
},
message: 'Password confirmation does not match'
});
export default {
data: () => ({
password: '',
confirmation: ''
})
};
</script>
On Vee-validate 3.x.x another way of doing it is:
<template>
<ValidationObserver>
<ValidationProvider vid="password" rules="required" v-slot="{ errors }">
<input type="password" v-model="password" />
<span>{{ errors[0] }}</span>
</ValidationProvider>
<ValidationProvider name="confirm" rules="required|confirmed:password" v-slot="{ errors }">
<input type="password" v-model="confirmation" />
<span>{{ errors[0] }}</span>
</ValidationProvider>
</ValidationObserver>
</template>
<script>
import { extend } from 'vee-validate';
extend("confirmed", {
...confirmed,
message: "The password does not match",
});
export default {
data: () => ({
password: '',
confirmation: ''
})
};
</script>
Something import to notice is the vid prop on the first validation provider. It will NOT work without it.

Resources