My form check does not work. If I leave alias field empty it returns name field as filled.
var alias = document.getElementById("alias");
var name = document.getElementById("name");
var status = '';
function checkIt() {
if (alias.value != '') {
document.getElementById("alias").style.borderColor = "#3c763d";
return true;
} else {
document.getElementById("alias").style.borderColor = "#a94442";
status = false;
}
if (name.value != '') {
document.getElementById("name").style.borderColor = "#3c763d";
return true;
} else {
document.getElementById("name").style.borderColor = "#a94442";
status = false;
}
}
name.onblur=checkIt;
alias.onblur=checkIt;
Try this, you should use current object this instead of global variable when eventing firing
var alias = document.getElementById("alias");
var name = document.getElementById("name");
var status = '';
function checkIt() {
if (this.value != '') {
this.style.borderColor = "#3c763d";
status = true;
} else {
this.style.borderColor = "#a94442";
status = false;
}
}
name.onblur=checkIt;
alias.onblur=checkIt;
JSFIDDLE DEMO
Try this one:
Plain Js
script
var validate = function(e) {
var v = this.value;
this.style.borderColor = ('' !== v) ? '#3c763d' : '#a94442';
};
document.getElementById('alias').onblur = validate;
document.getElementById('name').onblur = validate;
JQuery
script
$(function(){
$("#alias, #name").on('focusout', function() {
var box = $(this);
var c = ('' !== box.val()) ? '#3c763d' : '#a94442';
box.css('border-color', c);
});
})
Related
I am trying to fix this script to automatically connect people you may know on Linkedin based on User roles (CEO e.t.c), Can someone help me fix this, Below is my code; I have tried the script on almost all browsers, Somebody help fix this.
var userRole = [
"CEO",
"CIO"
];
var inviter = {} || inviter;
inviter.userList = [];
inviter.className = 'button-secondary-small';
inviter.refresh = function () {
window.scrollTo(0, document.body.scrollHeight);
window.scrollTo(document.body.scrollHeight, 0);
window.scrollTo(0, document.body.scrollHeight);
};
inviter.initiate = function()
{
inviter.refresh();
var connectBtns = $(".button-secondary-small:visible");
//
if (connectBtns == null) {var connectBtns = inviter.initiate();}
return connectBtns;
};
inviter.invite = function () {
var connectBtns = inviter.initiate();
var buttonLength = connectBtns.length;
for (var i = 0; i < buttonLength; i++) {
if (connectBtns != null && connectBtns[i] != null) {inviter.handleRepeat(connectBtns[i]);}
//if there is a connect button and there is at least one that has not been pushed, repeat
if (i == buttonLength - 1) {
console.log("done: " + i);
inviter.refresh();
}
}
};
inviter.handleRepeat = function(button)
{
var nameValue = button.children[1].textContent
var name = nameValue.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
function hasRole(role){
for(var i = 0; i < role.length; i++) {
// cannot read children of undefined
var position = button.parentNode.parentNode.children[1].children[1].children[0].children[3].textContent;
var formatedPosition = position.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
var hasRole = formatedPosition.indexOf(role[i]) == -1 ? false : true;
console.log('Has role: ' + role[i] + ' -> ' + hasRole);
if (hasRole) {
return hasRole;
}
}
return false;
}
if(inviter.arrayContains(name))
{
console.log("canceled");
var cancel = button.parentNode.parentNode.children[0];
cancel.click();
}
else if (hasRole(userRole) == false) {
console.log("cancel");
var cancel = button.parentNode.parentNode.children[0];
cancel.click();
}
else if (button.textContent.indexOf("Connect")<0){
console.log("skipped");
inviter.userList.push(name); // it's likely that this person didn't join linkedin in the meantime, so we'll ignore them
var cancel = button.parentNode.parentNode.children[0];
cancel.click();
}
else {
console.log("added");
inviter.userList.push(name);
button.click();
}
};
inviter.arrayContains = function(item)
{
return (inviter.userList.indexOf(item) > -1);
};
inviter.usersJson = {};
inviter.loadResult = function()
{
var retrievedObject = localStorage.getItem('inviterList');
var temp = JSON.stringify(retrievedObject);
inviter.userList = JSON.parse(temp);
};
inviter.saveResult = function()
{
inviter.usersJson = JSON.stringify(inviter.userList);
localStorage.setItem('inviterList', inviter.usersJson);
};
setInterval(function () { inviter.invite(); }, 5000);
`
When I try executing this, I get the following error:
VM288:49 Uncaught TypeError: Cannot read property 'children' of undefined
at hasRole (<anonymous>:49:71)
at Object.inviter.handleRepeat (<anonymous>:66:11)
at Object.inviter.invite (<anonymous>:30:69)
at <anonymous>:108:35
Any ideas as to how to fix it?
I've written a sample autocomplete application that works as I intended.
HTML
<div class="wrapper">
<div class="search">
<input type="text" id="search" placeholder="Search" onkeyup="autoComplete(this.value)">
<button onclick="search()">Go</button>
<ul id="suggest">
</ul>
</div>
<div class="result">
</div>
</div>
Script
var data = ['Bob', 'Aria', 'Smith', 'Jack', 'Cethy', 'Brad', 'Jony', 'Dan', 'Ashley', 'Janice'];
var suggestionArray = [];
var search = function(){
var searchTerm = document.getElementById('search').value;
if(searchTerm == undefined || searchTerm == ""){
return false;
}
console.log('You are searching for ' + searchTerm);
}
var clearSuggestion = function() {
suggestionArray = [];
}
var addListenersToChild = function(){
var el = document.getElementById('suggest');
el.addEventListener('click', function(event){
var searchTerm = event.target.textContent;
document.getElementById('search').value = searchTerm;
clearSuggestion();
showSuggestion();
}, false)
}
var showSuggestion = function(){
var el = document.getElementById('suggest');
el.innerHTML = "";
if(suggestionArray.length>0){
suggestionArray.forEach(function(suggestTerm){
var node = document.createElement('li');
var textnode = document.createTextNode(suggestTerm);
node.appendChild(textnode);
el.appendChild(node);
});
addListenersToChild();
}
}
var formSuggestionArray = function(dataTerm){
if(suggestionArray.indexOf(dataTerm) > -1){
return false;
} else {
suggestionArray.push(dataTerm);
}
}
var matchVal = function(val){
clearSuggestion();
for(var i=0; i<data.length;i++){
if(data[i].toLowerCase().indexOf(val.toLowerCase()) > -1) {
formSuggestionArray(data[i]);
}
}
}
var autoComplete = function(val){
if(val == undefined || val == ""){
clearSuggestion();
showSuggestion();
return false;
}
matchVal(val);
showSuggestion();
}
I am not sure, if the way I've written the code is the best way to do so. So for example, what I need to know is that if my current program is
good for readability
is optimized
follows the best practices or not
How can I improve the code
Looks GREAT to me, however...
var data = ['Bob', 'Aria', 'Smith', 'Jack', 'Cethy', 'Brad', 'Jony', 'Dan', 'Ashley', 'Janice'];
var suggestionArray = [];
/* Caching these two element nodes speeds things up a bit.. */
var search_element = document.getElementById('search');
var suggestion_element = document.getElementById('suggest');
var search = function(){
var searchTerm = search_element.value;
// concise falsey, TRUE IF `searchTerm` == 0 || undefined || ""
if(!searchTerm){
return false;
}
console.log('You are searching for ' + searchTerm);
}
/*
plurize because contains multiple values,
optionally can just do `suggestionArray.length = 0` equivalent
*/
var clearSuggestions = function() {
suggestionArray = [];
}
var addListenersToChild = function(){
suggestion_element.addEventListener('click', function(event){
var searchTerm = event.target.textContent;
search_element.value = searchTerm;
clearSuggestions();
showSuggestion();
}, false)
}
var showSuggestion = function(){
suggestion_element.innerHTML = "";
/* implicit casting/coersion - IF length == 0 (false) ELSE (true) */
if(suggestionArray.length){
/* reuse this `node` variable */
var node;
suggestionArray.forEach(function(suggestTerm){
node = document.createElement('li');
node.textContent = suggestTerm;
/*
too verbose/unnecessary in my opinion
var textnode = document.createTextNode(suggestTerm);
node.appendChild(textnode);
*/
suggestion_element.appendChild(node);
});
addListenersToChild();
}
}
var formSuggestionArray = function(dataTerm){
/* you can use a native `Set` for `suggestionArray`, insures unique entries */
if(suggestionArray.indexOf(dataTerm) > -1){
return false;
} else {
suggestionArray.push(dataTerm);
}
}
var matchVal = function(val){
clearSuggestions();
for(var i=0; i<data.length;i++){
if(data[i].toLowerCase().indexOf(val.toLowerCase()) > -1) {
formSuggestionArray(data[i]);
}
}
}
var autoComplete = function(val){
// concise falsey, TRUE IF `val` == 0 || undefined || ""
if(!val){
clearSuggestions();
showSuggestion();
return false;
}
matchVal(val);
showSuggestion();
}
I want to print specific emty error message as well as number error message for the age field while during the button click. for my code only the last error message is diplaying.
This is for Validation Purpose.
<script type="text/javascript">
$(document).ready(function () {
$("#<%=btnSubmit.ClientID %>").click(function () {
var error = 0;
var name = $('#<%=txtName.ClientID%>').val();
if ($.trim(name) == '') {
$('#name_error_msg').text('Name cannot be Empty');
$('#name_error_msg').parent().show();
error = 1;
} else
$('#name_error_msg').text('');
var country = $('#<%=ddlCountry.ClientID%>').val();
if (country == 0) {
$('#country_error_msg').text('Please select the Country');
$('#country_error_msg').parent().show();
error = 1;
}
else
$('#country_error_msg').text('');
var age = $('#<%=txtAge.ClientID%>').val();
if ($.trim(age) == '') {
$('#age_error_msg').text('Invalid Age');
$('#age_error_msg').parent().show();
error = 1;
}
var filter = /^[0-9-+]+$/;
if (!filter.test(age)) {
$('#age_error_msg').text('Invalid Age');
$('#age_error_msg').parent().show();
error = 1;
}
else
$('#age_error_msg').text('');
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (!filter.test(emailReg)) {
$('#email_error_msg').text('Invalid email format');
$('#email_error_msg').parent().show();
error = 1;
}
else {
$('#email_error_msg').text('');
}
var email = $('#<%=txtEmail.ClientID%>').val();
if ($.trim(email) == '') {
$('#email_error_msg').text('Email cannot be Empty');
$('#email_error_msg').parent().show();
error = 1;
} else {
$('#email_error_msg').text('');
}
if (!($('#<%=ChkAgree.ClientID%>').is(':checked'))) {
error = 1;
$('#check_error_msg').html("Please Tick the Agree to Terms of Use.");
$('#check_error_msg').parent().show();
}
else
$('#check_error_msg').html(" ");
if (error) {
return false;
} else {
return true;
}
});
});
</script>
All you need to do is, replace:
var age = $('#<%=txtAge.ClientID%>').val();
if ($.trim(age) == '') {
$('#age_error_msg').text('Invalid Age');
$('#age_error_msg').parent().show();
error = 1;
}
var filter = /^[0-9-+]+$/;
if (!filter.test(age)) {
$('#age_error_msg').text('Invalid Age');
$('#age_error_msg').parent().show();
error = 1;
}
else
$('#age_error_msg').text('');
with:
var filter = /^[0-9-+]+$/;
var age = $('#<%=txtAge.ClientID%>').val();
if ( $.trim(age) == '' || !filter.test(age)) {
$('#age_error_msg').text('Invalid Age');
$('#age_error_msg').parent().show();
error = 1;
} else {
$('#age_error_msg').text('');
}
You could create a temp variable to add up each error.
var age_errors = [];
var age = $('#<%=txtAge.ClientID%>').val();
if ($.trim(age) == '') {
age_errors.push('Age is empty');
$('#age_error_msg').parent().show();
error = 1;
}
var filter = /^[0-9-+]+$/;
if (!filter.test(age)) {
age_errors.push('Invalid Age number');
$('#age_error_msg').parent().show();
error = 1;
}
// set the error: empty string or a comma-separated list.
$('#age_error_msg').text(age_errors.join(', '));
I have three select boxes which filter the table on with different criteria. For example, if a user wants to see records with Medium priorities, a Yes On Air Critical & Closed Status. Closed is a data-attribute for every row.
I can do that but my issue is if user wants to select a single filter again, it just shows blank result. Here's the javascript:
$("#input_filter_priority").change(function() {
var data = this.value.split(" ");
var $tr_row = $('#project_table').find("tr:not(.hidden)");
var priority_column = $('#project_table').find("tr :not(.hidden) td:nth-child(5)");
if (this.value == "") {
$tr_row.show();
return;
}
$tr_row.hide();
if (filtered_row !== null) {
filtered_row = filtered_row.filter(function() {
$r = $(this);
if ($r.is(":contains('" + data + "')")) {
return true;
}
return false;
})
.show();
} else {
filtered_row = $tr_row.filter(function() {
$tr_text = $(this).val();
$r = $(this);
if ($r.is(":contains('" + data + "')")) {
return true;
}
return false;
})
.show();
}
});
$("#input_closed_filter").change(function() {
var data = this.value.split(" ");
var $tr_row = $('#project_table').find("tr:not(.hidden)");
if (this.value == "") {
$tr_row.show();
return;
}
$tr_row.hide();
if (filtered_row !== null) {
filtered_row = filtered_row.filter(function() {
$r = $(this);
if ($(this).attr('data-closed').match(data)) {
return true;
}
return false;
})
.show();
} else {
filtered_row = $tr_row.filter(function() {
$tr_text = $(this).val();
if ($(this).attr('data-closed').match(data)) {
return true;
}
return false;
})
.show();
}
});
$("#input_on_air_filter").change(function() {
var data = this.value.split(" ");
var $tr_row = $('#project_table').find("tr ");
var on_air_column = $('#project_table').find("tr td:nth-child(6)");
if (this.value == "") {
$tr_row.show();
return;
}
$tr_row.hide();
if (filtered_row !== null) {
filtered_row = filtered_row.filter(function() {
$r = $(this);
if ($(this).attr('data-critical').match(data)) {
return true;
}
return false;
})
.show();
} else {
filtered_row = $tr_row.filter(function() {
$tr_text = $(this).val();
$r = $(this);
if ($(this).attr('data-critical').match(data)) {
return true;
}
return false;
})
.show();
}
});
What should I do here in case user selects same filter twice or any number of times (Suppose if he changes his mind).
Here's the related JSBin.
Here is a simplified/working version:
var priorityFilterData=null;
var onAirCriticalFilterData=null;
var closedFilterData=null;
function applyFilters(){
var $tr_row = $('#project_table').find("tr");
$tr_row.hide();//hide all rows by default
//Show only the rows that meet each filter condition
$tr_row.filter(function(){
var closedFilterCondition = (closedFilterData === null || $(this).attr('data-closed').match(closedFilterData));
var onAirFilterCondition = (onAirCriticalFilterData === null || $(this).attr('data-critical').match(onAirCriticalFilterData));
var priorityFilterCondition = (priorityFilterData === null || $(this).is(":contains('" + priorityFilterData + "')"));
return closedFilterCondition && onAirFilterCondition && priorityFilterCondition;
}).show();
}
$("#input_closed_filter").change(function() {
closedFilterData = this.value.split(" ");
applyFilters();
});
$("#input_on_air_filter").change(function() {
onAirCriticalFilterData = this.value.split(" ");
applyFilters();
});
$("#input_filter_priority").change(function() {
priorityFilterData = this.value.split(" ");
applyFilters();
});
what is wrong with this code I get an undefined error. my checkbox is not an array on front end it uses different names and I want user to select only one checkbox:
function select_item(index){
var choice_options = [];
choice_options['S'] = 'item_cb_S';
choice_options['T'] = 'item_cb_T';
choice_options['Z'] = 'item_cb_Z';
choice_options['D'] = 'item_cb_D';
choice_options['N'] = 'item_cb_N';
for (i in choice_options) {
var vl = choice_options[i];
if(vl.substring(8) == index) {
document.wizardform.choice_options[index].checked = true;
//alert("true");
}
else {
document.wizardform.vl.checked = false;
}
}
return true;
}
It's not so pretty but you could use eval......
function select_item(index){
var choice_options = [];
choice_options['S'] = 'item_cb_S';
choice_options['T'] = 'item_cb_T';
choice_options['Z'] = 'item_cb_Z';
choice_options['D'] = 'item_cb_D';
choice_options['N'] = 'item_cb_N';
for (i in choice_options) {
var vl = choice_options[i];
if(vl.substring(8) == index) {
eval("document.wizardform." + choice_options[index] + ".checked = true;");
//alert("true");
}
else {
document.wizardform.vl.checked = false;
}
}
return true;
}