Javascript - Disable spaces on all pages except 2 - javascript

I'm trying to prevent the space button from being pressed on all of my pages except 2 where I have textareas. I need spaces on these textarea pages so the user can enter in their support ticket message. I have tried many different ways of doing this and cannot find a working way. I've spent about 1 whole week just trying this small error. I thought it was time to get some help.
The error is that when I use the code below, it tells me that I cannot use spaces (and prevents spaces) eventhough I am on one of the pages I said not to run the script on.
My current code is :
$(document).keydown(function(event) {
var myUrl_one = '/panel/staff?page=tickets';
var myUrl_two = '/panel/support';
var currentUrl = window.location.pathname;
if(currentUrl != myUrl_one || currentUrl != myUrl_two) {
if (event.which == 32) {
event.preventDefault();
$.Notification.autoHideNotify('error', 'top right', 'Keyboard Error!', 'No spaces are allowed here!');
}
}
});

Thanks to #RogerCageot and #Airwavezx, I have found the issue.
Firstly, I needed to change my || operator to && in my if statement like so :
if(currentUrl != myUrl_one && currentUrl != myUrl_two) {
Secondly, the javascript function window.location.pathname only gets the raw path location, not GET parameters. Because I was trying to get /panel/staff?page=tickets, it wasn't reading the ?page=tickets. It was only reading the /panel/staff.
My fully working code is below :
$(document).keydown(function(event) {
var myUrl_one = '/panel/staff';
var myUrl_two = '/panel/support';
var currentUrl = window.location.pathname;
if(currentUrl != myUrl_one && currentUrl != myUrl_two) {
if (event.which == 32) {
event.preventDefault();
$.Notification.autoHideNotify('error', 'top right', 'Keyboard Error!', 'No spaces are allowed here!');
console.log(currentUrl, myUrl_one);
}
}
});

Related

Recommended way to unittest javascript in Laravel 5

Is there a recommended way to unittest javascript in Laravel 5? I'm using the jQuery framework to do the search autocomplete task (code below). There's a lot of if blocks that I want to test but I'm not sure how to best test everything in Laravel 5. Any help is appreciated.
<script type="text/javascript">
(function($) {
var autocomplete_timer;
var ajax_request;
var autocomplete_delay = 50;
var search_keyword = "";
var max_result_count = 5;
var autocomplete_results = $('#autocomplete-results');
var autocomplete_results_list;
var default_report_url = '{{ route('report_summary_date_range_filter') }}';
var selected_autocomplete_item_index = 0;
var active_li = false;
var autocomplete_error = $('#autocomplete-error');
var redirect_state = false; //
$(document).ready(function () {
autocomplete_results_list = autocomplete_results.children('ul');
// Search Autocomplete
$("#search").keyup(function (e) {
search_keyword = $(this).val();
// If there is an existing XHR, abort it.
if (ajax_request) {
ajax_request.abort()
}
// Enable list iteration via keyboard
if (e.keyCode == 40 || e.keyCode == 38) {
ajax_request.abort();
var results_count = autocomplete_results_list.children('li').length;
if (e.keyCode == 40 && selected_autocomplete_item_index < results_count && active_li != false) {
selected_autocomplete_item_index++;
} else if (e.keyCode == 38 && selected_autocomplete_item_index > 0 && active_li != false) {
selected_autocomplete_item_index--;
}
active_li = autocomplete_results_list.children('li:eq(' + selected_autocomplete_item_index + ')');
if (active_li.length > 0) {
active_li.addClass('active');
autocomplete_results_list.children('li').not(active_li).removeClass('active');
$('#search').val(active_li.children('.autocomplete-ticker').text());
}
e.preventDefault();
return false;
}
// Clear the timer so we don't end up with dupes.
clearTimeout(autocomplete_timer);
// don't trigger ajax if user pressed enter/return key
// while a redirect is triggered
if (e.keyCode == 13 && redirect_state == true) {
return false;
}
if (search_keyword != '') {
// reset the index
selected_autocomplete_item_index = 0;
active_li = false;
// assign timer a new timeout
autocomplete_timer = setTimeout(function() {
ajax_request = $.ajax({
type: 'POST',
url: '/ajax/company/search/' + search_keyword,
data: {'_token': '{{ csrf_token() }}'},
success: function(response) {
if (response.count != 0) {
autocomplete_results.show();
autocomplete_results_list.empty();
autocomplete_error.hide();
var current_results = ((response.count > max_result_count) ? max_result_count : response.count);
for (var index = 0; index < current_results; index++) {
autocomplete_results_list.append(
'<li>' +
'<span class="autocomplete-ticker">' + response.results[index].ticker + '</span>' +
'<span class="autocomplete-company">' + response.results[index].name + '</span>' +
'</li>'
);
}
} else {
autocomplete_results_list.empty();
autocomplete_results.show();
autocomplete_error.show();
}
}
});
}, autocomplete_delay);
} else {
autocomplete_results.hide();
autocomplete_results_list.empty();
}
}).keydown(function (e) {
// prevent moving cursor to start of input field
// if the user presses the up arrow key
if (e.keyCode == 38) {
e.preventDefault();
}
});
// handle user clicking of an autocomplete item
autocomplete_results_list.on('click', 'li', function () {
var ticker = $(this).children('.autocomplete-ticker').text();
$('#search').val(ticker);
default_report_url = default_report_url.replace('%7Bticker%7D', ticker);
// redirect
$(location).attr('href', default_report_url);
redirect_state = true;
});
// if the user presses the return key while an autocomplete list
// is present, select the first item on the list and trigger a redirect
$('#searchbar form').submit(function (e) {
if ($('#search').val() != '') {
if (autocomplete_results_list.has('li').length > 0) {
autocomplete_results_list.children('li').first().addClass('active');
var ticker = autocomplete_results_list.children('li').first()
.children('.autocomplete-ticker').text().toUpperCase();
if (ticker != '') {
default_report_url = default_report_url.replace('%7Bticker%7D', ticker);
// redirect
$(location).attr('href', default_report_url);
redirect_state = true;
}
}
}
e.preventDefault();
});
});
$(document).click(function (e) {
// Hide autocomplete results if user clicked outside the search input field
// or the autocomplete listing
var container = $('#searchbar');
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
$('#autocomplete-results').hide();
$('#autocomplete-results ul').empty();
}
});
})(jQuery);
</script>
The choice of Laravel (or any other back-end framework/language/platform) is entirely irrelevant. This is purely front-end code. As such, you need to be using front-end testing tools for it.
However, even before you start thinking about unit testing this code, you need to do some re-coding so that it is actually testable in units. As things stand, you have a large monolithic blob of code there which cannot really be unit tested at all. You need to extract the functionality into discrete functions; the shorter the better.
Once you've done that, I'd suggest that the best starting point for your testing would be QUnit. This is a unit test framework developed by the jQuery foundation, and used for testing jQuery itself. Since your code has jQuery as a dependency, I'd suggest that this would probably be the best place to start. However there are numerous other testing frameworks for JavaScript, and you may want to investigate some of those as well.
Bear in mind that UI code (which most front-end JavaScript is) is notoriously difficult to write good quality unit tests for. You may find that functional testing -- ie automated end-user testing via a browser -- will serve you better. (indeed, you should be considering doing this kind of testing, even if you do also write unit tests for the JS code). For this, you will need an automation tool for the browser. The most well known one is Selenium, but you may also want to look into Sahi and also PhantomJS.

Rewrite URL on location change

I'm looking for a way to rewrite URL of the location when the user want's to change page. So, let's say you have something like this:
<body>
<a href="http://example.com" />
</body>
Is there a way I can catch URL changing moment, and actually modify that URL before location is changed, for example I would like to change href into relative link like \http://example.com and redirect page actually there.
If you just want to trap the link and then modify it then yes, that's quite simple...
$("a").on("click", function(e) {
e.preventDefault(); // stops the link doing its default thing
window.location.href = "something/" + $(this).attr("href");
});
You obviously need to modify the line that changes the location, so that it modifies the href value however you need. I'd also recommend giving the links a class and selecting them with that, as the above code will affect every link on the page.
Finally, this will need to run after the DOM is loaded, so either wrap it in a document.ready handler of your choice, or put it in a script at the bottom of the body.
Demo
You can work from here. Also you will need urlrewrite in htaccess for this to work properly.
$(function () {
$('.buttonn').on('click', function (e) {
var seperator = (window.location.href.indexOf("?") === -1) ? "?" : "&";
if (window.location.href.indexOf("s1") === -1 && window.location.href.indexOf("s2") != -1) {
window.location.href = window.location.href.replace(/&?s2=([^&]$|[^&]*)/i, "&s1=s1");
} else if (window.location.href.indexOf("s1") != -1) {
window.location.href = window.location.href.replace(/&?s1=([^&]$|[^&]*)/i, "&s1=s1");
} else {
window.location.href = window.location.href + seperator + "s1=s1";
}
});
});
$(function () {
$('.buttono').on('click', function (e) {
var seperator = (window.location.href.indexOf("?") === -1) ? "?" : "&";
if (window.location.href.indexOf("s2") === -1 && window.location.href.indexOf("s1") != -1) {
window.location.href = window.location.href.replace(/&?s1=([^&]$|[^&]*)/i, "&s2=s2");
} else if (window.location.href.indexOf("s2") != -1) {
window.location.href = window.location.href.replace(/&?s2=([^&]$|[^&]*)/i, "&s2=s2");
} else {
window.location.href = window.location.href + seperator + "s2=s2";
}
});
});

Mirroring input content with non-printable chars like CTRL, ALT or shift key

When non-printable char is pressed, it's replaced with let's say for CTRL=17 with "[CTRL]".
Here is code an example
$('#textbox1').keyup(function (event) {
if (8 != event.keyCode) {
if(17==event.keyCode){
$('#textbox1').val($('#textbox1').val()+"[CTRL]")
$('#textbox2').val($('#textbox1').val());
}else{
$('#textbox2').val($('#textbox1').val());
}
} else {
$('#textbox2').val($('#textbox1').val());
}
});
the problem is when user presses backspace the second input must reflect the content of the first one, so "[CTRL]" must be deleted at once like any other chars.
You could make use of the keyCode and/or in combination with charCode (if required). Basic idea would be:
Create a map of all required key codes in an array/object
Handle event for say keydown and listen for keycode
Look for the keycode in your map and if found show it
prevent the default (to prevent e.g. say backspace browsing back)
If not found in map, let the character go thru as usual.
A very basic example:
Demo: http://jsfiddle.net/abhitalks/L7nhZ/
Relevant js:
keyMap = {8:"[Backspace]",9:"[Tab]",13:"[Enter]",16:"[Shift]",17:"[Ctrl]",18:"[Alt]",19:"[Break]",20:"[Caps Lock]",27:"[Esc]",32:"[Space]",33:"[Page Up]",34:"[Page Down]",35:"[End]",36:"[Home]",37:"[Left]",38:"[Up]",39:"[Right]",40:"[Down]",45:"[Insert]",46:"[Delete]"};
$("#txt").on("keydown", function(e) {
// check if the keycode is in the map that what you want
if (typeof(keyMap[e.keyCode]) !== 'undefined') {
// if found add the corresponding description to the existing text
this.value += keyMap[e.keyCode];
// prevent the default behavior
e.preventDefault();
}
// if not found, let the entered character go thru as is
});
Edit: (as per the comments)
The concept remains the same, just copying the value to the second input:
Demo 2: http://jsfiddle.net/abhitalks/L7nhZ/3/
$("#txt1").on("keyup", function(e) {
if (typeof(keyMap[e.keyCode]) !== 'undefined') {
this.value += keyMap[e.keyCode];
e.preventDefault();
}
$("#txt2").val(this.value); // copy the value to the second input
});
Regarding deletion of the description, I could not get it done by caching the last inserted descrition from the map. Somehow, I kept struggling with the regex with a variable. Anyway, a simpler solution is to just add another event handler for keyup with hard-coded map.
Thanks to #serakfalcon for (that simple solution), which we are using here:
$('#txt1').keydown(function(event) {
if(8 == event.keyCode) {
var el = $(this);
el.val(el.val().replace(/\[(Tab|Enter|Shift|Ctrl|Alt|Break|Caps Lock|Esc|Space|Page (Up|Down)|End|Home|Left|Up|Right|Down|Insert|Delete)\]$/,' '));
$("#txt2").val(el.val());
}
});
You can check in the keydown for the last character in the input field. If it's a ] you can remove everything from the right to the last found opening bracket [. Unfortunatly this does not work if you're cursor is inside '[ ]'.
$('#textbox1').keydown(function(event) {
if(8 == event.keyCode) {
var element = $(this),
value = element.val(),
lastChar = value.slice(-1);
if(lastChar == ']') {
var lastIndex = value.lastIndexOf('['),
index = value.length - lastIndex;
element.val(value.slice(0, -index) + "]");
}
}
});
Fiddle
you can always use a regex.
$('#textbox1').keydown(function(event) {
if(8 == event.keyCode) {
var el = $(this);
el.val(el.val().replace(/\[(CTRL|ALT|SHIFT)\]$/,' '));
}
});
fiddle
Edit: combined with abhitalks code

jQuery - validation result is different from JS Fiddle demo

I am having a very weird issue where the code of my working files doesn't work when the same code on my JS Fiddle works fine.
All I am doing is checking whether either username or password field is submitted blank.
For some reason, my working platform code doesn't pick up any input value.
I've gone through number of times, making sure that I am on same code environment
but everything is identical. I don't know where to take it from here.
(function($){
$('#signIn_1').click(function () {
var username = $('#username_1').val();
var password = $('#password_1').val();
if ( username === '' || password === '' ) {
$('.fa-user').removeClass('success').addClass('fail');
} else {
$('.fa-user').removeClass('fail').addClass('success');
}
});
})(jQuery);
Is my if statement violating any rules that might result in inconsistency?
JS Fiddle
The problem is that your <form> element is submitting, thus reloading the page. I recommend modifying the form's submit event rather than giving the button a click event, as forms are usually but not necessarily triggered by clicking the button. Also, return false is not a good way of disabling behaviour.
Example:
(function($){
$('#form_1').submit(function (event) {
var username = $('#username_1').val();
var password = $('#password_1').val();
if ( username === '' || password === '' ) {
event.preventDefault();
$('.fa-user').removeClass('success').addClass('fail');
}
else {
$('.fa-user').removeClass('fail').addClass('success');
}
});
})(jQuery);
Here's the fiddle: http://jsfiddle.net/RyanJW/VqwNw/1/
check this
use return false to stop execution
(function($){
$('#signIn_1').click(function () {
var username = $('#username_1').val();
var password = $('#password_1').val();
if ( $.trim(username) === '' || $.trim(password) === '' ) {
$('.fa-user').removeClass('success').addClass('fail');
return false;
} else {
$('.fa-user').removeClass('fail').addClass('success');
}
});
})(jQuery);
Fiddle

If statement with url plus universal variable

I'm trying to transform a blog on blogger into a website. In order to have a static home page I am using the Javascript code below to see if the user is on the home page if they are then it will hide the post section and display a home page "gadget". Is anything supposed to match anything?
document.onload = hidepage();
function hidepage () {
if (window.location == "http://website.blogspot.com/" || window.location == "http://website.blogspot.com/?zx=" + ANYTHING) {
//Checks to see if user is on the home page
$(".hentry").hide(); //Hide posts
$(".hfeed").hide(); //Hide posts
}
else {
$("#HTML2").hide(); //hide gadget
}
$(".post-title").hide(); //Hide post titles
}
Based on what you're saying I think you want to change the if condition to:
if (window.location.href === "http://website.blogspot.com/" ||
window.location.href.indexOf("http://website.blogspot.com/?zx=") > -1)
You could also shorten this to:
if (window.location.href === "http://website.blogspot.com/" ||
window.location.href.indexOf("/?zx=") > -1)
Note that I've changed your == to === as the latter is a literal comparison.
Just use String.indexOf in the second half of the if expression.
var url = window.location.href;
if (url === "http://website.blogspot.com/" || url.indexOf("http://website.blogspot.com/?zx=") === 0) {
// do stuff
}

Categories