jQuery disable submit button if text box contains these variables - textbox

How I can strip out the variables listed below from within a textbox (input) that if a user tries to type a URL i.e these variables:
"http://"
"www."
".com"
".co.uk"
If any of the variables above exist in the textbox on keyup the submit button gets disabled or/and it removes/strips out the variables above.
Is this possible? I've tried doing it using Charcodes, but I face the problem that I would like the user to still use '.; (full-stops) etc
Can somebody help?
Thanks,

Here you go!
Demo
$("#myinput").keyup(function()
{
var a = ["http://", "www.", ".com", ".co.uk"]; //Add the substrings
a.forEach(function(k)
{
if($("#myinput").attr("value").indexOf(k) > -1)
{
alert('Found!'); //Do something
return true;
}
else
{
return false;
}
});
});
Every time the user types a char, it checks for the string in array a. If the substring is found, it popups an alert message.
Using blur it will check for the string only when the user go outs of the input box (its more efficient using blur, but you can use this way if you want to check few strings and the input value is not too long).

Try this,
$("#textboxId").blur(function (event) {
var text = event.target.val();
if(text.contains("www")) {
$("submitBtnId").prop('disabled', true);
}
});

Related

Adding new line to top of Grid with data does not display prefilled values in non-editable columns (vaadin7)

Let's say I load data into a Grid. That works perfectly, everything is displayed. I can see it just fine, even after I call editItem(objectId); to edit data for any given line in the Grid.
Then let's say I have a button that adds a new line with mostly empty elements. In other words, the corresponding bean is mostly empty except for some default values. For some reason this behaves weird when I call editItem(objectId);. Here are the situations and their results:
If column is editable (column.setEditable(true);), my default data displays just fine
If column is not editable (column.setEditable(false);), my default data does NOT display. It is definitely in the bean, just not displayed. I see it once I click "Save" or "Cancel" in the edit form.
If I just show the line, do NOT enter the edit form (don't call editItem(objectId);), it display the default data just fine. I mention this just to point out what happens in the "display only" situation.
I even tried making the editField read only, and even that hid the data. So what is happening?
Example of data being displayed (see circled red):
Figure 1: Non-Empty data, but editable column
Example of data NOT being displayed (see circled red):
Figure 2: Empty data inside edit form
Figure 3: Non-Empty data after clicking save.
Note that it does not matter if the column is a ComboBox or just a regular text element, if I make it non-editable, it will not show the value I put in that column on this new line until after I click Save or Cancel.
Here is how I load the list of beans initially, where gridContainer is defined as BeanItemContainer<T> gridContainer:
public void updateList( List<T> dataList, T defaultData ) {
updateList( dataList, defaultData, new GridLoader<T>() {
#Override
public void loadGrid(List<T> dataList) {
gridContainer.removeAllItems();
if( dataList instanceof List && !dataList.isEmpty() )
gridContainer.addAll(dataList);
}
});
}
This works fine for non-editable columns, all data being displayed as expected. My pictures sort of hide it, but it is displaying just fine, and works in edit mode just fine as well.
And here is how I add a new line:
private void addRouting() {
Routing emptyData = Routing.create();
emptyData.setKey(null);
if( facilityId instanceof String && !facilityId.trim().isEmpty() )
emptyData.setFacilityId(facilityId.trim());
if(wmsItem instanceof String && !wmsItem.trim().isEmpty())
{
emptyData.setWmsItem(wmsItem);
// gridComponent.hideColumn("wmsItem", true);
// gridComponent.hideColumn("wmsItemDisplay", false);
}
else
{
// gridComponent.hideColumn("wmsItem", false);
// gridComponent.hideColumn("wmsItemDisplay", true);
}
if(workCenter instanceof String && !workCenter.trim().isEmpty())
{
emptyData.setWorkCenter(workCenter);
// gridComponent.hideColumn("workCenter", true);
// gridComponent.hideColumn("workCenterDisplay", false);
}
else
{
// gridComponent.hideColumn("workCenter", false);
// gridComponent.hideColumn("workCenterDisplay", true);
}
gridComponent.addItemAt(0, emptyData);
gridComponent.select(emptyData);
if(gridComponent.isEditorEnabled())
gridComponent.editItem(emptyData);
}
And in GridComponent, we have addItemAt defined as follows (BTW, GridComponent just wraps a layout with a toolbar at top and a Grid for the data, and so exposes various methods I need from the toolbar and Grid):
public BeanItem<T> addItemAt(int index, T bean) throws IllegalStateException {
BeanItemContainer<T> gridContainer = getGridContainer();
if(gridContainer instanceof BeanItemContainer)
{
/* Clear filter first because adding an item will break this.
* TODO: Maybe restore prior filter with "saveLastFilter();" and then "reapplyLastFilter();" after "add"
*/
saveLastFilter();
clearFilter();
BeanItem<T> newItem = gridContainer.addItemAt(index, bean);
reapplyLastFilter();
return newItem;
}
else
throw new IllegalStateException("Missing bean grid container");
}

how to use NgIF condition with formcontrol instead of ngModel

I want to compare my values using my formcontrol than using ngModel, when values is entered in my input box , I want to display my cancel image, so I given userTextValue as true inside subscribe, my query now is how to reset the value when cancel is clicked . I want the input box to be empty , now cancel button is hidden but still values available, I am using pipe to filter values.
<input matInput class="form-control input" placeholder="Enter name or Id" id="user"
[formControl]="userControl"[matAutocomplete]="auto>
<img src="assets/icons/cancel.svg" *ngIf="userTextvalue" class="cancel-icon"
aria-label="Clear" (click)="clearUserValues()">
ts:
constructor() {
this.userControl.valueChanges.subscribe((user) => {
this.filterResult = user;
this.userTextvalue = true;
});
}
clearUserValues() {
this.filterResult = "";
this.userTextvalue = false;
}
pipe.ts
import { Pipe, PipeTransform } from '#angular/core';
#Pipe({
name: 'filterUser'
})
export class FilterUserPipe implements PipeTransform {
transform(items: any[], searchText: string): any[] {
if (searchText && searchText.length > 1) {
items = searchText ? this.filterUsers(items, searchText) : items.slice();
} else {
items = [];
}
return items;
}
filterUsers(items: any[], value: string): any[] {
const filterValue = value.toLowerCase();
return items.filter(item => item.name.toLowerCase().indexOf(filterValue) === 0);
}
}
First of All you have to get knowledge about what is difference between template driven and reactive form approach. When any change happens in formcontrol, it return new object of form (included its formcontrols) and that's what make it synchronous approach.
Let me wrap up this in short scenario.
When any change happens in formcontrol input or html tag
it could be tracked by subscribed it.
for example
// getting specific FormControl changed value.
// form: FormGroup
this.form.get('name of your formControl').subscribe(value => {// here (value) is changed value of that particular formControl. });
2nd Approach
For example you have formcontrol on any clickable input button or select input.
then you can emit an method on event click and on that method you can subscribe changed value and compare or save it to where you want.
sample code ::::
<mat-select formControlName="transferType">
<mat-option [value]="type" *ngFor="let type of transferTypes" (click)="onChanges()">{{type}}</mat-option>
</mat-select>
i am calling "onChanges()" method when i selects an option then i am subscribing this formControl and getting changed value and compare selected value by comparing operation.
same as you can get changed value and then set it to any boolean type variable then you can set any div with *ngIf="" statement in your html template/
if any confusion let me know.
Thanks..
angular7 #reactiveforms #formcontrol
As per your question i'm not completely sure why you want to use the filter since you have not shown the code. However, if you want to just reset your control, change this.filterResult = "" to this.userControl.setValue('') in clearUserValues() method.
Also, since you are subscribing to the valueChanges, it would be better if you do it in ngOnInit().
Check stackblitz here
Your TS code will be like this.
ngOnInit() {
this.onchanges();}
onchanges() {
this.form.get('userControl').valueChanges.subscribe( data => {
// here you can set your boolean value for condition to show cancel button
and push the value/or object which you take from input textbox in an your array for further comparison.
});}
clearUserValues() {
// here you will be set your boolean for hiding cancel button
and then you will be set empty state to your formControl input by doing like this.
this.form.get('userControl').patchValue(//here you will be pass empty string '' or what ever you want set it to.);}

Create a link within Textarea of CSHTML page in MVC

In CSHTML page, I am displaying text using #Html.TextArea. Now I need to create one link within that text. Is that possible to create a link within TextArea?
If it is not possible, what kind of control I can use to display text with link? Any suggestion please.
Ex:
#Html.TextArea("MsgTxtBox","Messagewithlinkhere",new { readOnly = true, id = "MsgTxtBox" })
Yes it is possible but you would have to use some javascript and provided there is only one link in the text. Add a javascript onclick event function to the textbox:
#Html.TextArea("MsgTxtBox","Messagewithlinkhere",new { readOnly = true, id = "MsgTxtBox", onclick="redirectToUrl()" })
Now make sure the links in the text are surrounded by a character like [link], so you can separate them from the text. Lets say the value of the text is "Hello [https://www.google.com] World"
Now add the following javascript on top: We would take the index of the first [ character and then the second one ], and use a substring method to get the string in between. See link, then use window.location to redirect to that link.
<script type="text/javascript">
function redirectToUrl() {
var text = document.getElementById("MsgTxtBox").value;
var start = text.indexOf('[') + 1;
var end = text.indexOf(']', start);
var link = text.substring(start, end)
window.location = link;
}
</script>

How to auto populate a date based on checkbox action Mvc4

I am currently doing a project in .net MVC4 and I have requirement to populate a Display field with current date, when a checkbox is ticked in the Edit form.
Since it's an edit form Checkbox, might be ticked already and I need to check if it's selected the first time then I need to populate the current date.
Update:
Matt Thanks..I got this around by using Hidden field.
Steps involved:
1. store the model field in Hidden field in your Edit Screen.
#Html.Hidden("hiddenDateField", Model.DateField)
#Html.Hidden("hiddenCheckBox", Model.CheckBoxField)
Then using JQuery I added following logic..
$('#chkBox').on('click', function () {
var myDate = new Date();
var displayDate = (myDate.getUTCDate()) + '/' +(myDate.getUTCMonth() + 1) + '/' + myDate.getUTCFullYear() + " " + myDate.getUTCHours() +":" + myDate.getUTCMinutes() +":"+myDate.getUTCSeconds();
if ($('#chkBox').is(":checked")) {
if ($('#hiddenCheckBox').val() == "False") { // This condition is to check if the user is selecting checkbox for 1st time by comparing with received model data value.
$('#lblDate').text(displayDate);
} else {
$('#lblDate').text($('#hiddenDateField').val()); // This condition is to restore the Date if user unticks and Select Checkbox again.
}
}
if (!$('#chkBox').is(":checked")) { // This when user unticks the checkbox and I replaced the date to empty char.
$('#lblDate').text("");
}
});
no need to use ajax, just use jquery. without your code it is hard to give an example so you will need to change this to match your code
$(document).ready(function(){
//this will check if checked on load and set the text box to now
if($('.chkClass').is(":checked")){
$('.txtClass').val($.now());
}
$('.chkClass').on('click', function(){
//check again so it only sets the date if they check and not uncheck
if($('.chkClass').is(":checked")){
$('.txtClass').val($.now());
}
});
});

Knockout jQueryUI Autocomplete how to use input value if nothing selected from autocomplete list

I am using the custom binding provided in How to create an auto-complete combobox?
I want to allow the user to either select a value from the list of suggestions or enter a value that is not in the list of suggestions. How can I get the value of the input into my observable field?
For example, if the user types 'smi' the autocomplete list will show Smith and other surnames beginning with 'smi', however, if they do not select an option from the list, I just want to set the value of my observable field to be 'smi'. At present, the only way the observable propety is set is when the user selects an item from the list of suggestions.
I have the following code (HTML):
<input type="text" data-bind="
value: surname,
jqAuto: { autoFocus: true },
jqAutoSource: surnames,
jqAutoQuery: surnameAutocomplete,
jqAutoValue: surname"
/>
JavaScript view model (simplified):
var vm = {
surnames: ko.observableArray(),
surname: ko.observable(),
surnameAutocomplete: function (searchTerm, result) {
repository.surnameAutocomplete(searchTerm, result);
};
Solution:
I amended the custom binding handler in two places:
init: function - added the following
// New setting to allow / disallow a user to enter values that are in the autocomplete list.
forceSelection = allBindings.jqAutoForceSelection;
options change function - amended to the following
//on a change, make sure that it is a valid value or clear out the model value
options.change = function (event, ui) {
var currentValue = $(element).val();
// Start: new code, check new setting on whether to force user to make a selection
if (!forceSelection) {
writeValueToModel(currentValue);
return;
}
// End: new code
var matchingItem = ko.utils.arrayFirst(unwrap(source), function (item) {
return unwrap(inputValueProp ? item[inputValueProp] : item) === currentValue;
});
if (!matchingItem) {
writeValueToModel(null);
}
}
I also found that the first item in the autocomplete list was being automatically selected, but then noticed by setting autofocus: false solved my issue, e.g.,
<input type="text" data-bind="
jqAuto: { autoFocus: false }, /* This fixes the auto select issue */
jqAutoSource: surnames,
jqAutoQuery: surnameAutocomplete,
jqAutoValue: surname,
jqAutoForceSelection: false"
/>
If you look closely at the binding handler you're using, you will notice this section:
//on a change, make sure that it is a valid value or clear out the model value
options.change = function(event, ui) {
var currentValue = $(element).val();
var matchingItem = ko.utils.arrayFirst(unwrap(source), function(item) {
return unwrap(item[inputValueProp]) === currentValue;
});
if (!matchingItem) {
writeValueToModel(null);
}
What this section of the binding handler essentially does is check if the text the user entered into the text field matches something in the autocomplete dropdown, and if it doesn't, it clears the model value (which it sounds like what you want to change).
You can either try deleting this section or extend it to suit your purposes.

Resources