keep checkbox enabled using jquery or javascript - javascript

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.

Related

Changing Style From JavaScript Not Saving

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();
}
});
});

ASP.Net Custom Checkbox property checked

so recently I started a C# Asp.Net quiz for one of my school projects, but I ran into the following problem:
My index.aspx site:
<form runat="server" class="ac-custom ac-checkbox ac-boxfill" autocomplete="off" onload="Page_Load">
<asp:CheckBox ID="q1a1" runat="server" Text="example answer" onclick="changeState(this);" />
</form>
I applied to the checkbox the onClick event which fires (I tested it out) the
changeState()
event. But so far, nothing is happening to one of the properties when I try to change it.
So, for the custom checkbox I use this:
(I hope it is okay, that I post a link reference to it. Either way, I'll do it.
Reference for the custom animated Checkboxes
So, when I click the checkbox, the custom style applies to it, but the checked property doesn't change at all. So I started experiment a bit around with Javascript, but came to no solution.
The javascript I use:
<script type="text/javascript">
function changeState(caller) {
if (document.getElementById(caller.id).checked)
{
document.getElementById(caller.id).checked = false;
}
else
{
document.getElementById(caller.id).checked = true;
}
}
</script>
Also I read somewhere, that you can use a thing like:
document.getElementById(caller.id).click();
to change the checkstate. But both of these things doesn't helped me.
Maybe you guys can give me some hope, pretty sure it can be a simple solution. But I'n open for all tips or changes.
This javascript is the issue, you are checking if it's checked and then setting it to false so it's unchecking it.
<script type="text/javascript">
function changeState(caller) {
if (document.getElementById(caller.id).checked)
{
document.getElementById(caller.id).checked = false;
}
else
{
document.getElementById(caller.id).checked = true;
}
}
</script>
I would use a variable like isCheckboxChecked to hold the value of the checkbox checked state.

Disable Firefox auto-search when using keypress() in JS

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.

Javascript getElementById value setting getting reset on function return

I have a simple function to show / hide a div element. I have a javascript function to do that. I debugged this with Opera. The function sets the hidden value properly on the div element. I can see the div element disappear. However, when the function returns the div element reappears. The javascript function is in its own file:main.js:
function showhide(name){
var elem = document.getElementById(name) ;
if( elem.hidden == false ) {
document.getElementById(name).hidden = true ;
} else {
document.getElementById(name).hidden = false ;
}
}
The Html is:
<div class=wrap><p>
<div class=sidebar>
<FORM><input type="submit" value="Toggle" onclick="showhide('specname');"/></FORM></div>
<div class=main>main Div
<div id="specname">collapsible text</div></div></p></div>.
I have set debugging breakpoints in the javascript function showhide to see that the value is being set properly. But on function return, the value is reset.
It is probably something simple I am missing but can't seem to see it? Any ideas? Thanks!
The answers solved my problem. I was missing the fact that the submit repainted the page and I lost my changes. I changed the type=submit to type=button. And I removed the form to just an input element with type button. That worked very nicely. Thanks everyone for your help!!! I really appreciate your answers!
The following wont do anything in some browsers:
document.getElementById(name).hidden = true
change it to
document.getElementById(name).style.display = 'block' // and 'none' for the matching line
does that make it do what you need?
As others have pointed at, it is also submitting the page - either use a different element or change the function to start :
function showHide(e, name) {
e.preventDefault();
//do the toggle here
return false;
}
The problem is you are using a submit control which will submit to the server and refresh the page. You want to stop the submit or change the control type. Both of the following should work. I recommend the 2nd one.
Try this
<FORM><input type="submit" value="Toggle" onclick="showhide('specname'); return false;"/>
or this
<input type="button" value="Toggle" onclick="showhide('specname');"/>
Probably because when you click the button the form submits and it refreshes the page ?
You should not be using a form just to have a button that does something. Instead, try using
<button onClick="showhide('specname');">Toggle</button> (and get rid of the form entirely)
Try this for your showhide().
function showhide(name){
var elem = document.getElementById(name);
(elem.style.visibility == 'hidden'?elem.style.visibility = 'visible':elem.style.visibility = 'hidden');
}
OR similarly:
function showhide(name){
var elem = document.getElementById(name);
(elem.style.display== 'none'?elem.style.display= 'inline':elem.style.display= 'none');
}
Maybe try them both and see which you need.
Cheers.

unobtrusive "default" text in input WITHOUT jQuery

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. :)

Categories

Resources