add command to check text and attribute - cypress

I have to write a command where i have a textfield which should have a value and i have to check that the field is disabled or not. The disabled part can be case per case that is sometimes i do not need this assertion but the value check will always be there.
This is what i have done so far:
Cypress.Commands.add('checkTextAndAttr', (selector, value) => {
cy.get(selector).within(() => {
cy.get('input').should('have.value', value)
})
This is the html of a disabled button:
<input disabled="" placeholder="my-field" type="tel" value="0,00" inputmode="numeric">
and this for one which is enabled:
<input placeholder="my-field" type="tel" value="1 200,00" inputmode="numeric">
A field which is enabled is a field in which i can input text.
A field not enabled is one which cannot input text, when a calculation is done the field will be updated by itself.
How do i put the disabled condition in it?
thank you

I think the best way would be to add an additional parameter to your command. We can then use that parameter to conditionally change the assertion between 'have.attr' and 'not.have.attr'. Below, I'm using a ternary to accomplish that.
Cypress.Commands.add('checkTextAndAttr', (selector, value, isDisabled) => {
cy.get(selector).within(() => {
cy.get('input').should('have.value', value);
cy.get('input').should(isDisabled ? 'have.attr' : 'not.have.attr', 'disabled')
});
});
Additionally, if you had an overwhelming amount of one checks vs. the other, you could make the isDisabled parameter optional/nullable, and make that "default" check the false result of the ternary. (If switching 'have.attr' to the false statement, it may make sense to rename isDisabled to isEnabled)
Cypress.Commands.add('checkTextAndAttr', (selector, value, isDisabled?)
// with isDisabled false
cy.checkTextAndAttr('foo', 'bar', false);
// with isDisabled true
cy.checkTextAndAttr('foo', 'bar', true);
// with isDisabled undefined -- the `.should()` evaluates the same as false (both undefined and false are not true)
cy.checkTextAndAttr('foo', 'bar')

Related

set a radio button selected by defualt in Html.RadioButtonFor

I can not select a default option for my radio buttons in my view.
I have tried:
#Html.RadioButtonFor(s => s.Before, false, new { #checked = true })
#Html.RadioButtonFor(s => s.Before, false, new { #class = "checked" })
and many other ways - but none of them is working!
and also I like to make it required. How can I make it selected and required?
I am using .NET Core 5.
How to make it selected:
The radio button will be checked if the value of property in the model is equal to the second argument we pass in to RadioButtonFor method.
So, in your case if you set Before property to false, then the radio button will be checked. I guess the right way would be set the value of Before to true and pass true as second argument value.
To make it require:
Decorate the Property with "System.ComponentModel.DataAnnotations.RequiredAttribute" attribute which makes the property required. Now you can check this.ModelState.IsValid in the post method and return this.Page().
Note: The page can be validated at client side if you use
jquery-validation library.
In case of bool types they will always have either true or false so
the model will always be valid even user won't select it. In this case
use nullable bool instead of bool.
[BindProperty]
[Required]
public bool? Before{ get; set; }
In the get method
this.Before = true;
In the view
#Html.RadioButtonFor(s => s.Before, true)
Please let me know if that works.

HandsOnTable Dropdown Without Editable Text?

Is it possible to use a dropdown column in a HandsOnTable without the editable textbox?
I know you can set the type to dropdown and it will validate/highlight red when you enter an invalid value, but is there a way to completely disable text entry for dropdown columns? It seems just using the readOnly property on the column blocks the dropdown altogether.
As you said, the readOnly option will disable you dropdown. So I believe the closest solution you can use is the allowIndvalid = false (true by default) :
allowInvalid: true (optional) - allows manual input of value that does not exist in the source. In this case, the field background highlight becomes red and the selection advances to the next cell
allowInvalid: false - does not allow manual input of value that does not exist in the source. In this case, the ENTER key is ignored and the editor field remains opened.
Documentation Link
You can use this JSFiddle to quickly check this option
I have the same issue and was able to resolve it with such steps. Maybe this could help:
1 when creating columns add a special className to the necessary column type:
{
data: 'priceUnitsName',
type: 'dropdown',
invalidCellClassName: 'colored',
source: Object.keys(unitNames),
width: 100,
className: 'disable-edit',
}
2 Subscribe to events to handle cancel editing:
private targetCell: HTMLTableCellElement;
public settings: GridSettings = {
// your settings
afterOnCellMouseDown: (event: MouseEvent, coords: CellCoords, TD: HTMLTableCellElement) => {
this.targetCell = TD;
},
afterBeginEditing: (row: number, column: number) => {
if (this.targetCell.classList.contains('disable-edit')) { // this handle only necessary columns with special class
setTimeout(() => {
const inputCollection: HTMLCollection = document.getElementsByClassName('handsontableInput');
Array.from(inputCollection).forEach((input: HTMLTextAreaElement) => {
input.blur(); // this calls blur on element manually
});
});
}
},
Maybe this is not the best decision, but by default, handsontable can't make dropdown elements readonly with leaving open-close dropdown functional and I can't find any workable suggestion with this.
Checked on 'dropdown' and 'date' types, and it works.

Can I add conditions within Kendo().DropDownList() definition?

I have a kendo dropdownlist and want to add a property to it but only if some condition is met. It that possible and, if so, what is the syntax? Below is the concept that I have in mind.
#(Html.Kendo().DropDownList()
.Name("My Dropdown List")
.Value(Model.xxx)
If (some condition){
.Height(1000)
}
.DataTextField("MYDESCRIPTIEN")
.DataValueField("MYFIELD")
.HtmlAttributes(new { style = "width:300px" })
)
Update: With regard to the Height, I am afraid you are out of luck, as the Height() method expects a non-null integer value that will be always serialized to the client. The only option is to use two different widget declarations inside an external conditional statement.
===
Each fluent method expects a value of a certain type, or an expression that returns a value of this type. In addition, each configuration setting has a default value.
So you have a couple of options:
use a ternary operator that returns different values, depending on the condition. In one case it may return the property's default value
use an auxiliary variable, that is assigned the appropriate value in advance
Fluent methods that expect an action can be managed differently and you can use standard conditional statements, instead of ternaries.
Here is an example for all above scenarios:
#{
bool myCondition = false;
}
#(Html.Kendo().DropDownList()
.HtmlAttributes(myCondition ? new { style = "width: 100%" } : new object { /* empty object */ } )
.Events(e => {
if (myCondition)
{
// nothing here this time
}
else
{
e.DataBound("onDataBound");
}
})
)
<script>
function onDataBound(e) {
console.log("dataBound");
}
</script>
Hi there you should be able to add Events like so:
#(Html.Kendo().DropDownList()
.Name("My Dropdown List")
.Value(Model.xxx)
.DataTextField("MYDESCRIPTIEN")
.DataValueField("MYFIELD")
.HtmlAttributes(new { style = "width:300px" })
.Events(e => e.Change("OnDropDownChanged"));
)
JAVASCRIPT
function OnDropDownChanged(e)
{
//Do stuff to meet condition
}

Knockout checked binding issue

I'm having a problem with checkbox bindings not quite working with KnockoutJS 2.0. I have an array of objects. One of the properties of those objects is an array of different objects. In the child objects there are a few properties, one of which is a boolean. I build a list for each parent object and under each parent I show the children. For each list of children I have two views, a read only and an edit view. In the read only I have images that represent whether or not the item is checked based on the boolean property. This works and if I update the boolean value through the console, I'm seeing what I would expect--the image goes away or displays based on the value I assign. In the edit view, the images are replaced with a checkbox. I see the same behavior when I update the value through the console--it is checked when I expect it to be and not when I don't. The problem comes in when I check or uncheck the checkbox. Doing this doesn't change the underlying value the checkbox is bound to.
Here's the basic idea of my data.
[
{
"xxx": "yyy",
"xxx": "yyy",
...
"Displays": [
{
"xxx": "yyy",
...
"Excluded": false,
},
{
"xxx": "yyy",
...
"Excluded": true,
}
],
}
]
Here's the binding
<input type="checkbox" data-bind="checked: !Excluded()" />
the problem is that "checked" here is a bidirectional binding: the bound property needs to be read to generate the correct view, but needs also to be updated when you click on the checkbox. Contrast this to a binding like:
<span data-bind="text: 'your name is ' + name()"></span>
when the expression is only read, so you can use an expression (and you need to unwrap the observable).
So, you need to bind directly to the observable property, without "unwrapping" it adding '()', it will be done by knockout when needed, both for read and write:
<input type="checkbox" data-bind="checked: Excluded" />
See http://jsfiddle.net/saurus/usKwA/ for a simple example. Note how the checkbox labels are updated on change, showing that the model is updated and the rendering triggers correctly.
If you need to negate the value (so that the checkbox is checked when the value is false), you can add a writeable computed observable, as explained on http://knockoutjs.com/documentation/computedObservables.html section "Writeable computed observables", or you can negate the data in the viewmodel, doing it on the server just before sending the data, or on the client before populating the viewmodel.
hope this helps.
I know my answer is a bit late to the game here, but I had this problem today and this was the closest thread I could find related to the problem, and it doesn't seem to have an answer that solves it. So here's my solution.
Essentially, the issue is that knockout really wants your viewModel values to be a string, not a boolean, but this isn't always practical. So, I created a binding called "isChecked" which works strictly with booleans. Note: This will only work with observable properties.
ko.bindingHandlers.isChecked = {
getElementDeclaredValue: function (element) {
var declaredValue = element.getAttribute("value");
// If a value is provided, we presume it represents "true",
// unless its explicitly "false". If no value is provided, we
// presume that a checked state would equal "true".
return declaredValue && Boolean.isBool(declaredValue)
? Boolean.parse(declaredValue)
: true;
},
init: function (element, valueAccessor) {
var updateHandler = function () {
var declaredValue = ko.bindingHandlers.isChecked.getElementDeclaredValue(element);
var elementValue = element.checked ? declaredValue : !declaredValue;
var modelValue = valueAccessor();
var currentValue = ko.utils.unwrapObservable(modelValue);
if (elementValue === currentValue)
return;
if (ko.isObservable(modelValue)) {
modelValue(elementValue);
}
};
ko.utils.registerEventHandler(element, "click", updateHandler);
},
update: function (element, valueAccessor) {
var elementValue = ko.bindingHandlers.isChecked.getElementDeclaredValue(element);
element.checked = elementValue === ko.utils.unwrapObservable(valueAccessor());
}
};
The two Boolean methods ("parse" and "isBool") are defined as follows:
Boolean.isBool = function (value) {
return (/^(?:true|false)$/i).test(value);
};
Boolean.parse = function (value) {
return (/^true$/i).test(value);
};
I'll ignore any comments that say I shouldn't be modifying a built-in object prototype; I'll do as I damn well please ;-).
Usage is the same as the checked binding. The "value" attribute is optional, unless you want the checked state to represent false:
<input type="radio" id="rbNewClaim" name="ClaimType" value="false" data-bind="checked: isExistingClaim" />
Hope this helps someone.
I gave up trying to get this to work with the bool values and created an array of selected objects and handled it that way. It isn't the optimal solution, but I was tired of fighting this.

Javascript onfocus event

I have textbox whose value if entered needs to be validated using some regularexpression
I need to validate the value as user is entering the data.
Which is suitable event can be used for this ? some sample example of using onfocus event on textbox will be helpful
Use onKeypress or onKeyup.
Beginners often think that onChange will do what you want, but that only fires when the input loses the focus.
OnFocus is irrelevant - that is when the box first gets the focus, not when the user types.
Typically you would do this when the text input loses focus, so it would be using the blur event. The reason is that many inputs aren't valid until some sufficient number of characters has been typed. It can be very annoying to the user to put up a validation error while they are still typing a valid string. For example, when doing email validation, the input cannot be valid until the # sign has been entered. Note that you'd also need to validate when the form is submitted to catch the case where the field has never had focus.
Using jQuery it might look like:
$('.klass').blur( function() {
if (!$(this).val().match( /your-regular-expression/ )) {
$(this).next('.validation-message').show();
return false; // keep focus on field
}
return true;
});
This assumes some HTML like
<input type="text" class="klass" name="myInput" />
<span class="validation-message" style="display: none;">This is not valid</span>
To stop the user from writing invalid characters, or to validate the fields as he types you can use .onkeypress.
document.getElementById(fieldId).onkeypress = onkeypressHandler;
var onkeypressHandler = function (event) {
var eKey = event.charCode;
var str = String.fromCharCode(eKey);
var pattern = /[^0-9]/g;
var strTmp = str.replace(pattern, "");
if (str!== strTmp) {
return false;
}
return true;
}
In this example the only valid characters are numbers, if the pressed key is not a number then the function will return false and the key will be ignored.
Also validate a field after the user is done typing you can use .onchange
document.getElementById(fieldId).onchange= onChangeHandler;

Resources