Am I using `button.disabled = true;` incorrectly? - javascript

I'm trying to build an interaction in Animate CC that plays movie clips, and the buttons disappear after they are clicked.
I'm trying to disable the other buttons temporarily while the movie clip plays over the main background, but it's not playing nice.
A code Snippet of the click handler:
exportRoot.btn_cook.addEventListener("click", cook_clickHandler.bind(this));
function cook_clickHandler(){
exportRoot.cook.gotoAndPlay(1); //play the info clip
exportRoot.btn_cook.visible = false; //hide button for no replays
disableAll();
}
disableAll(); does the following for each button on the canvas:
if(exportRoot.btn_receive.visible == true){
exportRoot.btn_receive.disabled = true;
}
I'm having some trouble trying to figure out how to use this properly. When I run through the interaction, I am still able to click on the buttons, even though I supposedly disabled them?
This demo won't load sound on GitHub, but it works otherwise. Click here to see it.

I had the same problem so I have another way to do it:
You can try to remove the eventListener click, like this:
if(!exportRoot.btn_receive.hasEventListener("click")){
exportRoot.btn_receive.removeEventListener("click", cook_clickHandler);
}
When u want this to be enabled again, add the eventListener.

The disabled attribute is a Boolean attribute. That means that just the presence of it is enough to cause the element to become disabled. It makes no difference what you set the value to. You need to remove the attribute from the element to remove the disabled effect.
Removing the event listener treats the symptom, it doesn't get to the heart of the issue.
Also (FYI), the visibility property gets values of "visible" or "hidden", not true or false.
Here is a simple example of how to apply and disable (no pun intended) the disabled attribute:
btnToggle.addEventListener("click", function(){
var elems = document.querySelectorAll(".disableEnable");
// Loop through each element in the class
elems.forEach(function(element){
// Check to see if the first element has the disabled attribute
// the value of the attribute doesn't matter. If the attribute
// is present, the element is currently disabled.
if(element.getAttribute("disabled")){
// Element is disabled, so enabled it by removing
// the attribute (not by setting a value)
element.removeAttribute("disabled");
} else {
// Element is enabled, so disable it by adding the disabled
// attribute. Again, the value doesn't matter, but convention
// says that we set a value of "disabled" to convey that it is
// a boolean attribute.
element.setAttribute("disabled", "disabled");
}
});
});
<button id="btnToggle">Disable / Enable</button>
<button class="disableEnable">Test Button</button>
<input class="disableEnable">
<input type="text" class="disableEnable">

Related

Javascript -- Why am I able to show a hidden div, but not hide it?

I'm trying to write a simple function to dynamically show or hide an element. I've written functions like this several times before and have never had an issue...I can't figure out what's going wrong here. I use Javascript to dynamically create the element, and then in the process of creating it and appending it to the page, I also write $(element).css("display", "none") so that it will be hidden on page load.
Now I'm writing an event listener function to display the hidden elements in response to a click event. When I click on the button with this event listener attached to it, the hidden elements DO appear (great!), but then when I click on the box again, they stay on the page. When I console.log out the function, I can see that it's always hitting the show condition and never hitting the hide condition...but I cannot figure out why after spending hours and hours looking at examples and trying different implementations.
To be clear, I did not assign display: none; in the static CSS stylesheet. I added it dynamically in the JS when I created the elements.
// Pass in an array of cards called "filterCards"
const toggleDisplayFilterCards = (filterCards) => {
// Loop through the cards, and for each card, grab the ID tag
for (let card of filterCards) {
card = `#filter-card-container_${card.id}`;
// If "display" style attribute = "none", show the div, else, hide it.
if ($(card).css("display", "none")) {
$(card).css("display", "")
console.log("show");
} else if ($(card).css("display", "")) {
$(card).css("display", "none");
console.log("hide");
}
}
};
Does anyone see a reason why this code would never hit the "hide" condition? I've inspected the element in the console once it's displayed on the page, and confirmed that the style attribute has been changed to "", so when I click the same button, I would expect the function to hit the "hide" condition.
What these two do
$(card).css("display", "none")
$(card).css("display", "")
is they set the style of the card, and then return the jQuery object containing the card. Objects are always truthy in JavaScript, so doing
if ($(card).css("display", "none")) {
doesn't make sense.
You need to retrieve the style (done with a single parameter), then compare it against the possible value.
if ($(card).css("display") === "none") {
...
} else {

Disabling a button via JS if a specific element ID appears on page

I am trying to use JS to change an add to cart button to be disabled if our inventory level (displayed on the front end in a <span>) is "out of stock". This JS is already set up on our site for changing button behaviour for variants (code at the bottom of the post) and so if I can integrate an additional conditional rule using our inventory <span> that would be amazing.
Here's the HTML for when the out of stock message appears:
<span class="LocationNoStock">Currently Sold Out</span>
I honestly have almost zero experience with JS so all I know is that I can look for elements by class name:
(document.getElementsByClassName("LocationNoStock")
Basically I want to add logic that dictates:
if class 'LocationNoStock' exists then disable 'add-to-cart' button
Any help that can be offered would be much appreciated! If it helps, our current JS for modifying the add-to-cart button is as follows - if an additional rule to search for the <span> could be inserted and mimic the behaviour that would be amazing!
updateCartButton: function(evt) {
var variant = evt.variant;
if (variant) {
if (variant.available) {
// Available, enable the submit button and change text
$(selectors.addToCart, this.$container).removeClass(classes.disabled).prop('disabled', false);
$(selectors.addToCartText, this.$container).html(theme.strings.addToCart);
} else {
// Sold out, disable the submit button and change text
$(selectors.addToCart, this.$container).addClass(classes.disabled).prop('disabled', true);
$(selectors.addToCartText, this.$container).html(theme.strings.soldOut);
}
} else {
// The variant doesn't exist, disable submit button
$(selectors.addToCart, this.$container).addClass(classes.disabled).prop('disabled', true);
$(selectors.addToCartText, this.$container).html(theme.strings.unavailable);
}
},
Your using jquery $(...) so you could do the following, look for .LocationNoStock if it's found then disable the .add-to-cart button.
if ($('.LocationNoStock').length) $('.add-to-cart').attr('disabled', 'disabled')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="LocationNoStock">Currently Sold Out</span>
<button type="button" class="add-to-cart">Add to Cart</button>
To disable buttonin javascript on load, can be done by setting attribute of the element
Example :
setAttribute("style","color:red")
In your case you are fetching element using class "add-to-cart" which gives htmlcollection so using index you can access the button element and then using setAttribute function of javascript, can set particular properties.
Try this:
$(document).ready(function(){
if (document.getElementsByClassName("LocationNoStock") != null){
var element = document.getElementsByClassName("add-to-cart");
element[0].setAttribute("disabled", "");
}
});

Hide a button until check box is checked, without ID

I need to hide a button until a check box is clicked, however I am stepping into someone elses code who used tag libraries that did not define ID in the button tag. Here is what I have:
The button code:
<html:button name="Next" value="BTN.NEXT" styleClass="button" localeCd="<%= localeCd %>" onClick='Submit("Next")'/>
The checkbox code:
<input type="checkbox" name="fedCheck" onclick="checkFed(this, 'myNext')" value="y" />
The Javascript Code
function checkFed(ele, id) {
x = document.getElementById(id);
if (ele.checked == true) x.disabled = false;
else x.disabled = true;
}
I can get this to work in a seperate page but the page that it is on does not allow for the button to have an ID so it crashes every time. Any suggestions?
There would be better ways of doing this, listening for the click event, etc... but, to simply modify your code see this jsFiddle (note: this assumes this is the only element named "Next"):
function checkFed(ele, name) {
x = document.getElementsByName(name)[0];
x.disabled = !x.disabled
}
And change the onclick="checkFed(this, 'myNext')" to:
onclick="checkFed(this, 'Next')"
And add disabled="true" to the button so that it's initial state is disabled
...also note that this doesn't actually hide it like the title asks, it disables it, like the content of the question seems to ask.
Instead of finding the button using document.getElementById, use document.querySelector.
For example, if you have a single button on the page with "Next" as the value of its name attribute:
document.querySelector('button[name="Next"]')

Dynamically creating an input field with disabled = true is setting null values to zero

I have a timesheet table. At the bottom of the table there is a button which allows me to add a row. Understandably, all the cells in the new row start off empty. The JavaScript uses:
txtFld.setAttribute('value', '');
to do so.
However, in some situations I want some of the new fields to show up but be disabled so I (in those situations) add in:
txtFld.setAttribute('disabled', 'disabled');
The problem is that, when doing this, after submission, when the table re-renders itself, all those empty values show up as zeroes instead of empty strings. As far as calculations go, that's fine, but I don't want rows of zeroes. I want empty cells. If I take out the disabled part, it works fine.
I've temporarily remedied this by, instead of using disabled, using readonly, which seems to give me the desired results. The only problem is that, while the text field remains non-editable, the user CAN place the cursor inside the box. I want the cleaner, "can't even click in here" that the disabled gives me.
Any thoughts on why the disabled feature is doing this and how I can use disabled without the resulting row of zeroes?
For the record, I've mixed and matched every combination of:
txtFld.setAttribute('value','');
txt.setAttribute('value', null);
txtFld.value = '';
txtFld.value = null;
with
txtFld.setAttribute('disabled');
txtFld.setAttribute('disabled', 'true');
txtFld.setAttribute('disabled', 'disabled');
txtFld.disabled = 'true';
txtFld.disabled = 'disabled';
that I can think of with the same results (or worse) every time.
Thanks.
When a field is disabled, it's not included in the form parameters sent to the server.
In new browsers (IE11+, and pretty much everything else) you can use CSS to disable pointer events on the element:
txtFld.readonly = true;
txtFld.style.pointerEvents = 'none';
That'll make the element simply not respond to any clicks. (Here is a jsfiddle.) Because it's not disabled, a form POST will send the empty field to the server.
You should disable fields by setting the "disabled" property of their DOM nodes to true (the boolean constant, not the string).
txtFld.disabled = true; // disables field
txtFld.disabled = false; // enables field
The "disabled" property is treated as a boolean, so setting it to any string value (other than the empty string) will set it to true:
txtFld.disabled = "false"; // disables field
Another thing you can do to exploit the real disabled browser behavior and have empty parameters posted to the server is to use pairs of inputs:
<input type=text name=whatever data-companion=whatever-c> <!-- visible input -->
<input type=hidden name=whatever id=whatever-c> <!-- invisible input -->
Now whenever you enable the text field, you disable the hidden input, and vice-versa. That way there's always something posted.

Prevent checkbox from ticking/checking COMPLETELY

I have been asked to disable the "ticking" of a checkbox. I am not being asked to disable the checkbox, but to simply disable the "ticking".
In other words, a user will think that a checkbox is tickable, but it is not. Instead, clicking on the checkbox will cause a modal dialog to appear, giving the user more options to turn on or off the feature that the checkbox represents. If the options chosen in the dialog cause the feature to be turned on, then the checkbox will be ticked.
Now, the real problem is that for a split second, you can still see that the checkbox is being ticked.
I have tried an approach like this:
<input type='checkbox' onclick='return false' onkeydown='return false' />
$('input[type="checkbox"]').click(function(event) {
event.preventDefault();
alert('Break');
});
If you run this, the alert will appear, showing that the tick is visible (the alert is just there to demonstrate that it still does get ticked, in production, the alert is not there). On some users with slower machines and/or in browsers with slow renderers/javascript, users can see a very faint flicker (the flicker sometimes lasts for half a second, which is noticeable).
A tester in my team has flagged this as a defect and I am supposed to fix it. I'm not sure what else I can try to prevent the tick in the checkbox from flickering!
From my point of view it is as simple as:
$(this).prop('checked', !$(this).prop('checked'));
Works both for checked and unchecked boxes
Try
event.stopPropagation();
http://jsfiddle.net/DrKfE/3/
Best solution I've come up with:
$('input[type="checkbox"]').click(function(event) {
var $checkbox = $(this);
// Ensures this code runs AFTER the browser handles click however it wants.
setTimeout(function() {
$checkbox.removeAttr('checked');
}, 0);
event.preventDefault();
event.stopPropagation();
});
This effect can't be suppressed I fear. As soon as you click on the checkbox, the state (and rendering) is changed. Then the event handlers will be called. If you do a event.preventDefault(), the checkbox will be reset after all the handlers are executed. If your handler has a long execution time (easily testable with a modal alert()) and/or the rendering engine repaints before reseting, the box will flicker.
$('input[type="checkbox"]').click(function(event) {
this.checked = false; // reset first
event.preventDefault();
// event.stopPropagation() like in Zoltan's answer would also spare some
// handler execution time, but is no more needed here
// then do the heavy processing:
alert('Break');
});
This solution will reduce the flickering to a minimum, but can't hinder it really. See Thr4wn's and RobG's answer for how to simulate a checkbox. I would prefer the following:
<button id="settings" title="open extended settings">
<img src="default_checkbox.png" />
</button>
document.getElementById("settings").addEventListener("click", function(e) {
var img = this.getElementsByTagName("img")[0]);
openExtendedSettingsDialog(function callbackTick() {
img.src = "checked_checkbox.png";
}, function callbackUntick() {
img.src = "unchecked_checkbox.png";
});
}, false);
It is very important to use return false at the end.
Something like this:
$("#checkbox").click((e) => {
e.stopPropagation();
return false;
});
Isn't is simpler ? :
<input type="checkbox" onchange="this.checked = !this.checked">
TL:DR;
HTML api's execute before JavaScript. So you must use JavaScript to undo HTML's changes.
event.target.checked = false
WHAT is the problem?
Strictly speaking: we cannot "stop" the checkbox from being ticked. Why not? Because "being ticked" exactly means that the DOM's, HTML <input> element has a checked property value of true or false, which is immediately assigned by the HTML api
console.log(event.target.checked) // will be opposite of the previous value
So it's worth explicitly mentioning this HTML api is called before scripts. Which is intuitive and should make sense, because all JavaScript files are themselves the assignment of a <script> element's attribute src, and the ancestral relationship in the DOM tree, between your <input> in question, and the <script> element running your JavaScript, is extremely important to consider.
HOW to get our solution
The HTML assigned value has not yet been painted before we have a chance to intercept the control flow (via JS file like jQuery), so we simply re-assign the checked property to a boolean value we want: false (in your case).
So in conclusion, we CAN, in-effect, "stop" the checkbox from being checked, by simply ensuring that the checked property is false on the next render and thus, won't see any changes.
Why not simply add a class in your CSS that sets pointer-events: none;?
Something like:
<style>
input.lockedCbx { pointer-events: none; }
</style>
...
<input type="checkbox" class="lockedCbx" tabindex=-1 />
...
You need the tabindex=-1 to prevent users from tabbing into the checkbox and pressing a space bar to toggle.
Now in theory you could avoid the class and use the tabindex=-1 to control the disabling as in:
<script>
input[type="checkbox"][tabindex="-1"] { pointer-events: none; }
</script>
With CSS, you can change the image of the checkbox. See http://ryanfait.com/resources/custom-checkboxes-and-radio-buttons/ and also CSS Styling Checkboxes .
I would disable the checkbox, but replace it with an image of a working checkbox. That way the checkbox doesn't look disabled, but won't be clickable.
Wrap the checkbox with another element that somehow blocks pointer events (probably via CSS). Then, handle the wrapper's click event instead of the checkbox directly. This can be done a number of ways but here's a relatively simple example implementation:
$('input[type="checkbox"').parent('.disabled').click( function() {
// Add in whatever functionality you need here
alert('Break');
});
/* Insert an invisible element that covers the checkbox */
.disabled {
position: relative;
}
.disabled::after {
content: "";
position: absolute;
top: 0px;
left: 0px;
right: 0px;
bottom: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Only wrapped checkboxes are "disabled" -->
<input type="checkbox" />
<span class="disabled"><input type="checkbox" /></span>
<input type="checkbox" />
<span class="disabled"><input type="checkbox" /></span>
<span class="disabled"><input type="checkbox" /></span>
<input type="checkbox" />
Note: You could also add the wrapper elements programmatically, if you would like.
Sounds to me like you are using the wrong interface element, a more suitable one would be a button that is disabled by default, but enabled when that option is available. The image displayed can be whatever you want.
<button disabled onclick="doSomething();">Some option</button>
When users have selected that feature, enable the button. The image on the button can be modified by CSS depending on whether it's enabled or not, or by the enable/disable function.
e.g.
<script type="text/javascript">
function setOption(el) {
var idMap = {option1:'b0', option2: 'b1'};
document.getElementById(idMap[el.value]).disabled = !el.checked;
}
</script>
<div><p>Select options</p>
<input type="checkbox" onclick="setOption(this);" value="option1"> Option 1
<br>
<input type="checkbox" onclick="setOption(this);" value="option2"> Option 2
<br>
</div>
<div>
<button id="b0" onclick="alert('Select…');" disabled>Option 1 settings</button>
<button id="b1" onclick="alert('Select…');" disabled>Option 2 settings</button>
</div>
The Event.preventDefault method should work for change, keydown, and mousedown events, but doesn't in my testing.
My solution to this problem in a Mozilla Firefox 53.0 extension was to toggle an HTML class that enabled/disabled the CSS declaration pointer-events: none being applied to the checkbox. This addresses the cursor-based case, but not the key-based case. See https://www.w3.org/TR/SVG2/interact.html#PointerEventsProp.
I addressed the key-based case by adding/removing an HTML tabindex="-1" attribute. See https://html.spec.whatwg.org/multipage/interaction.html#attr-tabindex.
Note that disabling pointer-events will disable your ability to trigger CSS cursors on hover (e.g., cursor: not-allowed). My checkbox was already wrapped in a span element, so I added an HTML class to that span element which I then retargeted my CSS cursor declaration onto.
Also note that adding a tabindex="-1" attribute will not remove focus from the checkbox, so one will need to explicitly defocus it by using the HTMLElement.blur() method or by focusing another element to prevent key-based input if the checkbox is the active element at the time the attribute is added. Whether or not the checkbox is the focused element can be tested with my_checkbox.isEqualNode(document.activeElement).
Simply revert the value back
$('input[type="checkbox"]').on('change', function(e) {
if (new Date().getDate() === 13) {
$(this).prop('checked', !$(this).prop('checked'));
e.preventDefault();
return false;
}
// some code here
});
Add this to click event in js file
event.stopPropagation();
$('#term-input').on('change click',function (e){
e.preventDefault();
})
works for me

Categories