Codeception acceptance test error for save/reset - html

I am trying to perform acceptance tests for my website using Codeception, and I am experiencing a strange error due to a reset button on the form I am testing. Basically, my test for clicking on 'Save' works only if either the reset button on my form is AFTER the Save button, or if the reset button is left off the form altogether. If the reset button is inserted in the form before the save button, Codeception throws an Unreachable field "reset" error. Here is my Codeception code:
<?php
$I = new WebGuy($scenario);
$I->wantTo('find an employee in the database');
$I->amOnPage('/employees/find/');
$I->fillField('employeeLookup[first_name]', 'Sergi');
$I->click('Save', '#employeeLookup_save');
$I->see('Based on your search for Sergi, the following employees were found:');
$I->see('Remmele');
$I->see('Feb 28 1992');
And here is my HTML (much of it being generated from Symfony2):
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Find existing employee</title>
</head>
<body>
<div id="content">
<p>Hello, enter either the first name, or the last name of the employee
you are searching for.</p>
<form name="employeeLookup" method="post" action="">
<div><label for="employeeLookup_first_name" class="required">Name: </label><input type="text" id="employeeLookup_first_name" name="employeeLookup[first_name]" required="required" /></div>
<div><button type="reset" id="employeeLookup_reset" name="employeeLookup[reset]">Reset</button></div>
<div><button type="submit" id="employeeLookup_save" name="employeeLookup[save]">Save</button></div>
<input type="hidden" id="employeeLookup__token" name="employeeLookup[_token]" value="RcpMVTGgB6WhKgDoXXRwmV_l4AFYKWTZko-dnBDhhvM" /></form>
</div>
<div id="sfwdte5d291" class="sf-toolbar" style="display: none"></div><script>/*<![CDATA[*/ Sfjs = (function() { "use strict"; var noop = function() {}, profilerStorageKey = 'sf2/profiler/', request = function(url, onSuccess, onError, payload, options) { var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); options = options || {}; xhr.open(options.method || 'GET', url, true); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onreadystatechange = function(state) { if (4 === xhr.readyState && 200 === xhr.status) { (onSuccess || noop)(xhr); } else if (4 === xhr.readyState && xhr.status != 200) { (onError || noop)(xhr); } }; xhr.send(payload || ''); }, hasClass = function(el, klass) { return el.className.match(new RegExp('\\b' + klass + '\\b')); }, removeClass = function(el, klass) { el.className = el.className.replace(new RegExp('\\b' + klass + '\\b'), ' '); }, addClass = function(el, klass) { if (!hasClass(el, klass)) { el.className += " " + klass; } }, getPreference = function(name) { if (!window.localStorage) { return null; } return localStorage.getItem(profilerStorageKey + name); }, setPreference = function(name, value) { if (!window.localStorage) { return null; } localStorage.setItem(profilerStorageKey + name, value); }; return { hasClass: hasClass, removeClass: removeClass, addClass: addClass, getPreference: getPreference, setPreference: setPreference, request: request, load: function(selector, url, onSuccess, onError, options) { var el = document.getElementById(selector); if (el && el.getAttribute('data-sfurl') !== url) { request( url, function(xhr) { el.innerHTML = xhr.responseText; el.setAttribute('data-sfurl', url); removeClass(el, 'loading'); (onSuccess || noop)(xhr, el); }, function(xhr) { (onError || noop)(xhr, el); }, options ); } return this; }, toggle: function(selector, elOn, elOff) { var i, style, tmp = elOn.style.display, el = document.getElementById(selector); elOn.style.display = elOff.style.display; elOff.style.display = tmp; if (el) { el.style.display = 'none' === tmp ? 'none' : 'block'; } return this; } } })();/*]]>*/</script><script>/*<![CDATA[*/ (function () { Sfjs.load( 'sfwdte5d291', '/employees/app_dev.php/_wdt/e5d291', function(xhr, el) { el.style.display = -1 !== xhr.responseText.indexOf('sf-toolbarreset') ? 'block' : 'none'; if (el.style.display == 'none') { return; } if (Sfjs.getPreference('toolbar/displayState') == 'none') { document.getElementById('sfToolbarMainContent-e5d291').style.display = 'none'; document.getElementById('sfToolbarClearer-e5d291').style.display = 'none'; document.getElementById('sfMiniToolbar-e5d291').style.display = 'block'; } else { document.getElementById('sfToolbarMainContent-e5d291').style.display = 'block'; document.getElementById('sfToolbarClearer-e5d291').style.display = 'block'; document.getElementById('sfMiniToolbar-e5d291').style.display = 'none'; } }, function(xhr) { if (xhr.status !== 0) { confirm('An error occurred while loading the web debug toolbar (' + xhr.status + ': ' + xhr.statusText + ').\n\nDo you want to open the profiler?') && (window.location = '/employees/app_dev.php/_profiler/e5d291'); } } ); })();/*]]>*/</script>
</body>
</html>
Finally, here is the relevant output of the error message from Codeception:
1) Failed to find an employee in the database in FindEmployeeCept.php
Sorry, I couldn't click "Save","#employeeLookup_save":
Behat\Mink\Exception\ElementException: Exception thrown by ((//html/descendant-or-self::*[#id = 'employeeLookup_save'])[1]/.//input[./#type = 'submit' or ./#type = 'image' or ./#type = 'button'][(((./#id = 'Save' or ./#name = 'Save') or contains(./#value, 'Save')) or contains(./#title, 'Save'))] | .//input[./#type = 'image'][contains(./#alt, 'Save')] | .//button[((((./#id = 'Save' or ./#name = 'Save') or contains(./#value, 'Save')) or contains(normalize-space(string(.)), 'Save')) or contains(./#title, 'Save'))] | .//input[./#type = 'image'][contains(./#alt, 'Save')] | .//*[./#role = 'button'][(((./#id = 'Save' or ./#name = 'Save') or contains(./#value, 'Save')) or contains(./#title, 'Save') or contains(normalize-space(string(.)), 'Save'))])[1]
Unreachable field "reset"
Again, if the reset button is rendered after the save button in the HTML, the acceptance tests pass just fine. Also, if the reset button is left off of the form entirely, the acceptance test passes as well. Does anyone have any idea what is causing this?

Related

Live Chat (Node.js) Custom Font Assistance Needed

Still relatively new to HTML/CSS and currently working on a Live Chat feature for my website utilizing Node.js and MongoDB. I've been able to get the chat to work, but have been stuck on figuring out how to customize a specific aspect of this chat. I'd like to change the font-weight of the username in the chat box (area where all messages are seen) to make the username stand out a bit more compared to the rest of the text in the box. I am confused on how to do so in CSS. I've highlighted (in yellow) the line where the 'Username' is called so I imagine this is the 'class' that I'd need to customize but it tied to the text afterwards if that makes sense...?
Thanks for your help!
Browser Inspect Element
What my code and chat currently look like (see line 59 for highlighted portion)
<!DOCTYPE html>
<html>
<head>
<title>Chat</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<div class="chat">
<input type="text" class="chat-name" placeholder="Chat">
<div class="info-rect">Info</div>
<div class="chat-messages"></div>
<textarea placeholder="Join the conversation..."></textarea>
<div class="chat-status">Status: <span>Idle</span></div>
</div>
<script src="http://127.0.0.1:8080/socket.io/socket.io.js"></script>
<script>
(function() {
var getNode = function(s) {
return document.querySelector(s);
},
// Get required nodes
status = getNode('.chat-status span'),
messages = getNode('.chat-messages'),
textarea = getNode('.chat textarea'),
chatName = getNode('.chat-name'),
statusDefault = status.textContent,
setStatus = function(s){
status.textContent = s;
if(s !== statusDefault){
var delay = setTimeout(function(){
setStatus(statusDefault);
clearInterval(delay);
}, 3000);
}
};
//try connection
try{
var socket = io.connect('http://127.0.0.1:8080');
} catch(e){
//Set status to warn user
}
if(socket !== undefined){
//Listen for output
socket.on('output', function(data){
if(data.length){
//Loop through results
for(var x = 0; x < data.length; x = x + 1){
var message = document.createElement('div');
message.setAttribute('class', 'chat-message');
message.textContent = data[x].name + ': ' + data[x].message;
//Append
messages.appendChild(message);
messages.insertBefore(message, messages.firstChild);
}
}
});
//Listen for a status
socket.on('status', function(data){
setStatus((typeof data === 'object') ? data.message : data);
if(data.clear === true){
textarea.value = '';
}
});
//Listen for keydown
textarea.addEventListener('keydown', function(event){
var self = this,
name = chatName.value;
if(event.which === 13 && event.shiftKey === false){
socket.emit('input', {
name: name,
message: self.value
});
}
});
}
})();
</script>
</body>
</html>
To add a css selector to the name:
var message = document.createElement('div');
message.setAttribute('class', 'chat-message');
message.textContent = ': ' + data[x].message;
var name=document.createElement('span');
name.setAttribute('class', 'userName');
name.textContent = data[x].name;
message.insertBefore(name, message.firstChild);
Then for css:
.userName{
font-weight: 700;
}
Here's a fiddle for you to see the results: https://jsfiddle.net/p4yfxLd0/

input type=“file” is not working with phonegap

I have to implement file upload feature in my phonegap project. User should be able to upload any type of file from the phone memory or sd card. The application screens I designed using jQuery Mobile framework. I used the below code to invoke the file browser and for the selection of the file.
<input type="file" />
When I run the app, its showing the 'Choose File' button. But nothing happens when I click on this button. I tested it in different android devices but facing the same issue. The LogCat window is not showing any error or warning messages. Is input type="file" supported in mobile browser? Is there any alternative way to implement the same?
input file does work with phonegap, but there is a bug on some android versions (4.4-4.4.2)
HTML file input in android webview (android 4.4, kitkat)
For android you can use this plugin: https://github.com/cdibened/filechooser
You need to include necessary files for JQuery, JQuery Mobile and PhoneGap in your project or main file (that invokes File Chooser). Then create a button in the calling page to launch the browser.
<a href="fileBrowser.html" id="browseBtn" data-role="button"
data-inline="true">Browse</a>
Then set parameters for the file chooser just before displaying it. You can do that by handling click event for ‘browseBtn’
var currPath = "";
var currEntry = null;
if (typeof file_Browser_params == 'undefined')
file_Browser_params = new Object();
if (typeof file_Browser_params.directory_browser != 'boolean')
file_Browser_params.directory_browser = false;
if (typeof file_Browser_params.on_folder_select != 'function')
file_Browser_params.on_folder_select = null;
if (typeof file_Browser_params.on_file_select != 'function')
file_Browser_params.on_file_select = null;
if (typeof file_Browser_params.on_ok != 'function')
file_Browser_params.on_ok = null;
if (typeof file_Browser_params.new_file_btn == 'undefined')
file_Browser_params.new_file_btn = true;
if (typeof file_Browser_params.new_folder_btn == 'undefined')
file_Browser_params.new_folder_btn = true;
function init()
{
if (!file_Browser_params.new_file_btn)
$("#new_file_btn").hide();
if (!file_Browser_params.new_folder_btn)
$("#new_dir_btn").hide();
$("#new_file_btn").click(function(){
if (currEntry == null)
return;
var fileName = prompt("Enter File Name","untitled.txt");
if (fileName == null || fileName == '')
return;
currEntry.getFile(fileName,{create:false},function(){
alert("File already exists");
},
function(){
currEntry.getFile(fileName,{create:true}, function(){
//refresh current folder
getEntries(currEntry);
}, function(){
alert("Error creating file " + fileName);
});
});
});
$("#new_dir_btn").click(function(){
if (currEntry == null)
return;
var fileName = prompt("Enter Folder Name","untitled");
if (fileName == null || fileName == '')
return;
currEntry.getDirectory(fileName,{create:false},function(){
alert("Folder already exists");
},
function(){
currEntry.getDirectory(fileName,{create:true}, function(){
//refresh current folder
getEntries(currEntry);
}, function(){
alert("Error creating file " + fileName);
});
});
});
$("#file_browser_ok").click(function(){
if (file_Browser_params.on_ok == null)
return;
file_Browser_params.on_ok(currEntry);
});
if (typeof file_Browser_params.initial_folder == 'undefined' ||
file_Browser_params.initial_folder == null)
{
file_Browser_params.initial_folder = null;
getRootAndDisplay();
}
else
{
getEntries(file_Browser_params.initial_folder);
}
}
function getRootAndDisplay()
{
getRoot(function(dirEntry){
try {
getEntries(dirEntry);
} catch (err)
{
alertError(err);
}
});
}
function getRoot(onGetRoot)
{
if (typeof window.requestFileSystem != 'undefined') {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem){
if (typeof onGetRoot != 'undefined')
onGetRoot(fileSystem.root);
}, function(){
log("Error accessing local file system");
});
}
return null;
}
function upOneLevel()
{
if (currEntry == null)
return;
currEntry.getParent(function(parentArg){
getEntries(parentArg);
}, function(error){
alert("Error getting parent folder");
})
}
function getEntries(dirEntry)
{
if (dirEntry == null)
return;
currPath = dirEntry.fullPath;
currEntry = dirEntry;
$("#curr_folder").html(currPath);
var dirReader = dirEntry.createReader();
dirReader.readEntries(function(entries){
displayEntries(entries);
}, function(err){
if (typeof err.message != 'undefined')
err = err.message;
alert(err);
});
}
function displayEntries(entriesArray)
{
entriesArray.sort(function(a,b){
var str1 = a.name.toLowerCase();
var str2 = b.name.toLowerCase();
if (str1 < str2)
return -1;
if (str1 > str2)
return 1;
return 0;
});
$("#fileBrowser_entries").empty();
var table = $("<table id='file_entry_table'></table>").appendTo("#fileBrowser_entries");
var row = $("<tr class='file_list_row'><td class='file_icon'>D</td><td>..</td></tr>").appendTo(table);
$(row).click(function(event){
upOneLevel();
});
for (var i in entriesArray)
{
var isFolder = entriesArray[i].isDirectory;
var name = entriesArray[i].name;
if (file_Browser_params.directory_browser && !isFolder)
continue;
var row = $("<tr class='file_list_row'></tr>").appendTo(table);
$(row).data("entry", entriesArray[i]);
$("<td class='file_icon'>" + (isFolder ? 'D' : 'F') + "</td>").appendTo(row);
$("<td class='file_name'>" + name + "</td>").appendTo(row);
$(row).click(function(event){
var entryData = $(this).data("entry");
if (entryData.isDirectory) {
if (file_Browser_params.on_folder_select != null)
{
var ret = file_Browser_params.on_folder_select(entryData);
if (ret == false) {
$('.ui-dialog').dialog('close');
return;
}
}
getEntries(entryData);
} else if (file_Browser_params.on_file_select != null)
{
var ret = file_Browser_params.on_file_select(entryData);
if (ret == false) {
$('.ui-dialog').dialog('close');
return;
}
}
});
}
}
function alertError(err){
if (typeof err.message != 'undefined')
err = err.message;
alert(err);
}
init();

Add search filter inside the select dropdown in AngularJS

I want to add a search filter inside a select dropdown in angularJS.
I have used ng-options to list down the options and used filter to filter out the data in the search box , but the problem is that the search box is not coming inside(or under) select dropdown. (When I click the select dropdown, it shows a search filter and below it has all the options)
Below is the code for your reference :
<div class="rowMargin">
<label class="control-label" for="entitySel">Entity:</label>
<div class="controls">
<select id="entityId" class="input-medium" type="text" name="entityId" ng-model="payment.entityId" ng-options="entityOpt for entityOpt in paymentEntityOptions">
<option value="">Select</option>
</select>
<span ng-show=" submitted && addPayment.entityId.$error.required">
<label class="error">Please provide entity Id </label>
</span>
<div ng-show="payment.entityId == \'Individual\'">
<span>
<select ng-model="payment.entity.individual" ng-options = "individual for individual in individualEntities | filter : filterEntity">
<option value="">Select Individual Entity</option>
<option>
<input type="search" placeholder="Search" ng-model="filterEntity"></input>
</option>
</select>
</span>
</div>
<div ng-show="payment.entityId == \'Group\'">
<span>
<select ng-model="payment.entity.group" ng-options = "group for group in groupEntities | filter : filterEntity">
<option value="">Select Group Entity</option>
<input type="search" placeholder="Search" ng-model="filterEntity"></input>
</select>
</span>
</div>
</div>
I have used the bootstrap button with class 'dropdown-toggle' and on click of the button I have appended an input search box as following :
<div class="dropdown pull-right makePaymentDropdownMainDiv" auto-close="outsideClick">
<button class="btn btn-default dropdown-toggle makePaymentDropdownBtn" type="button" id="individualDrop" data-toggle="dropdown">{{payment.entity}}<span class="caret pull-right"></span></button>
<span ng-show="submitted"><label class="error">Select an Individual</label></span>
<ul class="dropdown-menu makePaymentDropdownUlStyle" role="menu" aria-labelledby="individualDrop">
<input disable-auto-close type="search" ng-model="serchFilter" class="makePaymentDropdownSearchBox" placeholder="Search"></input>
<li role="presentation" ng-repeat="indi in individuals | filter: serchFilter"><a role="menuitem" ng-click="selectEntity(indi)">{{indi}}</a></li>
</ul>
</div>
Showing the 'li' using ng-repeat.
Remember to add auto-close="outsideClick" to your dropdown so that it doesn't close on filtering attempt.
Sorry, I'm rather late to the party, but to me it sounds like you need acute-select, an open source extension (MIT license) to Angular that does exactly this, without further dependencies.
They also have a demo page, which shows what it can do nicely.
you can use easy and best way to search filter inside the select dropdown in AngularJS
Working Demo : http://plnkr.co/edit/o767Mg6fQoyc7jKq77If?p=preview
(function (angular, undefined) {
'use strict';
// TODO: Move to polyfill?
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g, '');
};
}
/**
* A replacement utility for internationalization very similar to sprintf.
*
* #param replace {mixed} The tokens to replace depends on type
* string: all instances of $0 will be replaced
* array: each instance of $0, $1, $2 etc. will be placed with each array item in corresponding order
* object: all attributes will be iterated through, with :key being replaced with its corresponding value
* #return string
*
* #example: 'Hello :name, how are you :day'.format({ name:'John', day:'Today' })
* #example: 'Records $0 to $1 out of $2 total'.format(['10', '20', '3000'])
* #example: '$0 agrees to all mentions $0 makes in the event that $0 hits a tree while $0 is driving drunk'.format('Bob')
*/
function format(value, replace) {
if (!value) {
return value;
}
var target = value.toString();
if (replace === undefined) {
return target;
}
if (!angular.isArray(replace) && !angular.isObject(replace)) {
return target.split('$0').join(replace);
}
var token = angular.isArray(replace) && '$' || ':';
angular.forEach(replace, function (value, key) {
target = target.split(token + key).join(value);
});
return target;
}
var module = angular.module('AxelSoft', []);
module.value('customSelectDefaults', {
displayText: 'Select...',
emptyListText: 'There are no items to display',
emptySearchResultText: 'No results match "$0"',
addText: 'Add',
searchDelay: 300
});
module.directive('customSelect', ['$parse', '$compile', '$timeout', '$q', 'customSelectDefaults', function ($parse, $compile, $timeout, $q, baseOptions) {
var CS_OPTIONS_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?\s+for\s+(?:([\$\w][\$\w\d]*))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/;
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, elem, attrs, controller) {
var customSelect = attrs.customSelect;
if (!customSelect) {
throw new Error('Expected custom-select attribute value.');
}
var match = customSelect.match(CS_OPTIONS_REGEXP);
if (!match) {
throw new Error("Expected expression in form of " +
"'_select_ (as _label_)? for _value_ in _collection_[ track by _id_]'" +
" but got '" + customSelect + "'.");
}
elem.addClass('dropdown custom-select');
// Ng-Options break down
var displayFn = $parse(match[2] || match[1]),
valueName = match[3],
valueFn = $parse(match[2] ? match[1] : valueName),
values = match[4],
valuesFn = $parse(values),
track = match[5],
trackByExpr = track ? " track by " + track : "",
dependsOn = attrs.csDependsOn;
var options = getOptions(),
timeoutHandle,
lastSearch = '',
focusedIndex = -1,
matchMap = {};
var itemTemplate = elem.html().trim() || '{{' + (match[2] || match[1]) + '}}',
dropdownTemplate =
'<a class="dropdown-toggle" data-toggle="dropdown" href ng-class="{ disabled: disabled }">' +
'<span>{{displayText}}</span>' +
'<b></b>' +
'</a>' +
'<div class="dropdown-menu">' +
'<div stop-propagation="click" class="custom-select-search">' +
'<input class="' + attrs.selectClass + '" type="text" autocomplete="off" ng-model="searchTerm" />' +
'</div>' +
'<ul role="menu">' +
'<li role="presentation" ng-repeat="' + valueName + ' in matches' + trackByExpr + '">' +
'<a role="menuitem" tabindex="-1" href ng-click="select(' + valueName + ')">' +
itemTemplate +
'</a>' +
'</li>' +
'<li ng-hide="matches.length" class="empty-result" stop-propagation="click">' +
'<em class="muted">' +
'<span ng-hide="searchTerm">{{emptyListText}}</span>' +
'<span class="word-break" ng-show="searchTerm">{{ format(emptySearchResultText, searchTerm) }}</span>' +
'</em>' +
'</li>' +
'</ul>' +
'<div class="custom-select-action">' +
(typeof options.onAdd === "function" ?
'<button type="button" class="btn btn-primary btn-block add-button" ng-click="add()">{{addText}}</button>' : '') +
'</div>' +
'</div>';
// Clear element contents
elem.empty();
// Create dropdown element
var dropdownElement = angular.element(dropdownTemplate),
anchorElement = dropdownElement.eq(0).dropdown(),
inputElement = dropdownElement.eq(1).find(':text'),
ulElement = dropdownElement.eq(1).find('ul');
// Create child scope for input and dropdown
var childScope = scope.$new(true);
configChildScope();
// Click event handler to set initial values and focus when the dropdown is shown
anchorElement.on('click', function (event) {
if (childScope.disabled) {
return;
}
childScope.$apply(function () {
lastSearch = '';
childScope.searchTerm = '';
});
focusedIndex = -1;
inputElement.focus();
// If filter is not async, perform search in case model changed
if (!options.async) {
getMatches('');
}
});
if (dependsOn) {
scope.$watch(dependsOn, function (newVal, oldVal) {
if (newVal !== oldVal) {
childScope.matches = [];
childScope.select(undefined);
}
});
}
// Event handler for key press (when the user types a character while focus is on the anchor element)
anchorElement.on('keypress', function (event) {
if (!(event.altKey || event.ctrlKey)) {
anchorElement.click();
}
});
// Event handler for Esc, Enter, Tab and Down keys on input search
inputElement.on('keydown', function (event) {
if (!/(13|27|40|^9$)/.test(event.keyCode)) return;
event.preventDefault();
event.stopPropagation();
switch (event.keyCode) {
case 27: // Esc
anchorElement.dropdown('toggle');
break;
case 13: // Enter
selectFromInput();
break;
case 40: // Down
focusFirst();
break;
case 9:// Tab
anchorElement.dropdown('toggle');
break;
}
});
// Event handler for Up and Down keys on dropdown menu
ulElement.on('keydown', function (event) {
if (!/(38|40)/.test(event.keyCode)) return;
event.preventDefault();
event.stopPropagation();
var items = ulElement.find('li > a');
if (!items.length) return;
if (event.keyCode == 38) focusedIndex--; // up
if (event.keyCode == 40 && focusedIndex < items.length - 1) focusedIndex++; // down
//if (!~focusedIndex) focusedIndex = 0;
if (focusedIndex >= 0) {
items.eq(focusedIndex)
.focus();
} else {
focusedIndex = -1;
inputElement.focus();
}
});
resetMatches();
// Compile template against child scope
$compile(dropdownElement)(childScope);
elem.append(dropdownElement);
// When model changes outside of the control, update the display text
controller.$render = function () {
setDisplayText();
};
// Watch for changes in the default display text
childScope.$watch(getDisplayText, setDisplayText);
childScope.$watch(function () { return elem.attr('disabled'); }, function (value) {
childScope.disabled = value;
});
childScope.$watch('searchTerm', function (newValue) {
if (timeoutHandle) {
$timeout.cancel(timeoutHandle);
}
var term = (newValue || '').trim();
timeoutHandle = $timeout(function () {
getMatches(term);
},
// If empty string, do not delay
(term && options.searchDelay) || 0);
});
// Support for autofocus
if ('autofocus' in attrs) {
anchorElement.focus();
}
var needsDisplayText;
function setDisplayText() {
var locals = { };
locals[valueName] = controller.$modelValue;
var text = displayFn(scope, locals);
if (text === undefined) {
var map = matchMap[hashKey(controller.$modelValue)];
if (map) {
text = map.label;
}
}
needsDisplayText = !text;
childScope.displayText = text || options.displayText;
}
function getOptions() {
return angular.extend({}, baseOptions, scope.$eval(attrs.customSelectOptions));
}
function getDisplayText() {
options = getOptions();
return options.displayText;
}
function focusFirst() {
var opts = ulElement.find('li > a');
if (opts.length > 0) {
focusedIndex = 0;
opts.eq(0).focus();
}
}
// Selects the first element on the list when the user presses Enter inside the search input
function selectFromInput() {
var opts = ulElement.find('li > a');
if (opts.length > 0) {
var ngRepeatItem = opts.eq(0).scope();
var item = ngRepeatItem[valueName];
childScope.$apply(function () {
childScope.select(item);
});
anchorElement.dropdown('toggle');
}
}
function getMatches(searchTerm) {
var locals = { $searchTerm: searchTerm }
$q.when(valuesFn(scope, locals)).then(function (matches) {
if (!matches) return;
if (searchTerm === inputElement.val().trim()/* && hasFocus*/) {
matchMap = {};
childScope.matches.length = 0;
for (var i = 0; i < matches.length; i++) {
locals[valueName] = matches[i];
var value = valueFn(scope, locals),
label = displayFn(scope, locals);
matchMap[hashKey(value)] = {
value: value,
label: label/*,
model: matches[i]*/
};
childScope.matches.push(matches[i]);
}
//childScope.matches = matches;
}
if (needsDisplayText) setDisplayText();
}, function() {
resetMatches();
});
}
function resetMatches() {
childScope.matches = [];
focusedIndex = -1;
};
function configChildScope() {
childScope.addText = options.addText;
childScope.emptySearchResultText = options.emptySearchResultText;
childScope.emptyListText = options.emptyListText;
childScope.select = function (item) {
var locals = {};
locals[valueName] = item;
var value = valueFn(childScope, locals);
//setDisplayText(displayFn(scope, locals));
childScope.displayText = displayFn(childScope, locals) || options.displayText;
controller.$setViewValue(value);
anchorElement.focus();
typeof options.onSelect === "function" && options.onSelect(item);
};
childScope.add = function () {
$q.when(options.onAdd(), function (item) {
if (!item) return;
var locals = {};
locals[valueName] = item;
var value = valueFn(scope, locals),
label = displayFn(scope, locals);
matchMap[hashKey(value)] = {
value: value,
label: label/*,
model: matches[i]*/
};
childScope.matches.push(item);
childScope.select(item);
});
};
childScope.format = format;
setDisplayText();
}
var current = 0;
function hashKey(obj) {
if (obj === undefined) return 'undefined';
var objType = typeof obj,
key;
if (objType == 'object' && obj !== null) {
if (typeof (key = obj.$$hashKey) == 'function') {
// must invoke on object to keep the right this
key = obj.$$hashKey();
} else if (key === undefined) {
key = obj.$$hashKey = 'cs-' + (current++);
}
} else {
key = obj;
}
return objType + ':' + key;
}
}
};
}]);
module.directive('stopPropagation', function () {
return {
restrict: 'A',
link: function (scope, elem, attrs, ctrl) {
var events = attrs['stopPropagation'];
elem.bind(events, function (event) {
event.stopPropagation();
});
}
};
});
})(angular);
<body ng-app="Demo">
<div class="container" ng-controller="DemoController">
<label>Level 1</label>
<div custom-select="g for g in nestedItemsLevel1 | filter: $searchTerm" custom-select-options="level1Options" ng-model="level1"></div>
<label>Level 2</label>
<div custom-select="g for g in nestedItemsLevel2 | filter: $searchTerm" ng-model="level2" cs-depends-on="level1"></div>
</div>
<!-- basic scripts -->
<!--[if !IE]> -->
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<!-- <![endif]-->
<!--[if IE]>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<![endif]-->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/2.3.2/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<script src="js/customSelect.js"></script>
<script>
(function () {
var app = angular.module('Demo', ['AxelSoft']);
app.controller('DemoController', ['$scope', '$timeout', '$q', function ($scope, $timeout, $q) {
$scope.searchAsync = function (term) {
// No search term: return initial items
if (!term) {
return ['Item 1', 'Item 2', 'Item 3'];
}
var deferred = $q.defer();
$timeout(function () {
var result = [];
for (var i = 1; i <= 3; i++)
{
result.push(term + ' ' + i);
}
deferred.resolve(result);
}, 300);
return deferred.promise;
};
$scope.nestedItemsLevel1 = ['Item 1', 'Item 2', 'Item 3'];
$scope.level1 = $scope.nestedItemsLevel1[0];
$scope.level1Options = {
onSelect: function (item) {
var items = [];
for (var i = 1; i <= 5; i++) {
items.push(item + ': ' + 'Nested ' + i);
}
$scope.nestedItemsLevel2 = items;
}
};
$scope.nestedItemsLevel2 = [];
$scope.level1Options.onSelect($scope.nestedItemsLevel1[0]);
}]);
})();
</script>
</body>
https://docs.angularjs.org/api/ng/directive/select
There can be only one hard coded in a ngOption.

Client-Side Validation for entire model using MVC 3 (unobtrusive ajax)

I've got client-side validation working for individual properties, however, I would like to validate at the model level (2 or more properties) using client-side validation.
I'm using #Html.ValidationSummary(true) to display the validation error for the Model attribute that I created.
However, when the model error is generated, it doesn't display a message. It prevents the action from being made, but no error is displayed.
Anybody know why this would be the case?
My hunch is that it has something to do with client-side validation since server-side doesn't work in this case since I have to use an Ajax form.
Any advice would be appreciated!
Model Attribute
public class AuditDetailValidatorAttribute : ValidationAttribute, IClientValidatable
{
public AuditDetailValidatorAttribute()
{
ErrorMessage = "Must select an NCN level...";
}
public override bool IsValid(object value)
{
AuditRequirementDetail audit = value as AuditRequirementDetail;
if (audit == null || audit.AuditResult.Id == 0 || audit.AssessmentLevel.Id == 0)
{
return true;
}
else
{
return !(audit.AuditResult.Id == 4 && audit.AssessmentLevel.Id == 1);
}
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
return new List<ModelClientValidationRule>
{
new ModelClientValidationRule
{
ValidationType = "required",
ErrorMessage = this.ErrorMessage
}
};
}
}
Model Class
[AuditDetailValidator]
public class AuditRequirementDetail
{
// Constructor
public AuditRequirementDetail()
{
// instantiate the contained objects on AuditRequirementDetail creation
AssessmentLevel = new AssessmentLevel();
AuditResult = new AuditResult();
Requirement = new RequirementDetail();
Attachment = new Attachment();
Counter = 0;
}
/* rest of the code */
}
View
#model pdiqc.Models.AuditRequirement.AuditRequirementDetail
#{
var SuccessTarget = "success" + Model.DetailID;
var IsValidTarget = "IsValid" + Model.DetailID;
var PerformCompletedTarget = "PerformCompleted" + Model.DetailID;
var AuditResultTarget = "AuditResult_Id" + Model.DetailID;
var AssessmentLevelTarget = "AssessmentLevel_Id" + Model.DetailID;
var DesignatorTarget = "Designator_Id" + Model.DetailID;
var EvidenceTarget = "Evidence_Id" + Model.DetailID;
var AttachmentTarget = "Attachments_Id" + Model.DetailID;
var AuditResultReferral = "#" + AuditResultTarget;
var AssessmentLevelReferral = "#" + AssessmentLevelTarget;
var DesignatorReferral = "#" + DesignatorTarget;
var EvidenceReferral = "#" + EvidenceTarget;
var AttachmentReferral = "#" + AttachmentTarget;
}
#using (Ajax.BeginForm("PerformRequirement", "Audit", new AjaxOptions { HttpMethod = "POST", OnSuccess = "success" }, new {Class="PerformReqForm" }))
{
#Html.ValidationSummary(true)
if ((Model.AuditResult.Id == 1 && Model.AssessmentLevel.Id > 1) || Model.Evidence == string.Empty || Model.Evidence == null)
{
<input class="#IsValidTarget" name="IsValid" type="hidden" value=false />
}
else
{
<input class="#IsValidTarget" name="IsValid" type="hidden" value=true />
}
<p class="reqText">#Model.RequirementLabel.ConfigurableLabelDesc ##ViewBag.PerformCounter - #ModelMetadata.FromLambdaExpression(x => x.Requirement.Text, ViewData).SimpleDisplayText</p>
<div class="hide">
/* REST OF CODE */
}
I wrote a custom validator for a checkbox to make sure it was cheeked and had to do the following.
<script type="text/javascript">
$(function() {
$.validator.unobtrusive.adapters.addBool('requiredcheckbox', 'required');
}(jQuery));
</script>
Also include #Html.ValidationMessageFor(x=>x.yourProp)

jQuery - google chrome won't get updated textarea value

I have a textarea with default text 'write comment...'. when a user updates the textarea and clicks 'add comment' Google chrome does not get the new text. heres my code;
function add_comment( token, loader ){
$('textarea.n-c-i').focus(function(){
if( $(this).html() == 'write a comment...' ) {
$(this).html('');
}
});
$('textarea.n-c-i').blur(function(){
if( $(this).html() == '' ) {
$(this).html('write a comment...');
}
});
$(".add-comment").bind("click", function() {
try{
var but = $(this);
var parent = but.parents('.n-w');
var ref = parent.attr("ref");
var comment_box = parent.find('textarea');
var comment = comment_box.val();
alert(comment);
var con_wrap = parent.find('ul.com-box');
var contents = con_wrap .html();
var outa_wrap = parent.find('.n-c-b');
var outa = outa_wrap.html();
var com_box = parent.find('ul.com-box');
var results = parent.find('p.com-result');
results.html(loader);
comment_box.attr("disabled", "disabled");
but.attr("disabled", "disabled");
$.ajax({
type: 'POST', url: './', data: 'add-comment=true&ref=' + encodeURIComponent(ref) + '&com=' + encodeURIComponent(comment) + '&token=' + token + '&aj=true', cache: false, timeout: 7000,
error: function(){ $.fancybox(internal_error, internal_error_fbs); results.html(''); comment_box.removeAttr("disabled"); but.removeAttr("disabled"); },
success: function(html){
auth(html);
if( html != '<span class="error-msg">Error, message could not be posted at this time</span>' ) {
if( con_wrap.length == 0 ) {
outa_wrap.html('<ul class="com-box">' + html + '</ul>' + outa);
outa_wrap.find('li:last').fadeIn();
add_comment( token, loader );
}else{
com_box.html(contents + html);
com_box.find('li:last').fadeIn();
}
}
results.html('');
comment_box.removeAttr("disabled");
but.removeAttr("disabled");
}
});
}catch(err){alert(err);}
return false;
});
}
any help much appreciated.
I believe you should be using val() and not html() on a textarea.
On a side note, for Chrome use the placeholder attribute on the textarea. You won't need a lot of this code.
<textarea placeholder="Write a comment"></textarea>