Do not allow special characters jQuery - javascript

Have some error in this, can you guys please tell me what i am doing wrong
function verifyGroup(groupVal, errorid) {
groupVal = $.trim(groupVal);
if (groupVal != '') {
var splChars = "*|,\":<>[]{}`\';()#&$#%!+-";
for (var i = 0; i < groupVal.length; i++) {
console.log(groupVal.charAt(i)+' == '+splChars.indexOf(groupVal.charAt(i)));
if (splChars.indexOf(groupVal.charAt(i)) != -1) {
$("#" + errorid).addClass("form-error").html("Illegal characters detected!");
return false;
} else {
$("#" + errorid).removeClass("form-error").html("");
return true;
}
}
} else {
$("#" + errorid).addClass("form-error").html("Group name should not be empty");
return false;
}
}
DEMO

Use a regex
function verifyGroup(groupVal, errorid) {
groupVal = $.trim(groupVal);
console.log(groupVal);
console.log(errorid);
if (groupVal != '') {
var regex = /[*|,\\":<>\[\]{}`';()#&$#%!+-]/;
if(regex.test(groupVal)){
$("#" + errorid).addClass("form-error").html("Illegal characters detected!");
return false;
} else {
$("#" + errorid).removeClass("form-error").html("valid");
return true;
}
} else {
$("#" + errorid).addClass("form-error").html("Group name should not be empty");
return false;
}
}
$(function() {
// Handler for .ready() called.
$('#submit').click(function(){
verifyGroup($('#ipId_create').val(), 'error_id');
});
});
Demo: Fiddle

The comparison to -1 should be == not !=.

Related

jQuery detecting changes on two elements using keyup()

HTML:
<form>
<input type="text" id="target" placeholder="example.com">
<input type="checkbox" name="http" id="http" value="http"> http://
</form>
<div id="possible-targets">
<h4>Possible matches: </h4>
</div>
JS:
var target_value;
$(window).load(function () {
$('#target').keyup(function () {
target_value = $('#target').val();
if (target_value == '') {
$('#target-match').remove();
} else if ($('#target-match').length == 0) {
$('#possible-targets').append('<h4><span id="target-match">' + target_value + '</span></h4>');
} else if ($('#target-match').length != 0) {
$('#target-match').html(target_value);
}
if ($('#http').prop('checked')) {
if ($('#target-match-h').length == 0) {
$('#possible-targets').append('<h4><span id="target-match-h">http://' + target_value + '</span></h4>');
} else {
$('#target-match-h').html('http://' + target_value);
}
} else {
$('#target-match-h').remove();
}
});
});
Here is a JSFiddle: http://jsfiddle.net/h2Uw4/
Now when I start typing in the text input field I can see a live change in the possible-targets div, but when I click on the http:// checkbox it still needs to type at least one more character in the text input field to make a live change and add another possible target.
I tried to use keyup() on both #target (the text input) and #http (the checkbox) but it didn't work:
$('#target, #http').keyup()
Create a function and pass it to event handlers.
Example Code
var yourFunc = function () {
//Your code
};
$('#target').keyup(yourFunc);
$('#http').change(yourFunc);
DEMO
As per #DavidThomas comments you can also use
$('#target, #http').on('change keyup', yourFunc)
DEMO 2
Try this
var target_value;
$(window).load( function() {
$('#target').keyup(function() {
target_value = $('#target').val();
if(target_value == '') {
$('#target-match').remove();
} else if($('#target-match').length == 0) {
$('#possible-targets').append('<h4><span id="target-match">' + target_value + '</span></h4>');
} else if($('#target-match').length != 0) {
$('#target-match').html(target_value);
}
if($('#http').prop('checked')) {
if($('#target-match-h').length == 0) {
$('#possible-targets').append('<h4><span id="target-match-h">http://' + target_value + '</span></h4>');
} else {
$('#target-match-h').html('http://' + target_value);
}
} else {
$('#target-match-h').remove();
}
});
$('#http').click(function(){
if ($('#target').val() !== "")
if (this.checked === true) {
$('#possible-targets').html('<h4>Possible matches: </h4><h4><span id="target-match-h">http://' + target_value + '</span></h4>');
} else {
$('#possible-targets').html('<h4>Possible matches: </h4><h4><span id="target-match-h">' + target_value + '</span></h4>');
}
});
});
You will have to execute the callback functionality when the checkbox's value is changed.
please update the js as :
var target_value;
$(window).load( function() {
$('#target').keyup(displayMatches);
$('#http').change(displayMatches);
});
function displayMatches() {
target_value = $('#target').val();
if(target_value == '') {
$('#target-match').remove();
} else if($('#target-match').length == 0) {
$('#possible-targets').append('<h4><span id="target-match">' + target_value + '</span></h4>');
} else if($('#target-match').length != 0) {
$('#target-match').html(target_value);
}
if($('#http').prop('checked')) {
if($('#target-match-h').length == 0) {
$('#possible-targets').append('<h4><span id="target-match-h">http://' + target_value + '</span></h4>');
} else {
$('#target-match-h').html('http://' + target_value);
}
} else {
$('#target-match-h').remove();
}
}
updated fiddle

custom JS file prevents jquery from running

I have been working to get the jQuery UI Tabs to work with a site I'm working on. I was able to get it to work after commenting out a custom made javascript file that stops jQuery from running. I need to use this file but I am not sure what is wrong with the code that would keep jQuery from running. I would be grateful for any help. Thanks.
$(document).ready(function(){
initLimitedTextarea();
initPointsControls();
});
function initForms( id ){
$(id).bind('submit', function() {
if(id.toString().toLowerCase() == '#fm-registration'){
$(this).ajaxSubmit({ success: FinishRegistration });
} else if(id.toString().toLowerCase() == '#fm-join') {
$(this).ajaxSubmit({ success: FinishJoin });
} else {
console.log('Initializing...');
$(this).ajaxSubmit({ success: showResponse });
}
return false;
});
}
function FinishRegistration(responseText, statusText){
if(responseText.search(/NewNotify/) != -1 ){
$('#fm-registration').hide('slow').EffectChain({onComplete:function(){
$('#fm-registration').html(responseText);
$('#fm-registration').show('slow');
}});
} else {
showResponse(responseText, statusText);
}
}
function showResponse(responseText, statusText) {
if(responseText != '') {
$('#error-msg').html(responseText);
} else {
tb_remove();
}
}
function FinishJoin(responseText, statusText) {
//console.log(responseText);
if(responseText != '' && responseText.toLowerCase().search('viewtribe.php') == -1) {
$('#error-msg').html(responseText);
} else {
tb_remove();
window.location.href = responseText;
}
}
function hidePopup(){
$('#fade-area').animate({opacity:0}, 'fast').hide();
$('#container').html(' ');
//$('#container').fadeOut();
}
var specialKeys = [8,46,37,39,38,40,27,9,16,17,18,20,144];
function isSpecialKey(code){
for(i = 0; i < specialKeys.length; i++){
if(code == specialKeys[i]){ return true; }
}
return false;
}
function initLimitedTextarea(){
$('textarea.limited-size, input.limited-size').each(function(){
if ($(this).hasClass('edit')){
$('#' + $(this).attr('id') + '-monitor').html($(this).attr('size'));
$(this).keypress(function(e){
if(((parseInt($(this).attr('size')) - ($(this).val()).length)) <= 0 && !(specialKey = isSpecialKey(e.keyCode))){
return false;
}
});
$(this).keyup(function(e){
$('#' + $(this).attr('id') + '-monitor').html((parseInt($(this).attr('size')) - ($(this).val()).length));
});
}else{
$('#' + $(this).attr('id') + '-monitor').html($(this).attr('cols'));
$(this).keypress(function(e){
if(((parseInt($(this).attr('cols')) - ($(this).val()).length)) <= 0 && !(specialKey = isSpecialKey(e.keyCode))){
return false;
}
});
$(this).keyup(function(e){
$('#' + $(this).attr('id') + '-monitor').html((parseInt($(this).attr('cols')) - ($(this).val()).length));
});
}
});
}
function initPointsControls(){
$("input[name=completed[]], input[name=targeted[]]").each(function (i, el) {
$(el).bind('click', function(){
name = ($(this).attr('name').toLowerCase() == 'completed[]') ? 'targeted[]' : 'completed[]' ;
if($(this).attr('checked') == true && $("input[name=" + name + "][value=" + $(this).attr('value') + "]").attr('checked') == true){
$("input[name=" + name + "][value=" + $(this).attr('value') + "]").attr('checked', false);
}
});
});
}
function Activate( obj ){
$("#activation-done").load($(obj).attr('href'));
return false;
}
function delayer(){
window.location = 'GetRewards.php';
}
function confirmation() {
var answer = confirm('Are you sure you want to use reward points for this reward?');
if (answer){
setTimeout('delayer()', 1000);
return true;
}
else{
return false;
}
}
function SetData( value ){ $("input[name='profileimage']").val(value); }
function enableSubmit() { $('input[name="submitnew"]').attr('disabled', !$('#agree').attr('checked')); }

Select text contents of multiple elements by class

I want to make a search demo. My problem is that I have one parent div in which I have two child divs. Both child divs have same class (RLTRightDiv). I want to search on all content. Can you please tell me how I can achieve that. It is currently only searching the first child of the parent div.
example "leave" is present in both div.
http://jsfiddle.net/3MVNj/5/
var searchIndex = -1;
var searchTermOld = '';
$(document).ready(function () {
/*
Search Functionality method.
*/
$('.searchbox').on('change', function () {
if ($(this).val() === '') {
var selector = "#fullContainer .RLTRightDiv";
$(selector + ' span.match').each(function () {
$(this).replaceWith($(this).html());
});
}
searchIndex = -1;
$('.searchNext').attr("disabled", "disabled");
$('.searchPrev').attr("disabled", "disabled");
searchTermOld = $(this).val();
});
$('.searchbox').on('keyup', function () {
var selector = "#fullContainer .RLTRightDiv";
if ($(this).val() === '') {
$(selector + ' span.match').each(function () {
$(this).replaceWith($(this).html());
});
}
if ($(this).val() !== searchTermOld) {
$(selector + ' span.match').each(function () {
$(this).replaceWith($(this).html());
});
searchIndex = -1;
$('.searchNext').attr("disabled", "disabled");
$('.searchPrev').attr("disabled", "disabled");
}
});
//Search Click method
$('.search').on('click', function () {
if (searchIndex == -1) {
var searchTerm = $('.searchbox').val();
if (searchTerm == '') {
PG_alert("Please Insert Text.")
return;
}
if (searchTerm == 'b'||searchTerm == 'br'||searchTerm == 'r') {
return;
}
setTimeout(function(){
searchAndHighlight(searchTerm);
},300);
} else
{
//naveen
setTimeout(function(){
searchNext();
},300);
}
if ($('.match').length > 1) {
$('.searchNext').removeAttr("disabled");
$('.searchPrev').removeAttr("disabled");
}
});
$('.searchNext').on('click', searchNext);
});
/*
Seacrh and highlight text method.
*/
function searchAndHighlight(searchTerm) {
if (searchTerm) {
var searchTermRegEx, matches;
var selector = "#fullContainer .RLTRightDiv";
$(selector + ' span.match').each(function () {
$(this).replaceWith($(this).html());
});
try {
searchTermRegEx = new RegExp('(' + searchTerm + ')', "ig");
} catch (e) {
return false;
}
$('.highlighted').removeClass('highlighted');
matches = $(selector).text().match(searchTermRegEx);
if (matches !== null && matches.length > 0) {
var txt = $(selector).html().replace(searchTermRegEx, '<span class="match">$1</span>');
$(selector).html(txt);
searchIndex++;
$('.match:first').addClass('highlighted');
$('#realTimeContents').animate({
scrollTop: $('.match').eq(searchIndex).get(0).offsetTop
});
return true;
} else {
console.log("yes===========")
searchIndex = -1;
}
return false;
}
return false;
}
function searchNext() {
var searchTerm = $('.searchbox').val();
if (searchTerm == '') {
PG_alert("Please Insert Text.")
return;
}
if (searchTerm == 'b'||searchTerm == 'r'||searchTerm == 'br') {
// PG_alert("Please .")
return;
}
if(searchIndex!=-1){
searchIndex++;
if (searchIndex >= $('.match').length) {
//naveen end
searchIndex = -1;
}
$('.highlighted').removeClass('highlighted');
$('.match').eq(searchIndex).addClass('highlighted');
$('#realTimeContents').animate({
scrollTop: $('.match').eq(searchIndex).get(0).offsetTop
});
}
}

Javascript showing alert without refreshing the page

when I click submit button it shows the validation right but after that alert message the page is being refreshed and i loos all other datas from the fields :S, how can i make it to still remain the others field filled.
I tried to remove the window.location.reload() after submit event is called but still not working :S. ANYONE any suggestion?
this is the code:
function formValidation() {
var uid = document.registration.userid;
var passid = document.registration.passid;
var uname = document.registration.username;
var uadd = document.registration.address;
var ucountry = document.registration.country;
var uzip = document.registration.zip;
var uemail = document.registration.email;
var umsex = document.registration.msex;
var ufsex = document.registration.fsex;
if (userid_validation(uid, 5, 12)) {
if (passid_validation(passid, 7, 12)) {
if (allLetter(uname)) {
if (alphanumeric(uadd)) {
if (countryselect(ucountry)) {
if (allnumeric(uzip)) {
if (ValidateEmail(uemail)) {
if (validsex(umsex, ufsex)) {}
}
}
}
}
}
}
}
return false;
}
function userid_validation(uid, mx, my) {
var uid_len = uid.value.length;
if (uid_len == 0 || uid_len >= my || uid_len < mx) {
alert("User Id should not be empty / length be between " + mx + " to " + my);
uid.focus();
return false;
}
return true;
}
function passid_validation(passid, mx, my) {
var passid_len = passid.value.length;
if (passid_len == 0 || passid_len >= my || passid_len < mx) {
alert("Password should not be empty / length be between " + mx + " to " + my);
passid.focus();
return false;
}
return true;
}
function allLetter(uname) {
var letters = /^[A-Za-z]+$/;
if (uname.value.match(letters)) {
return true;
} else {
alert('Username must have alphabet characters only');
uname.focus();
return false;
}
}
function alphanumeric(uadd) {
var letters = /^[0-9a-zA-Z]+$/;
if (uadd.value.match(letters)) {
return true;
} else {
alert('User address must have alphanumeric characters only');
uadd.focus();
return false;
}
}
function countryselect(ucountry) {
if (ucountry.value == "Default") {
alert('Select your country from the list');
ucountry.focus();
return false;
} else {
return true;
}
}
function allnumeric(uzip) {
var numbers = /^[0-9]+$/;
if (uzip.value.match(numbers)) {
return true;
} else {
alert('ZIP code must have numeric characters only');
uzip.focus();
return false;
}
}
function ValidateEmail(uemail) {
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (uemail.value.match(mailformat)) {
return true;
} else {
alert("You have entered an invalid email address!");
uemail.focus();
return false;
}
}
function validsex(umsex, ufsex) {
x = 0;
if (umsex.checked) {
x++;
}
if (ufsex.checked) {
x++;
}
if (x == 0) {
alert('Select Male/Female');
umsex.focus();
return false;
} else {
alert('Form Succesfully Submitted');
window.location.reload()
return true;
}
}
Two problems...
Missing return
onSubmit="return formValidation();"
Missing return true;
if (validsex(umsex, ufsex)) { return true; }

AutoComplete (AutoFilter?), using jQuery delegate

$('#container form').delegate('#addSearch', 'keyup', function(e) {
var tmpVAL = $('#addSearch').val();
$('.w').each(function() {
var tmpHTML = $(this).html();
if (tmpHTML == tmpVAL) {
$(this).fadeIn(250);
} else if (tmpVAL.length < 1) {
$(this).fadeIn(250);
} else {
$(this).fadeOut(250);
}
});
});
and #addSearch is an <input type="text">.
So, my problem is that; this obviously will only return the results that are an exact match to the tmpVAL - How would I allow it so every letter will change the search result.
e.g.
I type N
it comes up with No, Not, Nothing, Nothingness
I type NOT
it comes up with Not, Nothing, Nothingness
Any help would be appreciated, I would imagine that it would be RegEx?
DEMO https://so.lucafilosofi.com/autocomplete-autofilter-using-jquery-delegate
$(function() {
$('#container form').delegate('#addSearch', 'keyup', function(e) {
var tmpVAL = $('#addSearch').val();
$('.w').each(function() {
var tmpHTML = $(this).text();
var subSection = tmpHTML.substring(tmpVAL.length, 0);
if (subSection == tmpVAL && tmpVAL != '' ) {
$(this).show();
} else {
$(this).hide();
}
});
});
});
You could use a regular expression, but I think that might be overkill. You could just use indexOf:
$('#container form').delegate('#addSearch', 'keyup', function(e) {
var tmpVAL = $('#addSearch').val().toLowerCase();
$('.w').each(function() {
var tmpHTML = $(this).html().toLowerCase();
if (tmpHTML.indexOf(tmpVAL) >= 0) {
$(this).fadeIn(250);
} else if (tmpVAL.length < 1) {
$(this).fadeIn(250);
} else {
$(this).fadeOut(250);
}
});
});
Working example: http://jsfiddle.net/andrewwhitaker/PRyvU/
Here's an alternative solution that doesn't use an .each():
$('#container form').delegate('#addSearch', 'keyup', function(e) {
var tmpVAL = $('#addSearch').val().toLowerCase();
var $words = $(".w");
var contains = function(haystack, needle) {
return haystack.indexOf(needle) >= 0;
};
if (tmpVAL.length < 1) {
$words.fadeIn(250);
}
else {
$words.filter(function() {
return !contains($(this).html().toLowerCase(), tmpVAL);
}).fadeOut(250);
$words.filter(function() {
return contains($(this).html().toLowerCase(), tmpVAL);
}).fadeIn(250);
}
});
http://jsfiddle.net/andrewwhitaker/EyJ6b/

Categories

Resources