apply validation on ko.computed using knockout.js - validation

i just created a scenario , the thing i wanted, can you check out this fiddle jsfiddle.net/5PRMe/393. i want to validate this, some piece of code i used here, but comment it.kindly check this.
Bascially i am follow this link https://github.com/knockout/knockout/wiki/View-Add-Edit-Delete-Design-Pattern (full code of this link is at the bottom of the page), to create my code, but i want knockout validation, with proper messages, but i did't understand how to do validation if we have with binding with computedObservable, can anyone help me to sort out the problem?
var baseModel = function () {
this.id = ko.observable(0);
this.name = ko.observable("").extend({ required: true });
this.title = ko.observable(undefined).extend({
required: { message: "You must select title" },
});
this.email = ko.observable("").extend({ required: true });
this.phone = ko.observable("").extend({ required: true });
this.mobile = ko.observable('');
this.streetAddress = ko.observable('');
this.city = ko.observable('');
this.state = ko.observable('');
this.zipCode = ko.observable('');
this.fax = ko.observable('');
this.description = ko.observable('');
this.editSelectedItemErrors = ko.validation.group([this.name,this.accountId,this.title,this.gender,this.email,this.phone,this.country]);
}
var viewModel = function () {
var self = this;
self.editSelectedItem = ko.observableArray('');
var mappedItems = ko.mapping.fromJS(new baseModel());
self.editSelectedItem(mappedItems);
self.saveContact = function (form) {
if (baseModel.editSelectedItemErrors().length === 0) {
// save data
}
else{
baseModel.editSelectedItemErrors.showAllMessages();
}
}
self.SelectedRecord = ko.computed(function () {
var selected = self.editSelectedItem();
selected.selectedOption;
//selected.selectLanguage;
selected.streetAddress;
var result = (selected);
console.log(result.length);
if (result != null) {
result = ko.toJS(result);
var observable = ko.mapping.toJS(result);
//console.log(observable);
return observable;
} else {
return new baseModel();
};
}, self);
}
var contactModel = new viewModel();
$(function () {
ko.validation.init({
registerExtenders: true,
messagesOnModified: true,
insertMessages: true,
parseInputAttributes: true,
messageTemplate: null,
decorateElement: true,
grouping: { deep: true, observable: true, live: true }
}, true);
ko.applyBindings(contactModel);
});
<div id="divContact" class="flt w100 space form" data-bind="with : SelectedRecord()">#*<!-- ko with : SelectedRecord -->*#
<div class="row">
<label>
First Name</label>
<span>
<input id="Name" name="Name" type="text" data-bind="value : name,uniqueName: true" class="field required" placeholder="Name" />
</span>
</div>
<div class="row">
Email</label>
<span>
<input id="Email" type="text" data-bind="value : email,uniqueName: true" class="required field" placeholder="Email" /></span>
</div>
<div class="row">
<label>
Phone</label>
<span>
<input id="Phone" type="text" data-bind="value : phone,uniqueName: true" class="field" placeholder="Phone" /></span>
<label>
Mobile</label>
<span>
<input id="Mobile" type="text" data-bind="value : mobile,uniqueName: true" class="field" placeholder="Mobile" /></span>
</div>
<div class="row">
<label>
Street Adress</label>
<span>
<input id="Street" type="text" data-bind="value : streetAddress,uniqueName: true" class="field" placeholder="Street" /></span>
<label>
City</label>
<span>
<input id="City" type="text" data-bind="value : city,uniqueName: true" class="field" placeholder="City" /></span>
</div>
<div class="row">
<label>
State</label>
<span>
<input id="State" type="text" data-bind="value : state,uniqueName: true" class="field" placeholder="State" /></span>
<label>
Zip Code</label>
<span>
<input id="Zip" type="text" data-bind="value : zipCode,uniqueName: true" class="field" placeholder="Zip Code" /></span>
</div>
<div class="row">
Fax</label>
<span>
<input id="Fax" type="text" data-bind="value : fax,uniqueName: true" class="field" placeholder="Fax" /></span>
</div>
<div class="row">
<label>
Description</label>
<span>
<textarea class="input-field " data-bind="value: description,uniqueName: true"></textarea></span>
</div>
<div class="row">
<input data-bind="click: function() { contactModel.saveContact($data,0);}" type="submit" value="Save" class="btn"/>
<input type="button" class="btn" value="Cancel" data-bind="click: function() { contactModel.cancelCreate($data,0);}">
</div>

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>

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>

How to bind the formControlName to static radio-button value

I am new to the reactive forms, here I am trying to bind the form control name to the static radio button, but radio button depends on the loop where it keeps repeating based on the number of loops.
When I bind the radio button to the form control name then this is the issue I am facing
If i try to select the one value "good" then all button are selected with value "good"
Here is the code for the above issue:-
import {
Component
} from '#angular/core';
import {
FormBuilder,
FormGroup,
Validators
} from '#angular/forms';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [FormBuilder]
})
export class AppComponent {
name = 'Angular';
ipdForm: FormGroup;
IpdData = [];
response = {
"data": [{
"id": 19,
"question" : "question 1",
"options": "radio"
},
{
"id": 20,
"question" : "question 2",
"options": "radio"
},
{
"id": 33,
"question" : "question 3",
"options": "text"
},
{
"id": 34,
"question" : "question 4",
"options": "text"
},
]
}
constructor(
private fb: FormBuilder,
) {}
ngOnInit() {
this.getIpdFormData();
this.filterDefaultValues();
}
getIpdFormData() {
this.IpdData = this.response.data;
}
filterDefaultValues() {
this.ipdForm = this.fb.group({
ratingForm: [''],
question: [],
});
}
ipdFeedback() {
}
html
<form class="custom-form" [formGroup]="ipdForm" (submit)="ipdFeedback();">
<div class="form-group" *ngFor="let d of IpdData;let i = index">
<label for="dob" class="control-label">
{{d.question }}
<sup class="custom-required">*</sup>
</label>
<label class="radio-inline custom-radio">
<div *ngIf="d.options == 'radio'">
<div >
<label class="radio-inline custom-radio">
<input class="radio-text" formControlName="ratingForm" type="radio" value="Poor" />
<span class="radio-text">Poor</span>
</label>
<label class="radio-inline custom-radio">
<input class="radio-text" formControlName="ratingForm" type="radio" value="Fair" />
<span class="radio-text">Fair</span>
</label>
<label class="radio-inline custom-radio">
<input class="radio-text" formControlName="ratingForm" type="radio" value="Good" />
<span class="radio-text">Good </span>
</label>
</div>
</div>
<div *ngIf="d.options == 'text'">
<textarea placeholder="Comments" formControlName="ratingForm" type="text" class="form-control" tabindex="14"></textarea>
</div>
</label>
</div>
<button type="submit"></button>
</form>
here when I bind the value to form control name then all radio button is selected for that particular value
How to send the value of radio button and also id of that question to the ipdFeedback function.
This is required array
array [{
value : "good"
questionId : 20
}]
Your formControlName is inside a ngfor. It is same name for every index.That is why the value changed in every Index.You need to create FormArray.
ngOnInit() {
this.ipdForm = this.fb.group({
IpdData: this.fb.array([])
})
}
get ipdFormArray() {
return this.ipdForm.get('IpdData') as FormArray;
}
filterDefaultValues() {
for (let i = 0; i < this.IpdData.length; i++) {
const datas = this.fb.group({
ratingForm: [''],
question: [IpdData[i].question],
});
this.ipdFormArray.push(datas);
}
}
change your html like below; ngfor for reacctive form array and add formarray name
<form class="custom-form" [formGroup]="ipdForm"
(submit)="ipdFeedback();">
<div formArrayName="IpdData">
<div class="form-group" *ngFor="let d of ipdFormArray.controls;let i = index" [formGroupName]="i">
<label for="dob" class="control-label">
{{d.question }}
<sup class="custom-required">*</sup>
</label>
<label class="radio-inline custom-radio">
<div *ngIf="IpdData[i].options == 'radio'">
<div >
<label class="radio-inline custom-radio">
<input class="radio-text" formControlName="ratingForm" type="radio" value="Poor" />
<span class="radio-text">Poor</span>
</label>
<label class="radio-inline custom-radio">
<input class="radio-text" formControlName="ratingForm" type="radio" value="Fair" />
<span class="radio-text">Fair</span>
</label>
<label class="radio-inline custom-radio">
<input class="radio-text" formControlName="ratingForm" type="radio" value="Good" />
<span class="radio-text">Good </span>
</label>
</div>
</div>
<div *ngIf="IpdData[i].options == 'text'">
<textarea placeholder="Comments" formControlName="ratingForm" type="text" class="form-control" tabindex="14"></textarea>
</div>
</label>
</div>
<button type="submit"></button>
You will get the values in this.ipdFormArray.value

how to highlight invalid section β€” twitter bootstrap/jquery/validate plugin

I have a form in twitter bootstrap:
<div class="form-div">
<form id="fvujq-form1" method="post" action="">
<div class="control-group name">
<fieldset>
<label>Name *</label>
<input type="text" name="name">
</fieldset>
</div>
<div class="control-group email">
<fieldset>
<label>E-Mail *</label>
<input type="text" name="email">
</fieldset>
</div>
<div class="control-group comment">
<fieldset>
<label>Your comment *</label>
<textarea name="comment"></textarea>
</fieldset>
</div>
<button class="btn btn-primary">Submit</button>
</form>
</div>
and this is how I validate it with bassistance Validate plugin:
$(document).ready(function() {
$("#fvujq-form1").validate({
submitHandler:function(form) {
SubmittingForm();
},
success: function(label) {
label.html("βœ”").addClass("valid");
},
onfocusout: function(element) { $(element).valid(); },
focusInvalid: false,
highlight: function(element, errorClass, validClass) {
$('.form-div').find('.control-group' + element.id).addClass('error');
},
unhighlight: function(element, errorClass, validClass) {
$('.form-div').find('.control-group' + element.id).removeClass('error');
},
errorClass: "help-inline",
errorElement: "strong"
I want to add .error to the div currently validated, but this code adds class to every .control-group occurence, not only validated one :(
thx 4 yr help.
JSFiddler Example
This will validate as you leave each field or when you hit the submit button all fields that meet the rules will present errors.
HTML
<form action="" id="fvujq-form1" class="form-horizontal">
<fieldset>
<div class="control-group">
<label class="control-label" for="name">Your Name</label>
<div class="controls">
<input type="text" class="input-xlarge" name="name" id="name">
</div>
</div>
<div class="control-group">
<label class="control-label" for="email">Email Address</label>
<div class="controls">
<input type="text" class="input-xlarge" name="email" id="email">
</div>
</div>
<div class="control-group">
<label class="control-label" for="comment">Comment</label>
<div class="controls">
<input type="text" class="input-xlarge" name="comment" id="comment">
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</fieldset>
</form>
Javascript
$(document).ready(function(){
$('#fvujq-form1').validate(
{
rules: {
name: {
minlength: 2,
required: true
},
email: {
required: true,
email: true
},
comment: {
minlength: 2,
required: true
},
},
highlight: function(element) {
$(element).closest('.control-group').removeClass('success').addClass('error');
},
success: function(element) {
element
.text('OK!').addClass('valid')
.closest('.control-group').removeClass('error').addClass('success');
}
});
});

Resources