This is my html code: this is my input filed where i have declare input type and id.
<div class="col-lg-4 col-sm-6">
<div class="form-group">
<div>
<input id="SkillsAndInterests" class="form-control" type="text"
name="SkillsAndInterests" style="width:286px;height:35px;" />
</div>
</div>
</div>
This is my js code :
vm.CommunityMembersAdditionalInfoData.SkillsAndInterests = vm.skillsandinterestarray;
$('#SkillsAndInterests').tagSuggest({
data: vm.CommunityMembersAdditionalInfoData.SkillsAndInterests,
sortOrder: 'name',
maxDropHeight: 200,
name: 'SkillsAndInterests'
});
And this is my reset function: where i am unable reset filed
vm.ResetSerachMembers = function () {
$("#SkillsAndInterests").val('');
}
And this is my button where i am calling reset function:
<button class="btn btn-danger" ng-disabled="data.isMembersLoading"
ng-click="data.ResetSerachMembers();" type="button">
Reset
</button>
Related
I am trying to validate the length of ID value in userForm in Angular14, I tried for
if(this.userForm.value.id.length < 6 || this.userForm.value.id.length >9){
console.log("length error")
}
But this is not giving the expected result. the above snippet is working for != and = only.
How can I validate this value for the range.
Adding the .ts and .html snippets for the better understanding.
component.ts
userSubmit(){
console.log(this.userForm.get('image').value);
console.log(this.userForm.value);
const formData = new FormData();
formData.append('image', this.images);
formData.append('id', this.userForm.value.id);
formData.append('des', this.userForm.value.des);
formData.append('name', this.userForm.value.name);
if(this.userForm.value.id.length < 6 || this.userForm.value.id.length > 9){
console.log("length error")
}
component.html
<div class="container">
<div *ngIf="errorMsg" class="alert alert-danger alert-dismissible fade show" role="alert">
<strong>{{errorMsg}}</strong>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<form [formGroup]="userForm" >
<div class="col-lg-4 mt-2" >
<label>Employee ID:</label>
<input type="number" class="form-control" formControlName="id" [(ngModel)]="id">
</div>
<div class="col-lg-4 mt-2" *ngIf="!getParamId" >
<button class="btn btn-primary btn-sm" [disabled]="!name || !des ||!photo||!id" (click)="userSubmit()">
Submit!!
</button>
</div>
<div class="col-lg-4 mt-2" *ngIf="getParamId" >
<button class="btn btn-dark btn-sm" (click)="userUpdate()" >
Update
</button>
</div>
</form>
</div>
From what I understand from your question, you are performing the validation for id with the length within a range.
The problem is currently your id is not a string, but it is a number.
<input type="number" class="form-control" formControlName="id" [(ngModel)]="id">
Hence you can't use .length as this property doesn't exist in the number value.
Change the <input> element from type="number" to type="text" or without type. (By default type is text).
Since you are using the Reactive form, you don't need the [(ngModel)].
<input type="text" class="form-control" formControlName="id" />
Add Validators.minLength() and Validators.maxLength() validators to id form control.
import { Validators } from '#angular/forms';
this.userForm = this.fb.group({
id: [
'',
[Validators.required, Validators.minLength(6), Validators.maxLength(9)],
],
// Following controls
});
Note: If you want the id input to be numeric characters, you need Validators.pattern():
Validators.pattern('[0-9]+')
Or validate with the length as well, so the Validators.minLength() and Validators.maxLength() can be omitted.
Validators.pattern('[0-9]{6,9}')
To disable the submit button when there is any control(s) that failed the validation:
<button
class="btn btn-primary btn-sm"
[disabled]="idHasError /* or other form controls */"
(click)="userSubmit()"
>
Submit!!
</button>
And implementing the getter.
get idHasError() {
return this.userForm.controls.id.errors;
}
Implement the getter method(s) for the rest form control(s) to return a boolean value that the form control has errors or not.
Demo # StackBlitz
I'm using below FormulateForm to have input field with the submit button:
<div class="col-12 col-md-3">
<FormulateInput
name="product_codes"
label="Style number"
placeholder="Style number"
/>
</div>
<div class="col-12 col-md-3">
<button
type="button"
class="btn btn-primary"
#click="syncProducts"
>
Sync
</button>
</div>
I want to sent this input data to BE as an array:
<script>
export default {
name: 'SyncProducts',
data() {
return {
styleCodes: [],
}
},
}
</script>
But with this code, instead of Array of String, it sends it as a String.
What's happening:
I have a form in a modal where the user inputs data. The form is only populated with data when opening the modal, not after submission. The form's action InsertLabelDefectRobotsT returns a return NoContent(); When the form is submitted the modal stays open and I clear the input values to allow new submissions.
Now, I have two dropdowns (Célula and Defeito), when changing the first one the visible options of the second one will change. My problem is that after submitting a set of values, if I change the first dropdown value and then change it back the option I submitted before disappears (this only happens if I submit the form and only the option I submitted disappears).
I have no clue why this is happening... and this is a very specific question, but if you have any leads I appreciate it.
Modal
Modal.html
<form id="formDefectsRobots" method="post" asp-action="InsertLabelDefectRobotsT" asp-controller="Labels" onsubmit="onSubmit(this);onSubmit2()">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-row">
<div class="form-group col-md-12">
<label asp-for="CellId"></label>
<select id="select1DefectsRobots" asp-for="CellId" asp-items="Model.Cells" class="custom-select">
<option value="">--</option>
</select>
<span asp-validation-for="CellId" class="text-danger"></span>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-12">
<label asp-for="DefectName"></label>
<select id="select2DefectsRobots" asp-for="DefectName" asp-items="Model.Defects" class="custom-select defectsSelect">
<option value="">--</option>
</select>
<span asp-validation-for="DefectName" class="text-danger"></span>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-12">
<label asp-for="Quantity"></label>
<input class="form-control form-control-sm numpad defectsSelect" asp-for="Quantity" />
<span asp-validation-for="Quantity" class="text-danger"></span>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-12">
<label asp-for="Details"></label>
<input type="text" class="form-control form-control-sm defectsSelect" asp-for="Details" />
<span asp-validation-for="Details" class="text-danger"></span>
</div>
</div>
<div class="row mb-3">
<div class="col-md-12">
<button type="button" class="btn btn-dark" data-dismiss="modal"><i class="fas fa-arrow-left mr-2"></i>Cancelar</button>
<button type="button" class="btn btn-success" onclick="doSomething();submitDefectsRobots(this)"><i class="fas fa-play-circle mr-2"></i>Introduzir Defeito</button>
</div>
</div>
</form>
<script>
//Changes second Select based on the first
$("#select1DefectsRobots").change(function () {
if ($(this).data('options') === undefined) {
//Taking an array of all options-2 and kind of embedding it on the select1
$(this).data('options', $('#select2DefectsRobots option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#select2DefectsRobots').html(options);
});
//This changes the val of the select option to it's text.
function doSomething() {
$('#select2DefectsRobots option:selected').val($('#select2DefectsRobots option:selected').text());
};
//Clear some values
function onSubmit2() {
setTimeout(function () {
$('.defectsSelect').val('');
}, 1000);
};
</script>
script.js
function submitDefectsRobots(button) {
$form = $('#formDefectsRobots');
if ($form.valid()) {
Swal.fire({
title: "Inserir Defeito?",
text: "Esta acção irá inserir um novo registo de defeito.",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
cancelButtonText: 'Cancelar',
confirmButtonText: 'Confirmar',
animation: false,
focusCancel: true
}).then((willSubmit) => {
if (willSubmit.value) {
$form.submit();
hideOverlay();
setTimeout(function () {
toastr.success("Defeitos Inseridos");
}, 1000);
}
})
}
}
Before submission (two "defeito" options appear on 3.9.V and one on 3.9.Y)
After submission on 3.9.V (Values Cleared, Still two options on 3.9.V)
After submission (Changed to "Célula" 3.9.Y and when changing back to 3.9.V only one "defeito" option appears now)
I found it: since I was changing the val of the selected option on submit, it would not work on the next time.
//This changes the val of the select option to it's text.
function doSomething() {
$('#select2DefectsRobots option:selected').val($('#select2DefectsRobots option:selected').text());
};
I've setup a view which contains a search form:
<form>
<input type="hidden" id="product_id" value="{{$tour->id}}">
<div class="form-group col-md-4">
<label>Date:</label>
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="text" class="form-control pull-right" id="start" placeholder="Start Date">
</div>
</div>
<div class="form-group col-md-4">
<label>End:</label>
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="text" class="form-control pull-right" id="end" placeholder="End Date">
</div>
</div>
<div class="form-group col-md-4" id="dateprice-search">
<label></label>
<button type="submit" class="btn" id="btn-search" >
Search
</button>
</div>
The below is the ajax code to handle the request of the form:
$(document).ready(function() {
$('#dateprice-search').on('click', '#btn-search', function() {
$.ajax({
type: 'post',
url: '/date-price',
data: {
'_token': $('input[name=_token]').val(),
'product_id': $("#product_id").val(),
'start': $("#start").val(),
'end': $("#end").val()
},
success: function(data) {
$('.shadow-z-1').show();
$('.shadow-z-1').append("<tr class='liquid-row><td>" + data.start + "</td><td>"+ data.end + "</td><td>" + data.end + "</td><td><a class='btn-m btn btn-m-success'>Available</a></td></tr>");
}
});
});
});
Route:
Route::post('/date-price','GetPublicController#datePrice')
->name('searchDate');
And finally method in controller to give the results:
public function datePrice(Request $request){
$start = $request->start;
$end = $request->end;
$dates = DatePrice::where('tour_id','=',$request->product_id)
->whereBetween('start', array($request->start, $request->end))
->whereBetween('end', array($request->start, $request->end))
->get();
return response()->json($dates);
}
At first the url looks like this before submitting the form http://localhost:8000/trips/popular/trekking/test and url becomes http://localhost:8000/trips/popular/trekking/test? after clicking the search button. Console section of inspect element shows no error in script. What mistake I had made over here ?
It mean your form submiting to same page due to type="submit"
1) change to type="button"
<button type="button" class="btn" id="btn-search" >
2) Here click event should be for button not to div so change the selector and add e.preventDefault(); in jquery to prevent the default submit .
$('#btn-search').on('click', '#btn-search', function() { e.preventDefault(); });
note :
1st : your action attribute missing so form will be submit same page .
2nd : your method attribute missing so it will take default GET method
You have given button type as submit, either remove it as
<button type="button" class="btn" id="btn-search" >
Search
</button>
or use the jquery preventDeafult() function to prevent the default behavior of submit button i.e form submit in your button click event as
$(document).ready(function() {
$('#dateprice-search').on('click', '#btn-search', function(e) {
e.preventDefault();
//your ajax code
});
});
I'm new to MVC and AJAX so this is probably a simple mistake I am making but using the code below, I am getting the following error trying to getElementById("txtCount").value:
<div class="row">
<div class="col-sm-4">
<div class="panel panel-primary">
<div class="panel-heading">
<h5 style="font-weight:bold;">Parameters</h5>
</div>
<div class="panel-body" id="parameters">
<form class="form-horizontal" id="frmParameters">
<div class="form-group">
<label for="txtCount" class="col-sm-4 col-form-label">Repeat</label>
<input type="number" min="1" max="100" step="1" id="txtCount" value="#Model.Count" class="input-sm col-sm-7" />
</div>
#if (Model.Grammar.SupportsMaxLength)
{
<div class="form-group">
<label for="txtMaxLength" class="col-sm-4 col-form-label">Max Length</label>
<input type="number" min="1" max="100" step="1" id="txtMaxLength" value="#Model.MaxLength" class="input-sm col-sm-7" />
</div>
}
<button name="btnGenerate" class="btn btn-primary pull-right" onclick="Generate();">Generate</button>
</form>
</div>
</div>
</div>
</div>
<script>
function Generate() {
var data = { count: document.getElementById("txtCount").value, maxLength: document.getElementById("txtMaxLength").value };
}
</script>
If I change:
var data = { count: document.getElementById("txtCount").value, maxLength: document.getElementById("txtMaxLength").value };
to:
var data = { count: document.getElementById("txtCount").value};
I don't get the error anymore.
Your code looks fine. I think you are getting the error when your code tries to execute this line
document.getElementById("txtMaxLength").value
Because in your view you are rendering this element when some if condition returns true. So it is possible that your view does not have this input element at all and you are trying to read that! (Check the view source of the page and search for input with txtMaxLength id.
The best solution is to check it exists before trying to read the value.
var data = {
id: "#Model.Id",
count: document.getElementById("txtCount").value,
maxLength: null // or whatever default value you want
};
if (document.getElementById("txtMaxLength")) {
data2.maxLength = document.getElementById("txtMaxLength").value;
}
Or if you are using jQuery library, it is easy
var data = {
id: "#Model.Id",
count: $("#txtCount").val(),
maxLength:$("#txtMaxLength").val()
};