Question:
I am running a function where you press the keys C or M using the keypress() function and every time I press one of those keys, the letter is marked automatically in Firefox. Is there a way to disable this using JavaScript or is this something Firefox does by default?
I have tried to look for an answer using Google but it seems no one has had this issue before using the keypress() function in JS.
Code:
<script type="text/javascript">
$(document).ready(function()
{
var once = false;
$(window).keypress(function(e)
{
if(!once)
{
if (e.which == 99)
{
once = true;
$("input#left").val( 1 );
$("form").submit();
}
else if (e.which == 109)
{
once = true;
$("input#right").val( 1 );
$("form").submit();
}
}
});
});
</script>
Thanks in advance for any tips!
Just call preventDefault():
$(window).keypress(function(e)
{
e.preventDefault()
// other code
}
There are a few ways of handling this. If you call e.preventDefault() you should be covered, however that's not your only option.
HTML5 introduced many new tags and attributes into markup, one of them being an autocomplete attribute for text fields. If you add this to your HTML (<input type='text' id='myInput' autocomplete='off'>) you should be covered as well. You can't always rely on your user having support for HTML5, but this is still an easy solution to your problem.
It can't hurt you to implement both of these small changes in your code.
Related
I have an problem with my site when I want to change the css style from the JavaScript it works but only for few seconds.
function validateForm() {
var fname = document.getElementById('<%=UserFnameTextBox.ClientID%>');
if (fname.value == "") {
document.getElementById("WarnUserFnameTextBox").style.opacity = 1;
document.getElementById('<%=UserFnameTextBox.ClientID%>').style.borderColor = "red";
getElementById('<%=UserFnameTextBox.ClientID%>').focus;
}
}
I'm using also Asp.net, that's why I wrote the ID like this
I want that the JS will save the style for as long that the user enter the textbox.
Multiple things here: I suggest that your validateForm() function triggers in an onClick on your submit-button, right? Does your button look somewhat like this?
<input type="submit" value="submit" onClick="validateForm()">
If this is the case, the reason why your styles work only for few seconds is simply that the website reloads. The styles are in effect, but the form is also triggering and send to the site, which you added in your <form action>. After reloading, the website will fall back to its default style, as if the errors never occured... which is correct on that instance of the site.
If you want to have it permanent, you have to disable the submit-button as long as there are invalid fields. You can make use of the required attribute for form elements as well, since the form won't submit as long as there are invalid fields. These can be styled as well.
Have a look at these CSS rules for that:
/* style all elements with a required attribute */
:required {
background: red;
}
You can make use of jQuery as well and disable the form-submit with preventDefault. You can take care of every style and adjust accordingly, as long as there empty / non-valid characters in your input-fields. I suggest combining this with the onKeyUp-function. This way you check everytime the users releases a key and can react as soon as your input is valid.
As an example with jQuery:
var $fname = $('#<%=UserFnameTextBox.ClientID%>');
var $textBox = $('#WarnUserFnameTextBox');
$fname.on("input", function() {
var $this = $(this);
if($this.val() == "") {
$textBox.show();
$this.focus().css("border", "1px solid red");
}
});
(thanks for pointing out my errors and optimizing the code, #mplungjan!).
To "disable" the actual form-submission, refer to this answer:
https://stackoverflow.com/a/6462306/3372043
$("#yourFormID").submit(function(e){
return false;
});
This is untested, feel free to point out my mistake, since I can't check it right now. You can play around on how you want to approach your "errorhandling", maybe switch to onKeyDown() or change(), that kind of depends on your needs / usecase.
Since your question isn't tagged with jQuery, have a look at this answer given by mplungjan as well, since it uses native JS without any framework.
https://stackoverflow.com/a/53777747/3372043
This is likely what you want. It will stop the form from being submitted and is reusing the field and resetting if no error
It assumes <form id="myForm"
window.addEventListener("load", function() {
document.getElementById("myForm").addEventListener("submit", function(e) {
var field = document.getElementById('<%=UserFnameTextBox.ClientID%>');
var error = field.value.trim() === "";
document.getElementById("WarnUserFnameTextBox").style.opacity = error ? "1" : "0"; // or style.display=error?"block":"none";
field.style.borderColor = error ? "red" : "black"; // reset if no error
if (error) {
field.focus();
e.preventDefault();
}
});
});
I have a checkbox on my website which is currently enabled and it can be disabled by users. What I want to do is to keep it locked in that way so it cannot be disabled.
I think this can be achieved using jquery or javascript but I'm not quite sure how.
<input type="checkbox" value="check" id="moove_gdpr_strict_cookies">
And please note it's a wordpress website. So I can't edit HTML.
you can simple prevent click.
$(document).ready(function() {
$('#moove_gdpr_strict_cookies').click(function(e) {
e.preventDefault();
});
});
Simply you can return false onclick event
$('#moove_gdpr_strict_cookies').on('click',function(){
return false;
});
Would suggest to do something like this:
var form = document.getElementById('yourform');
form.onSubmit = function () {
var formElems = document.getElementsByTagName('INPUT');
for (var i = 0; i , formElems.length; i++){
if (formElems[i].type == 'checkbox'){
formElems[i].disabled = true;
}
}
}
I would not recommend doing this. As suggested by the id of checkbox this checkbox has to do with GDPR. A user on your sight MUST have the right to decline cookies for tracking purposes (which this seems to be). Please be careful, as fines can be very high.
Technically most answers seem viable.
I know that it's impossible to thwart the world's most advanced minds, but I'd like to put the slightest of barriers on my website to keep my students from copying text from it and posting that text as their answer. (If they hand type it, that's ok).
I'm just so afraid of JavaScript because of cross browser inconsistencies.
Given that I have jQuery loaded and prefer to use jQuery whenever possible, how do I:
Disable Ctrl + c
Disable Menu Edit Copy.
Its some how daunting to create a function that would do that, what you should target is, clearing the clipboard so even if, the user press Ctrl + C, nothing is copied into the clipboard, a simple function like this should do the trick :
<script language="javascript">
function clearData(){
window.clipboardData.setData('text','')
}
function cldata(){
if(clipboardData){
clipboardData.clearData();
}
}
setInterval("cldata();", 1000);
</script>
<body ondragstart="return false;" onselectstart="return false;" oncontextmenu="return false;" onload="clearData();" onblur="clearData();">
although this can still be defeated....
Just add the following code right before closing </HEAD>
tag of your web page:
<script>
function killCopy(e){
return false;
}
function reEnable(){
return true;
}
document.onselectstart=new Function ("return false");
if (window.sidebar){
document.onmousedown=killCopy;
document.onclick=reEnable;
}
</script>
I would suggest you to use:
<div oncopy="return false;">Here you have protected text</div>
Support for this method could be found here: http://help.dottoro.com/ljwexqxl.php
It is simple and in my opinion sufficient against regular users. To be honest there is no option to fully prevent copying text. One can always use for example Chrome Developer Tools and copy even dynamically loaded text from there.
For more effective protection you should place oncopy in <body> tag because otherwise it is possible to copy text by starting selection from outer <div>.
If you have your texts in particular divs, you could put a transparent div on top of those divs. Secondly, you could make all your protected text dynamic, and inject it into the divs from javascript where is would exist in a coded form -- that would defeat a 'view-source'.
<script type="text/javascript" language="javascript">
$(function() {
$(this).bind("contextmenu", function(e) {
e.preventDefault();
});
});
</script>
<script type="text/JavaScript">
function killCopy(e){ return false }
function reEnable(){ return true }
document.onselectstart=new Function ("return false");
if (window.sidebar)
{ document.onmousedown=killCopy;
document.onclick=reEnable; }
</script>
//By using above code you right click will be disabled as well as no one can copy your page content
A simple and valid solution - bind to the 'copy' event and prevent it. You can also set what text will be copied (and later pasted by the user).
document.addEventListener('copy', function (e){
e.preventDefault();
e.clipboardData.setData("text/plain", "Do not copy this site's content!");
})
Selecting text, copy, the right click can be disabled on a web page easily using jQuery. Below is the simple jQuery code snippet which can do this task easily:
<script type="text/javascript">
// Disable right click on web page
$("html").on("contextmenu",function(e){
return false;
});
// Disable cut, copy and paste on web page
$('html').bind('cut copy paste', function (e) {
e.preventDefault();
});
</script>
Source: Disable right click, copy, cut on web page using jQuery
To achieve that you need to block mouse click and context menu click on your webpage.
Here is a sample code:
<script language="JavaScript1.2">
var msgpopup="COPYING CONTENT IS PROHIBITED";
function handle(){
if(toShowMessage== "1") alert(message);
if(closeSelf== "1") self.close();
return false;
}
function mouseDown() {
if (event.button == "2" || event.button == "3"){handle();}
}
function mouseUp(e) {
//if (document.layers || (document.getElementById && !document.all)){
if (e.which == "2" || e.which == "3"){ handle();}
//}
}
document.onmousedown=mouseDown;
document.onmouseup=mouseUp;
document.oncontextmenu=new Function("alert(msgpopup);return false")
</script>
You can put the text in an input tag attributed as readonly and prevent the user from copy using JS. So, user cannot copy it even from developer menu.
I need to trigger a custom javascript function when something is typed into FCKeditor 2 textarea. However, I have searched far and wide and can't find an answer to this. Would like to do something like add onkeypress="customfunction()" to the textarea somehow.
Thanks for any help!
managed to find something in the end using some hints of words. Here is how to do an onkeypress even on FCKeditor 2.0. You need to load this javascript AFTER the editor code is called:
function FCKeditor_OnComplete(editorInstance){
if (document.all) { // If Internet Explorer.
editorInstance.EditorDocument.attachEvent("onkeydown", function(event){alert('key was pressed');} ) ;
} else { // If Gecko.
editorInstance.EditorDocument.addEventListener( 'keypress', function(event){alert('key was pressed')}, true ) ;
}
}
This seems to work:
CKEDITOR.instances.<yourEditorname>.document.on('key', function(event) { });
Found here: http://cksource.com/forums/viewtopic.php?t=18286
i'm trying to write unobtrusive default/placeholder text in input (actually, relatively placed label over input, which hides on onFocus, and stays hidden if input isn't empty on onBlur), but I don't want to use jQuery, because this is the only javascript used on page - therefore using jQuery seems a bit over the top.
Please, how can I do this without jQuery?
Thank you.
EDIT: I know the idea (getElementByID), but I'm more looking into how to add it to document - preferably something you have used before. Thank you.
EDIT: Thank you all, I finally went with jQuery, seeing answers :] (my example is here: http://jsbin.com/ehega/3 - it's concept, I'll probably add more eye candy. As an answer I Robert Koritnik - because of valid points... and styling ;])
you will need to manually attach the onfocus and onblur events, having got a handle on the input with getElementById.
here is an example: http://www.aspsnippets.com/Articles/Watermark-TextBox-using-JavaScript.aspx
I suggest you use jQuery
jQuery is nothing more than a cross-browser library that makes it easier for developers to achieve something and not worry about browser particularities. And when you load it once (it's rather small) it's cached so I wouldn't worry because it will save you lots of development/testing time later.
No? Then do it manually but make it more reusable
But if you do decide to do something manually you can always use regular Javascript and manipulate DOM as you wish. You best friends in this case would of course be (as Andrew pointed out):
getElementById() and
getElementsByTagName()
functions, but since you'll be manipulating DOM and styles, make sure you test your code against all common browsers. If you use custom attributes on INPUT elements it's good to use the second function, so you'll attach additional functionality to all inputs at once and only to those that define that particular custom attribute like:
<input type=text id="inputX" name="inputX" placeholder="Enter something">
Your script would then get all inputs and you'd check for the custom attribute existance and attach events to those elements that do define that attribute. This way you won't depend on IDs and make your code universal so you can reuse it app wide. Or even on other projects.
Just a sidenote: Andrew's example works somehow differently than what you said would like to do (using labels), but I suggest you use the same approach, because you'll be running scripts anyway. For the sake of unobtrusiveness make sure that you set default content using Javascript so default values and styles on textboxes won't be set for those users that are not running Javascript.
You can use jQuery and still be unobtrusive and use the ability of HTML5 Browsers, make your input like this:
<input type="whatever" placeholder="Your Default Text"/>
I user Modernizr to check the html5 capabilities of the browser and if the browser doesn't understand the placeholder attribute than I use this little javascript to emulate this function.
if (!Modernizr.input.placeholder) {
$('input').each(function(){
var obj = $(this);
var placeholder = obj.attr('placeholder');
if (placeholder) {
obj.val(placeholder);
obj.focus(function(){
var obj2 = $(this);
if (obj2.val() == obj2.attr('placeholder')) obj2.val('');
});
obj.blur(function(){
var obj2 = $(this);
if (obj2.val() == '') obj2.val(obj2.attr('placeholder'));
});
}
});
}
It is unobtrusive, because you don't need any javascript in your html code. the function above can easily changed if you want to use any other framework. I wouldn't use a solution without any Framework, because the frameworks do a great job in working around the incompatibilities between browsers.
This is how I would do it, without JQuery. It grays out the control when it shows the default text, and allows entering the default text if need be. The "title" tag will fallback to a tooltip for people who disable JavaScript:
<html>
<body>
<input type="text" value="" title="default text" />
<script type="text/javascript">
function DefaultInput(e) {
// Get the elements
this.e = e
this.d = e.title
this.s = e.style
e.removeAttribute('title') // remove the tooltip
e.value = '' // IE cached value remove HACK!
// Bind the events
e.onblur = this.bind(this.onblur)
e.onfocus = this.bind(this.onfocus)
// Show the initial value in gray
this.onblur()
}
DefaultInput.prototype = {
bind: function(f) {
// Return `f` so it's always called as an object of DefaultInput
var o = this
return function(){
f.apply(o, arguments)
}
},
onblur: function() {
// Gray out my value and show the default text if my value's blank
if (!this.h && !this.e.value) {
this.s.color = 'gray'
this.e.value = this.d
this.h = true // true -> help text displayed
// false -> help text hidden/user entered value
}
},
onfocus: function() {
// Make the text black and blank the text if in "help" mode
if (this.h) {
this.s.color = 'black'
this.e.value = ''
this.h = false
}
}
}
// Make sure the page is loaded before
// running for twitchy browsers like IE
window.onload = function() {
// Add defaults for all text input elements which have a `title`
var L = document.getElementsByTagName('input')
for (var i=0; i<L.length; i++) {
var e = L[i]
if (e.type=='text' && 'title' in e)
new DefaultInput(e)
}
}
</script>
</body>
EDIT: Cleared up the comments a bit, fixed some IE bugs and made it so it looks for <input> tags with title's to make it so different pages have less conversion time rather than individually intitializing the input controls ;-)
I think that you need something like this:
<input type="text" onfocus="if (this.value == this.getAttribute('mydefaulttext')) this.value = '';" onblur="if (this.value == '') this.value = this.getAttribute('mydefaulttext');" mydefaulttext="click here..." value="click here..."/>
<input name="test" type="text" id="test" value="testValue" />
<script type="text/javascript">
var myInput = document.getElementById("test");
myInput.onfocus = function() {
this.value = '';
}
myInput.onblur = function() {
if(this.value == '') this.value = "testValue";
}
</script>
Here's how I do:
Online Working Example
http://jsbin.com/ehivo3 (source code)
HTML
<input type="text" name="myfield" id="myfield" value="Please, fill my field!!!" />
jQuery
$(document).ready(function() {
// Handle each input on focus() and blug()
$('input[type="text"]').each(function() {
$(this)
// Store the default value internally
// Don't use .val() because browser autofill will poison it
.data('defaultValue', $(this).attr('value'))
// Handle the focus() (when you enter the field)
.focus(function() {
if ($(this).val() == $(this).data('defaultValue'))
$(this).val('');
})
// Handle the blur() (when you leave the field)
.blur(function() {
if ($(this).val() == '')
$(this).val($(this).data('defaultValue'));
});
});
// Clear all fields with "default value" on submit
$('form').submit(function() {
$('input[type="text"]', $(this)).each(function() {
// If the input still with default value, clean it before the submit
if ($(this).val() == $(this).data('defaultValue'))
$(this).val('');
});
});
});
And that's all! No invalid or extra attributes, valid markup and all handled in your jQuery file. :)