How do I add an option from a select class to a list when chosen by the user? - class

I am trying to allow a user to add an option from a select class after pressing submit. As of now, it is adding the whole list. How do I go about allowing the user to select the specific option that they have chosen?
<div class="col alert alert-dark">
<h1 class="text-center">To Do App</h1>
</div>
<form class="form text-center col-8 ml-auto mr-auto alert alert-primary" id="newTaskForm">
<label for="toDo" class="toDo">What Color Do You Want To Add?</label>
<div class="row">
<select class="form-control col-8 mr-2" id="colorToAdd">
<option>Red</option>
<option>Yellow</option>
<option>Orange</option>
<option>Green</option>
<option>Blue</option>
</select>
<button type="submit" class="btn btn-success col-2" id="taskSubmit">Submit</button>
</div>
</form>
<hr class="col-8 ml-auto mr-auto mb-3">
<section class="text-center col-8 ml-auto mr-auto alert alert-dark" id="toDoList">
<h2>Tasks</h2>
<div id="colors">
</div>
window.addEventListener("load", () => {
const form = document.querySelector("#newTaskForm");
const input = document.querySelector("#colorToAdd");
const list_el = document.querySelector("#colors");
form.addEventListener("submit", (e) => {
e.preventDefault();
const colorElement = document.createElement("div");
colorElement.classList.add("newColor");
colorElement.type = "text";
colorElement.innerHTML = input.innerHTML;
list_el.appendChild(colorElement);
});
});

Related

Bootstrap 5 form validation - required & disabled

I currently have a disabled input box. I use the box to display the sum of two range sliders, where I update the value of the box via JavaScript.
I currently require that the value of the box equals 100 before allowing the form to be submitted. Is there a work-around where I can still disable the box, where it will still adopt the same Bootstrap style formatting (change color from red to green, etc) as a non-disabled box with the 'require' option?
Following a suggestion here, I've updated the code snippet below to almost be what I want. The only thing that I'd like to change, is to make 'rSum', the box that displays the sum, disabled (while still keeping all the validation formatting features). Ideally, I want this sum to adopt the validation feedback rather than the sliders, or other mutable input objects.
function checkSum() {
let currSum = parseInt(document.getElementById('rSum').value);
if (currSum != 100) {
document.getElementById('rSum').setCustomValidity('Must sum to 100%');
return false
} else {
document.getElementById('rSum').setCustomValidity('');
return true
}
}
function updateBoxes() {
const s1 = document.getElementById('range1');
const s2 = document.getElementById('range2');
let currSum = parseInt(s1.value) + parseInt(s2.value);
document.getElementById('rangeValue1').value = (s1.value)+"%";
document.getElementById('rangeValue2').value = (s2.value)+"%";
document.getElementById('rSum').value = (currSum)+"%";
}
// This last function is the original bootstrap validation example, modified to call 'checkSum()' instead
(function () {
'use strict'
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.querySelectorAll('.custom-validation')
// Loop over them and prevent submission
Array.prototype.slice.call(forms)
.forEach(function (form) {
form.addEventListener('submit', function (event) {
if (!checkSum()) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
}, false)
})
})()
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
<!-- JavaScript Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
<form class="custom-validation" novalidate>
<div class="mb-3 row">
<div class="form-group col-md-1">
<input class="form-control" type="text" id="rangeValue1" disabled>
</div>
<div class="form-group col-md-4 col-form-label">
<input type="range" class="form-range" min="0" max="100" step="5" id="range1" value="0" onchange="updateBoxes()" >
</div>
</div>
<div class="mb-3 row">
<div class="form-group col-md-1">
<input class="form-control" type="text" id="rangeValue2" disabled>
</div>
<div class="form-group col-md-4 col-form-label">
<input type="range" class="form-range" min="0" max="100" step="5" id="range2" value="0" onchange="updateBoxes()" >
</div>
</div>
<div class="mb-3 row">
<div class="form-group">
<input type="text" class="form-control text-center" id="rSum" placeholder="100%" required>
<div class="valid-feedback">
Looks good!
</div>
<div class="invalid-feedback">
Probabilities must add up to 100%
</div>
</div>
</div>
<div class="mb-3 row">
<div class="col-sm-6 offset-md-1">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
A couple of ways to do this. Here I use an example form with some inputs that can be used in the slider validation (one is a range slider but could be a simple number input also).
I set an event handler for those elements, associate them using data attributes and then; very verbosely and a bit ugly for clarity, use them in a function.
function checkSum(event) {
const fearRequird = this.fearNeed;
const myFear = event.target;
const associated = document.querySelector(myFear.dataset.related);
const result = this.sumEl;
const thisValue = parseInt(myFear.value);
const associatedValue = parseInt(associated.value);
let currSum = thisValue + associatedValue;
result.value = currSum;
let isValidSlider = currSum >= fearRequird;
result.classList.toggle("is-valid", isValidSlider);
result.classList.toggle("is-invalid", !isValidSlider);
let t = isValidSlider ? '' : `You Fear ${thisValue} and ${associatedValue} total ${currSum}. You need total ${fearRequird} fear`;
result.setCustomValidity(t);
result.closest('.form-group').querySelector('.invalid-feedback').textContent = t;
return isValidSlider;
}
(function() {
'use strict'
// Fetch all the forms we want to apply custom Bootstrap validation styles to
let forms = document.querySelectorAll('.needs-validation');
// Loop over them and prevent submission
Array.prototype.slice.call(forms)
.forEach(function(form) {
form.addEventListener('submit', function(event) {
if (!form.checkValidity()) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false)
});
const fearNeed = 100;
const myFears = document.querySelectorAll('.fear-factor');
const needs = {
fearNeed: fearNeed,
sumEl: document.querySelector('#rSum')
};
myFears.forEach((fearElement) => {
fearElement.addEventListener('change', checkSum.bind(needs), false);
});
})();
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
<!-- JavaScript Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
<form class="row g-3 needs-validation mx-1 my-2" novalidate>
<div class="form-group">
<input type="text" class="form-control text-center" id="rSum" placeholder="100%" required>
<div class="valid-feedback">
Looks good!
</div>
<div class="invalid-feedback">
Fears must add up to 100%
</div>
</div>
<div class="col-md-4">
<label for="validationCustomUsername" class="form-label">Fish Name</label>
<div class="input-group has-validation">
<span class="input-group-text" id="inputGroupPrepend">Fish</span>
<input type="text" class="form-control" id="validationCustomFishname" aria-describedby="inputGroupPrepend" required>
<div class="invalid-feedback">
Must catch a fish.
</div>
<div class="valid-feedback">
Looks like an good catch!
</div>
</div>
</div>
<div class="col-md-3">
<label for="validationCustomFearMet" class="form-label">Scary cats fear</label>
<div class="input-group has-validation">
<input type="number" class="form-control fear-factor" min="0" max="100" step="1" value="13" id="validationCustomFearMet" data-related="#customRange3" required />
<span class="input-group-text" id="inputGroupPrepend">%</span>
<div class="invalid-feedback">
Please provide scary cats fear as a percent 0-100.
</div>
<div class="invalid-feedback">
Please provide scary cats fear as a percent 0-100.
</div>
</div>
</div>
<div class="mx-1">
<label for="customRange3" class="form-label">Fear range</label>
<input type="range" class="form-range fear-factor" min="0" max="100" step="1" value="0" data-related="#validationCustomFearMet" id="customRange3">
</div>
<div class="col-12">
<button class="btn btn-primary" type="submit">Submit form</button>
</div>
</form>

Error setting form array only brings first value

I can't find the problem to set value in my form. It's only brings me the first value and the mistake is ERROR Error: Cannot find form control at index 1
at FormArray._throwIfControlMissing. Does anyone know what the right way would be like?
in my components
public setValueForm(): void {
const values = {
'_id': this.priceList._id,
'name': this.priceList.name,
'percentage' : this.priceList.percentage,
'allowSpecialRules' : this.priceList.allowSpecialRules,
'rules' : this.priceList.rules || []
};
this.priceListForm.setValue(values);
}
and my html
<div class="row tab-content">
<div formArrayName="rules" *ngFor="let rule of priceListForm.get('rules').controls; let i = index;">
<div [formGroupName]="i">
<div class="row">
<div class="form-group col-md-4">
<label for="category" class="control-label">Rubro:</label>
<select class="form-control" formControlName="category">
<option *ngFor="let category of categories"
[value]="category._id"
[disabled]="readonly">
{{category.description}}
</option>
</select>
</div>
<div class="form-group col-md-4">
<label for="make" class="control-label">Marca</label>
<select class="form-control" formControlName="make">
<option *ngFor="let make of makes"
[value]="make._id"
[disabled]="readonly">
{{make.description}}</option>
</select>
</div>
<div class="form-group col-md-3">
<label for="percentage" class="control-label">Porcentaje:</label>
<div class="input-group">
<input type="number" class="form-control" formControlName="percentage" name="percentage" id="percentage" [readonly]="readonly"/>
</div>
<div *ngIf="formErrors.percentage" class="alert alert-danger">
{{ formErrors.percentage }}
</div>
</div>
<div class="col-md-1">
<label class="control-label">Acción:</label>
<button type="button" class="btn btn-success btn-sm" (click)="addRule()">
<i class="fa fa-plus"></i>
</button>
<button type="button" class="btn btn-danger btn-sm" (click)="deleteRule(i)">
<i class="fa fa-trash-o"></i>
</button>
</div>
</div>
</div>
</div>
</div>
Resolved
let control = <FormArray>this.priceListForm.controls.rules;
this.priceList.rules.forEach(x => {
control.push(this._fb.group({
'_id': x._id,
'percentage': x.percentage,
'make' : x.make,
'category' : x.category
}))
})

Angular refresh page after disable DOM field form

I click Buy radio button, images upload field will be removed, but when i click submit, the page refresh. It works normally when I don't affect DOM
Please, explain me what happened ?
Here is my code
onSubmitPost() {
this.progress = true;
const fileList: FileList = this.event.target.files;
if (fileList.length > 0) {
const fileListLength = fileList.length;
const formData: FormData = new FormData();
formData.append('title', this.title);
formData.append('telephone', this.telephone);
formData.append('description', this.description);
formData.append('city', this.city);
if (this.isSell === true) {
for (let x = 0; x < fileListLength; x++) {
formData.append('thumbnail', fileList[x]);
}
}
const headers = new Headers();
headers.append('Accept', 'application/json');
headers.append('Authorization', 'clientId 7702919f7e72965');
this.http
.post('http://localhost:3000/api/post', formData, {
headers: headers
})
.map(res => res.json())
.subscribe(
data => {
this.Notificationervice.success('Success');
this.progress = false;
},
error => this.Notificationervice.error('Something wrong')
);
}
}
}
HTML Code
<div id="new-post" class="modal" materialize="modal">
<div class="modal-content">
<div class="row">
<form class="col s12" (submit)="onSubmitPost()" enctype="multipart/form-data">
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">web</i>
<input id="icon_prefix" type="text" class="validate" name="title" [(ngModel)]="title">
<label for="icon_prefix">Title</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">phone</i>
<input id="icon_telephone" type="tel" class="validate" name="telephone" [(ngModel)]="telephone">
<label for="icon_telephone">Telephone</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">mode_edit</i>
<textarea id="icon_prefix2" class="materialize-textarea" [(ngModel)]="description" name="description"></textarea>
<label for="icon_prefix2">Description</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">location_on</i>
<input type="text" id="autocomplete-input" class="autocomplete" materialize="autocomplete" [materializeParams]="[{'data': {'houston': null, 'Cali': null}}]"
[(ngModel)]="city" name="city">
<label for="autocomplete-input">City</label>
</div>
</div>
<div class="row">
<div class="col s6">
<p>
<input name="isSell" type="radio" id="buy" (change)="isSell = !isSell" [checked]="!isSell" />
<label for="buy">Buy</label>
</p>
</div>
<div class="col s6">
<p>
<input name="isSell" type="radio" id="sell" (change)="isSell = !isSell" [checked]="isSell" />
<label for="sell">Sell</label>
</p>
</div>
</div>
<div class="file-field input-field" *ngIf="isSell">
<div class="btn">
<span>Images</span>
<input type="file" multiple accept='image/*' name="post" (change)="onChange($event)">
</div>
<div class="file-path-wrapper">
<input class="file-path validate" type="text" placeholder="Upload one or more files">
</div>
</div>
<div class="modal-footer">
<input type="submit" class="modal-action modal-close waves-effect waves-green btn-flat" value="Submit">
</div>
</form>
</div>
</div>
</div>

Laravel REST API generating 500 internal server error during inserting data from controller to model

I have created a REST API for inserting data from Modal. After submitting my form I get data from my "store" controller. But when I call a Model function to insert that data to Database then I am getting 500 internal server error at console.
I have tried with two ways 1. Using Eloquent ORM
2. Using Query Builder
My controller:
public function store(Request $request)
{
$category_name = $request->category_name;
$category_entry_date = $request->category_entry_date;
$category_info = array(
'Supplier_Name' => $category_name,
'Supplier_Des' => $category_entry_date,
'Shop_Id' => 1
);
// Insert data into database
Product::CreateProductCategory($category_info);
return response()->json(['success_massege'=>'Category Added Successfully']);
}
Js:
$("#category_submit").click(function (e) {
event.preventDefault();
var category_name = $('#category_name_id').val();
var category_entry_date = $('#category_entry_date_id').val();
if (category_name && category_entry_date) {
$.post("/api/api/product_category", {category_name: category_name, category_entry_date: category_entry_date}).done(function (data) {
$('#category_name_id').val("");
$('#category_entry_date_id').val("");
var success_massege_dialogbox = '';
success_massege_dialogbox += '<div class="alert alert-success fade in">';
success_massege_dialogbox += '×';
success_massege_dialogbox += '<strong>Success!</strong>' + data.success_massege + '</div>';
$('#success_massege').append(success_massege_dialogbox);
});
}
else {
alert('Please give a category name and entry date');
}
});
Model:
static function CreateProductCategory($category_info){
DB::table('product_category_info')->insert($category_info);
}
View:
<div class="modal fade" id="addCategory" tabindex="-1" role="dialog" aria-labelledby="addCategoryLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="addCategoryLabel">Add Category</h4>
</div>
<form action="{{ route('product_category.store') }}" method="POST">
<div class="modal-body">
<div class="modal-body">
<div class="box-body">
<div class="row form-group">
<div class="col-md-3 form-level"></div>
<div class="col-md-9" id="success_massege"> </div>
</div>
<div class="row form-group">
<div class="col-md-3 form-level"><label>Category Name<b class="mandetory_star">*</b></label></div>
<div class="col-md-9" id="email-error-dialog">
{{Form::text('category_name','', $attributes = array('class' => 'form-control',
'id' => 'category_name_id',
'data-validation'=>'alphanumeric', 'data-validation-allowing'=>'-_',
'data-validation-error-msg'=>'Please Enter a Valid Category Name',
'data-validation-error-msg-container'=>'#email-error-dialog',
))}}
</div>
</div>
<div class="row form-group">
<div class="col-md-3 form-level"><label>Entry Date<b class="mandetory_star">*</b></label></div>
<div class="col-md-9" id="date-error-dialog">
{{Form::date('entry_date','', $attributes = array('class' => 'form-control',
'id' => 'category_entry_date_id',
'data-validation'=>'date',
'data-validation-error-msg'=>'Please Enter a Valid Date',
'data-validation-error-msg-container'=>'#date-error-dialog'))}}
</div>
</div>
</div><!-- /.box-body -->
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="category_submit" type="submit" class="btn btn-primary save-category"> Save category </button>
</div>
</form>
</div>
</div>
</div>

Form not submitting after form validation

I have a form in a modal window :
<div class="modal fade bs-example-modal-lg" id="vp" >
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Create Job</h4>
</div>
<div class="modal-body container-fluid">
<form id="create_job" method="post" action="?create">
<div class="form-group">
<div class="row">
<div class="col-md-4">
<input type="text" class="form-control" placeholder="Job number - Jxxxx" name="job_number">
</div>
<div class="col-md-4">
<input type="text" class="form-control" placeholder="Part number - xxxxxx" name="part_number">
</div>
<div class="col-md-2"><p class="form-control-static text-right"><b>Cable length (m):</b></p></div>
<div class="col-md-2">
<input type="text" class="form-control" placeholder="Cable" value="06" name="cable">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" name="submitButton" class="btn btn-primary">Submit</button></form>
</div>
</div>
</div>
</div>
This is the validation js:
$(document).ready(function() {
$('#create_vpf_job').formValidation({
framework: 'bootstrap',
excluded: ':disabled',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
job_number: {
validators: {
notEmpty: {
message: ' '
}
}
},
part_number: {
validators: {
notEmpty: {
message: ' '
}
}
},
cable: {
validators: {
notEmpty: {
message: ' '
}
}
}
}
});
});
I've look online for same problems but I haven't found a solution. The submit button doesn't submit. I'm using formvalidation.io for validation and nothing from their docs helped me.
Also tried adding with no luck
$('#create_job').submit();
Your HTML is bad formatted, and the form is closing after the container div closes, so the submit button doesn't know what to submit. Change it to:
<div id="vp" class="modal fade bs-example-modal-lg">
<div role="document" class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 id="myModalLabel" class="modal-title">Create Job</h4>
</div>
<div class="modal-body container-fluid">
<form action="?create" method="post" id="create_job">
<div class="form-group">
<div class="row">
<div class="col-md-4">
<input type="text" name="job_number" placeholder="Job number - Jxxxx" class="form-control" />
</div>
<div class="col-md-4">
<input type="text" name="part_number" placeholder="Part number - xxxxxx" class="form-control" />
</div>
<div class="col-md-2">
<p class="form-control-static text-right">
<b>Cable length (m):</b>
</p>
</div>
<div class="col-md-2">
<input type="text" name="cable" value="06" placeholder="Cable" class="form-control" />
</div>
</div>
</div>
<div class="modal-footer">
<button data-dismiss="modal" class="btn btn-default" type="button">Close</button>
<button class="btn btn-primary" name="submitButton" type="submit">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
And it will work. On this plunkr you can check that it's giving a bad-request response, which is good news, because it means the request is being done, and so, the form is being submitted once the correction made