What is the quickest way to validate al my input fields with javaScript?
I want to check if the fields are filled in or not.
Thx
following is my javascript code :
<script>
function Check(frm)
{
var input, EmptyFound=false;
var elem = document.getElementById('frmMain').elements;
for(var i=0;i<elem.length;i++)
{
input = elem[i];
if(input.type == "text")
{
if(input.value == "")
{
EmptyFound = true;
break;
}
}
return notEmpty;
}
</script>
I would use jQuery Validate.
A single line of jQuery to select the form and apply the validation
plugin. And a bit of metadata on each element to specify the
validation rules.
The docs specifically for enforcing required are at
http://docs.jquery.com/Plugins/Validation/Methods/required
It requires adding jQuery (if you don't use it already) but provides a fast and powerful validation framework.
you can use this to distinguish between input different types
this is just a sample from my project
//var frm_elements = document.mainForm.elements;
//var frm_elements =document.getElementById('mainForm').elements;
for (var i = 0; i < document.mainForm.elements.length; i++)
{document.mainForm.elements[i];
if(document.mainForm.elements[i]!=null)
{
var field_type = document.mainForm.elements[i].type;
switch (field_type)
{
case "text":
if(document.mainForm.elements[i].name.indexOf("from")!='-1' &&
document.mainForm.elements[i].name.indexOf("frotom")!='-1' &&
!document.mainForm.elements[i].name.indexOf("serNo")!='-1' &&
!document.mainForm.elements[i].name.indexOf("repKey")!='-1' &&
!document.mainForm.elements[i].name.indexOf("orderKey")!='-1' &&
!document.mainForm.elements[i].name.indexOf("formatKey")!='-1' )
{
document.mainForm.elements[i].value = "";
}
break;
case "password":
case "textarea":
case "hidden":
/* frm_elements[i].value = "";
break;*/
case "radio":
case "checkbox":
/*if (frm_elements[i].checked)
{
frm_elements[i].checked = false;
}
break;*/
case "select-one":
case "select-multi":
if(document.mainForm.elements[i].name.indexOf("ddlMainSubModule")=='-1')
document.mainForm.elements[i].selectedIndex = 0;
break;
default:
break;
}
}
}
Related
I try with my programm to recognise a specific word when I speek a sentence, it's use Web speech API.
When I speek the word alone, my programm work fine, but when I speek it in a sentence, my programm doesn't run.
Thank's to tell me where is the problem with my programm.
<script>
(function($)
{
var $btn = $('#btn');
var $result = $('#result');
var words = null;
if ('webkitSpeechRecognition' in window)
{
var recognition = new webkitSpeechRecognition();
recognition.lang = "fr-FR";
recognition.continuous = false;
recognition.interimResults = true;
$btn.click(function(e)
{
e.preventDefault();
$btn.removeClass('btn-primary');
recognition.start();
});
recognition.onresult = function (event)
{
$result.text('');
for (var i = event.resultIndex; i < event.results.length; i++)
{
var transcript = event.results[i][0].transcript;
if (event.results[i].isFinal)
{
$result.text(transcript);
recognition.stop();
$btn.addClass('btn-primary');
words = transcript.split(' ');
if(words[0] == 'test')
{
// do something
}
return true;
}
else
{
$result.text($('#result').text() + event.results[i][0].transcript);
}
}
};
}
else{$btn.hide();}
})(jQuery);
</script>
When you do words = transcript.split(' ') you make words an array of all of the recognized words. Then when you do if(words[0] == 'test') you are only checking the first word, so it will only work if the word you are trying to recognize is the first (or only) word.
Instead of this:
if(words[0] == 'test')
{
// do something
}
Try this:
words.some(function (word) {
if (word === 'test') {
// do something
return true;
}
});
I'm trying to assert that a name is displayed in a column of a table. I've written an inResults function that will iterate through a column's text to see if a name exists. Here's what I'm trying:
Page object:
this.names = element.all(by.repeater('row in rows').column('{{row}}'));
this.inResults = function(nameString) {
var foundit = '';
this.names.each(function(name) {
name.getText().then(function(it) {
console.log(it); // each name IS printed...
if(it == nameString) {
console.log('it\'s TRUE!!!!'); // this gets printed...
foundit = true;
}
});
});
return foundit; // returns '' but should be true?
};
Spec expect:
expect(friendPage.inResults('Jo')).toBeTruthy();
Both console statements print as expected... but my expect fails as foundit's value is still ''. I've tried this a number of ways and none are working. What am I missing?
I've devised what I think is a better/cleaner way to solve this. It's less complex and doesn't require locator/css code in the method.
friend.page.js
// locator
this.friendName = function(text) { return element.all(by.cssContainingText('td.ng-binding', text)) };
// method
this.inResults = function(name) {
return this.friendName(name).then(function(found) {
return found.length > 0;
});
};
friend.spec.js
expect(friendPage.inResults('Jo')).toBeTruthy();
I've added this to my protractor_example project on GitHub...
I would recommend you to use filter: http://angular.github.io/protractor/#/api?view=ElementArrayFinder.prototype.filter
this.inResults = function(nameString) {
return this.names.filter(function(name) {
return name.getText().then(function(text) {
return text === nameString;
});
}).then(function(filteredElements) {
// Only the elements that passed the filter will be here. This is an array.
return filteredElements.length > 0;
});
});
// This will be a promise that resolves to a boolean.
expect(friendPage.inResults('Jo')).toBe(true);
Use map to do this.This will return a deferred that will resolve with the values in an array, so if you have this:
this.mappedVals =element.all(by.repeater('row in rows').column('{{row}}')).map(function (elm) {
return elm.getText();
});
It will resolve like this:
this.inResults = function(nameString) {
var foundit = '';
mappedVals.then(function (textArr) {
// textArr will be an actual JS array of the text from each node in your repeater
for(var i=0; i<textArr.length; i++){
if(it == textArr[i]) {
console.log('it\'s TRUE!!!!'); // this gets printed...
foundit = true;
}
}
return foundit;
});
}
And Use that in Spec file like,
friendPage.inResults('Jo').then(function(findIt){
expect(findIt).toBeTruthy();
});
while actively learning Play2.0 I am stuck with creating a tag. In the sample application, called computer-database, the following helper is created in the list template:
#****************************************
* Helper generating navigation links *
****************************************#
#link(newPage:Int, newSortBy:String) = #{
var sortBy = currentSortBy
var order = currentOrder
if(newSortBy != null) {
sortBy = newSortBy
if(currentSortBy == newSortBy) {
if(currentOrder == "asc") {
order = "desc"
} else {
order = "asc"
}
} else {
order = "asc"
}
}
// Generate the link
controllers.orders.routes.Work.list(newPage, sortBy, order, currentFilter)
}
Since I want to use this helper in a view templates I thought that the best solution would be to create a tag for it. So I did the following (in my tags package):
#(newPage : Int, newSortBy:String) {
var sortBy = currentSortBy
var order = currentOrder
if(newSortBy != null) {
sortBy = newSortBy
if(currentSortBy == newSortBy) {
if(currentOrder == "asc") {
order = "desc"
} else {
order = "asc"
}
} else {
order = "asc"
}
}
// Generate the link
controllers.orders.routes.Computer.list(newPage, sortBy, order, currentFilter)
}
But, obviously this is not working and I do not know where or why it is not working.
Thanks for the input.
UPDATE WITH ANSWER:
So in Scala template we have to define, just as in Java, the arguments that are passed to this view (Note: that the variables that you will use in the javascript must be passed too!). The template will be compiled as a method as stated in the documentation.
The working tag looks like:
#(newPage : Int, newSortBy : String, currentSortBy: String, currentOrder: String, currentFilter : String ) #{
var sortBy = currentSortBy
var order = currentOrder
if(newSortBy != null) {
sortBy = newSortBy
if(currentSortBy == newSortBy) {
if(currentOrder == "asc") {
order = "desc"
} else {
order = "asc"
}
} else {
order = "asc"
}
}
// Generate the link
controllers.orders.routes.Work.list(newPage, sortBy, order, currentFilter)
}
The trick is that the first version uses a template syntax allowing to write Scala code instead of HTML: #{ val scalaVal = 42}.
In your tag, the template engine interpretes your code as HTML.
If you want to copy-paste this code, don’t forget the leading # before the opening brace.
I have an extjs form with fields. The user isn't required to enter data into each field so I do not want to submit the fields with no data. I want it to post only fields that actually have data. Is this possible?
I recommend using form's beforeaction event. While handling this event you can check all fields. If all values are empty just return false;. The following example works in ExtJS4 and has to work in ExtJS3:
myform.on('beforeaction', function(form, action) {
if (action.type == 'submit') {
var doSubmit = false, vals = form.getValues();
for (var i in vals)
if (vals[i] !== '') {
doSubmit = true;
break;
}
return doSubmit;
}
});
Actualy, the right way to not submit empty fields is to use action's submitEmptyText config. But it's not working in current version (ExtJS4.0.2a).
Another options is to override component's getSubmitValue() method and return null if this field is empty, this way it won't be included into submit fields.
{
xtype: 'combo',
getSubmitValue: function(){
var value = this.getValue();
if(Ext.isEmpty(value)) {
return null;
}
return value;
}
}
Instead of using form's submit, directly call Ext.Ajax.request(...) with the url, method type (GET/POST) and params (and any other options as explained in the call documentation).
To generate params, iterate over the form fields and check for null value before adding to params.
This bug is present in ExtJS 4.0.7 too.
As Molecule Man pointed:
Actualy, the right way to not submit empty fields is to use action's submitEmptyText config. But it's not working in current version (ExtJS4.0.2a).
A possible solution to fix this bug is by overriding 2 functions, getValues in "Ext.form.Basic" (where the bug is) and createForm (to create our basic form) in "Ext.form.Panel" by extension in the following way:
Ext.define("My.form.Basic", {
alias: "form.mybasic",
extend: "Ext.form.Basic",
getValues: function(asString, dirtyOnly, includeEmptyText, useDataValues) {
var values = {};
this.getFields().each(function(field) {
if (!dirtyOnly || field.isDirty()) {
var data = field[useDataValues ? "getModelData" : "getSubmitData"](includeEmptyText);
if (Ext.isObject(data)) {
var isArray = Ext.isArray;
Ext.iterate(data, function(name, val) {
if (includeEmptyText && val === "") {
val = field.emptyText || "";
}
if (includeEmptyText || ((!isArray(val) && val !== "") || (isArray(val) && val.length !== 0))) {
if (name in values) {
var bucket = values[name];
if (!isArray(bucket)) {
bucket = values[name] = [bucket];
}
if (isArray(val)) {
values[name] = bucket.concat(val);
}
else {
bucket.push(val);
}
}
else {
values[name] = val;
}
}
});
}
}
});
if (asString) {
values = Ext.Object.toQueryString(values);
}
return values;
}
});
Ext.define("My.form.Panel", {
alias: "form.mypanel",
extend: "Ext.form.Panel",
createForm: function() {
return Ext.create("My.form.Basic", this, Ext.applyIf({listeners: {}}, this.initialConfig));
}
});
The code is copied from the ext source code. The only change is inside the iteration of each field: introduced the following wrapping "if":
if (includeEmptyText || ((!isArray(val) && val !== "") || (isArray(val) && val.length !== 0)))
I am a bit late but, better later than never...
Can anyone tell me how to use DataType.Custom in ASP.NET MVC 2?
Don't use DataType.Custom.
Instead use [DataType("YourCustomDataTypeHere")] with an editor/display template named YourCustomDataTypeHere.
I'd read over Brad Wilson's ASP.NET MVC 2 Template series on his blog here. It explains what you're asking better than I could.
Hope that helps.
I haven't used it personally, but looking at the MSDN it seems to just be a matter of setting DataType = DataType.Custom and CustomDataType = "String". Then when you process your model you would check for DataType.Custom and if found perform different operations based on the value in CustomDataType.
Here's the sample they give on the MSDN - How to: Customize Data Field Appearance and Behavior For Non-Intrinsic Data Types in the Data Model:
public partial class TextField : System.Web.DynamicData.FieldTemplateUserControl {
string getNavUrl() {
var metadata = MetadataAttributes.OfType<DataTypeAttribute>().FirstOrDefault();
if (metadata == null)
return FieldValueString;
switch (metadata.DataType) {
case DataType.Url:
string url = FieldValueString;
if (url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ||
url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
return url;
return "http://" + FieldValueString;
case DataType.EmailAddress:
return "mailto:" + FieldValueString;
default:
throw new Exception("Unknown DataType");
}
}
protected override void OnDataBinding(EventArgs e) {
base.OnDataBinding(e);
if (string.IsNullOrEmpty(FieldValueString))
return;
var metadata = MetadataAttributes.OfType<DataTypeAttribute>().FirstOrDefault();
if (metadata == null || string.IsNullOrEmpty(FieldValueString)) {
Literal literal = new Literal();
literal.Text = FieldValueString;
Controls.Add(literal);
return;
}
if (metadata.DataType == DataType.Url ||
metadata.DataType == DataType.EmailAddress) {
HyperLink hyperlink = new HyperLink();
hyperlink.Text = FieldValueString;
hyperlink.NavigateUrl = getNavUrl();
hyperlink.Target = "_blank";
Controls.Add(hyperlink);
return;
}
if (metadata.DataType == DataType.Custom &&
string.Compare(metadata.CustomDataType, "BoldRed", true) == 0) {
Label lbl = new Label();
lbl.Text = FieldValueString;
lbl.Font.Bold = true;
lbl.ForeColor = System.Drawing.Color.Red;
Controls.Add(lbl);
}
}
}