Check if a div is disabled jQuery - javascript

I need to check whether myDiv1 is disabled. If so, I need to hide myDiv2, otherwise I need to show myDiv2.
Here is what I have so far:
$(document).ready(function () {
var isDisabled = $('#myDiv1').is('[disabled=disabled]')
alert(isDisabled); //this always returns false
if(isDisabled)
$("#myDiv2").hide();
else
$("#myDiv2").show()
});
But isDisabled return always false even when myDiv1 is enabled. What am I missing here?

So many answers, but none addressing the actual problem: A div element doesn't allow an attribute of type disabled. On a div only global attributes are allowed, whereas disabled is allowed on form elements.
You can easily verify it by testing this HTML:
<div id="a" disabled></div>
<input id="b" disabled>
against this JavaScript:
var e = $('#a');
alert(e.is(':disabled'));
var e = $('#b');
alert(e.is(':disabled'));
Which will return false and true.
What's a solution then?
If you want to have an attribute that is actually named disabled use a data-* attribute:
<div id="c" data-disabled="true"></div>
And check it using this JavaScript:
var e = $('#c');
alert(e.data('disabled'));
or:
var e = $('#c');
alert('true' === e.attr('data-disabled'));
Depending on how you're going to handle attached data-*-attributes. Here you can read more about jQuery's .data() which is used in the first example.
Demo:
Try before buy

The reason why isDisabled returns false to you is, because you have most likely set the following in your HTML:
<div id = "myDiv1" disabled>...</div>
In reality, disabled means disabled = "", so, since "disabled" != "", if you keep using $('#myDiv1').is('[disabled=disabled]') you will always get false.
What will work:
To make this work, as other answers have mentioned, you can use:
$('#myDiv1').attr('disabled') == "disabled" (#guradio answer),
$('#myDiv1').is('[disabled=""]') or
$('#myDiv1')[0].getAttribute("disabled") != null.
What won't work:
While $('#myDiv1')[0].getAttribute("disabled") != null will work regardless of what element the attribute is set on, on the other hand, $('#myDiv1')[0].disabled will only work on 'form elements' and will return undefined for all others (check out the note at the end).
The same occurs when you use $('#myDiv1').is(':disabled') as well.
Alternatively, if you want to keep your code intact, you can set disabled = "disabled" in your HTML and the problem will be solved.
Working Example (using 2.):
/* --- JavaScript --- */
$(document).ready(function(isDisabled) {
isDisabled = $('#myDiv1').is('[disabled=""]');
if (isDisabled) $("#myDiv2").hide();
else $("#myDiv2").show()
/* Will return 'true', because disabled = "" according to the HTML. */
alert(isDisabled);
});
<!--- HTML --->
<script src = "//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "myDiv1" disabled>DIV 1</div>
<div id = "myDiv2">DIV 2</div>
Note: Beware, however, that the disabled attribute is meant to be used with 'form elements' rather than anything else, so be sure to check out the very informative answer of #insertusernamehere for more on this. Indicatively, the disabled attribute is meant to be used with the following elements:
button,
fieldset (not supported by IE),
input,
keygen (not supported by IE),
optgroup (supported by IE8+),
option (supported by IE8+),
select and
textarea.

$('#myDiv1').attr('disabled') == "disabled" ? $("#myDiv2").hide() : $("#myDiv2").show();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='myDiv1' disabled="true">1</div>
<div id='myDiv2'>2</div>
Try this way. But i dont think div has disable attribute or property
$('#myDiv1[disabled=true]').length > 0 ? $("#myDiv2").hide() : $("#myDiv2").show();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='myDiv1' disabled="true">1</div>
<div id='myDiv2'>2</div>
Using attribute selector
attribute selector
Description: Selects elements that have the specified attribute with a value exactly equal to a certain value.

First you need to set disabled property for your div
<div id="myDiv" disabled="disabled">This is Div</div>
Then you need to use this
$('#myDiv1').is('[disabled=disabled]')

Use this one:
$(document).ready(function () {
if($('#myDiv1').is(':disabled'))
$("#myDiv2").hide();
else
$("#myDiv2").show()
});

I hope this will help you:
$(document).ready(function () {
var isDisabled = $('#myDiv1').is(':disabled')
if(isDisabled)
$("#myDiv2").hide();
else
$("#myDiv2").show()
});

Use $("#div1").prop("disabled") to check whether the div is disabled or not. Here is a sample snippet to implement that.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<style>
.container {
width: 100px;
height: 100px;
background: grey;
margin: 5px;
float: left;
}
div {
width: 100%;
float: left;
}
</style>
</head>
<body>
<div>
<input type="checkbox" id="ChkBox" onclick="UpdaieDivStatus()" /> Toggle access
</div>
<div id="div1" class="container">Div 1</div>
<div id="div2" class="container">Div 2</div>
<script>
function UpdaieDivStatus() {
if ($("#ChkBox").prop('checked')) {
$("#div1").prop("disabled", true);
} else {
$("#div1").prop("disabled", false);
}
if ($('#div1').prop('disabled')) {
$("#div2").hide();
} else {
$("#div2").show();
}
console.log($("#div1").prop("disabled"));
}
</script>
</body>
</html>

If you look at this MDN HTML attribute reference, you will note that the disabled attribute should only be used on the following tags:
button, command, fieldset, input, keygen, optgroup, option, select,
textarea
You can choose to create your own HTML data-* attribute (or even drop the data-) and give it values that would denote the element being disabled or not. I would recommend differentiating the name slightly so we know its a custom created attribute.
How to use data attributes
For example:
$('#myDiv1').attr('data-disabled') == "disabled"

Why don't you use CSS?
html:
<div id="isMyDiv" disabled>This is Div</div>
css:
#isMyDiv {
/* your awesome styles */
}
#isMyDiv[disabled] {
display: none
}

Set the disabled attribute on any HtmlControl object. In your example it renders as:
<div id="myDiv1" disabled="disabled"><div>
<div id="myDiv2" ><div>
and in javascript can be checked like
('#myDiv2').attr('disabled') !== undefined
$(document).ready(function () {
if($('#myDiv1').attr('disabled') !== undefined)
$("#myDiv2").hide();
else
$("#myDiv2").show()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<div id="myDiv1" disabled="disabled">Div1<div>
<div id="myDiv2" >Div1<div>

Related

when checkbox is checked, change background color of div

What I'm trying to do is when the checkbox is checked, change the background color of the div, and when it's unchecked, remove the background color. How can I do this using jquery?
<div class="checkbox-container">
<input type="checkbox" class ="checkbox-border" id="personal-info-checkbox">
<label for="personal-info-checkbox"> Mark as reviewed and acknowledged
</label>
</div>
using parent selector and .removeclass I do not know how to select my div and turn the color off and on using jquery.
You don't need jQuery for this
You can do this only with css.
.checkbox-container:has(input:checked) {
background-color: red;
}
:has pseudo class is supported in chromium, safari.
For firefox, need to enable flag.
know more at mdn ::has pseudo class
Add a change event listener to the input that sets its closest parent div's background color based on whether it is checked:
$('input[type="checkbox"]').change(function(){
$(this).closest('div').css('background-color', this.checked ? 'green' : 'white')
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="checkbox-container">
<input type="checkbox" class ="checkbox-border" id="personal-info-checkbox">
<label for="personal-info-checkbox"> Mark as reviewed and acknowledged
</label>
</div>
Try this I hope this will help you
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#personal-info-checkbox").click(function(){
if($(this).is(":checked")){
$(this).parent().addClass("color-blue");
}else {
$(this).parent().removeClass("color-blue");
}
});
});
</script>
<style>
.checkbox-container
{
padding:20px;
}
.color-blue {
background-color:blue;
}
</style>
</head>
<body>
<div class="checkbox-container">
<input type="checkbox" class ="checkbox-border" id="personal-info-checkbox">
<label for="personal-info-checkbox"> Mark as reviewed and acknowledged
</label>
</div>
</body>
</html>
Here's an example of how you can do this
$(function() {
$("input[type=checkbox]").click( () => {
$("div").toggleClass("background");
})
});
.background {
background: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="height:4em;">
Change colors<input type="checkbox" />
</div>
There are a number of ways to do this:
CSS (with limited, as of writing, browser support),
jQuery (among other libraries), and
native JavaScript.
The below example has explanatory comments in the code:
// using jQuery, we select the relevant element via its class, and use the on()
// method to bind the anonymous function as the event-handler for the 'change'
// event:
$('.checkbox-container.with-jQuery').on('change', function(){
// here we find the <input> element descendant with find(), and then use the
// is() method to test that element to see if it matches the :checked pseudo-
// class; this returns a Boolean true/false which is cached in the 'checked'
// variable:
let checked = $(this).find('input').is(':checked');
// here we use toggleClass() to toggle the 'checked' class-name on the element,
// and use the 'checked' variable to ascertain whether the class should be
// added/retained (if the Boolean is true) or removed/not-added (if the Boolean
// is false):
$(this).toggleClass('checked', checked);
});
// using JavaScript we use document.querySelector to retrieve the element
// with the listed classes; and use EventTarget.addEventListener() to bind the
// anonymous Arrow function as the event-handler for the 'change' event:
document.querySelector('.with-JavaScript.checkbox-container').addEventListener('change',(evt)=>{
// we cache a reference to the current element (the <div>):
let current = evt.currentTarget,
// we find the <input> descendant, and access its checked property to
// obtain a Boolean true (if checked) or false (if not-checked) and
// store that Boolean in the 'checked' variable:
checked = current.querySelector('input').checked;
// here we use Element.classList.add() to add the 'active' class-name,
// with the checked variable to determine if it should be added/retained
// (if true) or removed/not-added (if false):
current.classList.add('active', checked);
});
:root {
--checkedColor: lime;
}
/* here we select the element via classes, and use :has()
to check if it has a descendant element which matches
the enclosed selector: */
.with-CSS.checkbox-container:has(input:checked) {
/* if so, we set the --checkedColor custom property
as the background-color of the element: */
background-color: var(--checkedColor);
}
.with-jQuery.checkbox-container.checked {
background-color: var(--checkedColor);
}
.with-JavaScript.checkbox-container.active {
background-color: var(--checkedColor);
}
<!-- each wrapper <div> has a 'with-...' class applied in order to identify which
approach is being taken: -->
<div class="checkbox-container with-CSS">
<!-- an id must be unique, to that end - because there are three checkboxes in
this example - the id has been modified, as has the corresponding <label>
element's 'for' attribute: -->
<input type="checkbox" class="checkbox-border" id="personal-info-checkbox1">
<label for="personal-info-checkbox1"> Mark as reviewed and acknowledged
</label>
</div>
<div class="checkbox-container with-jQuery">
<input type="checkbox" class="checkbox-border" id="personal-info-checkbox2">
<label for="personal-info-checkbox2"> Mark as reviewed and acknowledged
</label>
</div>
<div class="checkbox-container with-JavaScript">
<input type="checkbox" class="checkbox-border" id="personal-info-checkbox3">
<label for="personal-info-checkbox3"> Mark as reviewed and acknowledged
</label>
</div>
References:
Browser compatibility:
:has().
CSS:
CSS Custom properties.
:checked.
:has().
var().
JavaScript:
document.querySelector().
Element.classList API.
jQuery#
is().
on().
toggleClass().

Check if all spans with class "x" in a given div have an attribute

How can I check, with js or jquery, whether all spans with class "x" in a given div have the attribute style="display: none".
I tried $('div').find('.x').att('style', 'display: none'), but it doesn't work.
You can use the :hidden selector to find display="none" elements and compare the length vs all .x elements
let allHidden = $('div').find('.x:hidden').length === $('div').find('.x').length
Along with .hidden count vs all count, you can check if there are any that are not hidden:
var allHidden = $('div').find('.x:not(:hidden)').length == 0
This may give a false positive if you don't have any at all. It's up to you if "none" is the same as "all hidden" or if that's a case in your scenario.
You can also use the Attribute Selector.
$(function() {
var hidden = $("div > span.foo:hidden").length;
var styleCount = $("div > span.foo[style*='display: none']").length;
console.log(hidden, styleCount);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<span class="foo" style="display: none">I am hidden</span>
<span class="foo">I am visible</span>
</div>
See More: https://api.jquery.com/category/selectors/attribute-selectors/
You can use the *= to ensure that we can find display: none in the style attribute. You can use = for a direct comparison, yet this can fail if there are any other items in the style. Using the *= will allow it to be found in the following patterns:
style="display: none;"
style="display: none"
style="color: red; display: none;"
I will give you the simplest answer for you.
var hiddenItems = $("div").find('span.x:hidden');
console.log(hiddenItems);
alert("Check the results in the console.");

jQuery append method inserting text rather than HTML

I want append an input text in my html page. I use JQuery to do that.
My JQuery script :
$(document).ready(function(){
$(".reply").click(function(){
var tempat=$(this).parent().parent().next(".komentar-balasan");
console.log(tempat[0]);
var html=
tempat[0].append('<input type="text"></input>');
});
});
And the HTML :
<div class="isi">
<div class="like-comment">
<div class="kotak"></div>
<div class="kotak-jumlah">
</div>
<div class="kotak"><button class="reply"></button></div>
</div><div class="komentar-balasan"></div>
The Fiddle
I Don't know why, but instead of displayed the input text box. The browser just display <input type="text"></input>. It's like the browser didn't recognize the HTML code.
It's because tempat[0] is accessing the underlying DOM node rather than the jQuery wrapper. It works fine if you omit the array access and just call append on tempat.
You don't need it here but the right way to get a jQuery wrapped element of a jQuery selector list is to use eq
The problem is that you aren't calling the append element on a jQuery object (which treats strings as HTML), but instead on a native DOM element. The experimental ParentNode#append method treats strings as text, so you are seeing text.
If you omit the [0] before calling append, your code runs perfectly:
$(document).ready(function() {
$("#post-komentar").click(function() {
console.log($(this).siblings('.editor-komentar').val());
});
$(".reply").click(function() {
var tempat = $(this).parent().parent().next(".komentar-balasan");
console.log(tempat[0]);
var html =
tempat.append('<input type="text"></input>');
});
});
.reply {
background-color: #fff;
width: 20px;
height: 20px;
margin: 0;
padding: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="isi">
<div class="like-comment">
<div class="kotak"><</div>
<div class="kotak-jumlah">
</div>
<div class="kotak"><button class="reply"></button></div>
</div>
<div class="komentar-balasan"></div>
Hello,
Check if this is what you need:
You need to create an element and only then add it.
Here is an example:
$(document).ready(function(){
$(".reply").click(function(){
var tempat=$(this).parent().parent().next(".komentar-balasan");
console.log(tempat[0]);
var newEl = document.createElement('input');
newEl.type = "text";
tempat.append(newEl);
});
});
I hope I have helped!
Remove the [0]. You are dereferencing your jQuery object by doing that.
This works: tempat.append('<input type="text"></input>');

How to change the colour of a div element when clicked?

I have a this html page, Whenever the element with class name FreeSeat is clicked I want to change the colour of that div element.Below is my html page
<html>
<head>
<title>
QuickBus
</title>
<link type="text/css" rel="stylesheet" href="Seat.css">
</head>
<body>
<div id="Bus">
<div class="Row">
<div class="FreeSeat" ></div>
<div class="FreeSeat" ></div>
<div class="ResSeat" ></div>
<div class="ResSeat" ></div>
<div class="ResSeat" ></div>
</div>
</div>
<body>
</html>
It will be very helpful if anyone can help me out with this .
Considering that you want to use pure JS and not any library, you'd have to manually add event listeners to your classes.
And it has been solved for a similar problem here
var freeclass = document.getElementsByClassName("FreeSeat");
var myFunction_Free = function() {
this.style.color = "blue";
}
for(var i=0;i<freeclass.length;i++){
freeclass[i].addEventListener('click', myFunction_Free, false);
}
But for your case, here's a working fiddle
JQuery is amazing for these sorts of things.
Say you have a div with id 'box1'
<div id='box1'></div>
Style it with css
#box1 {
width:100px;
height:100px;
background-color:white;
border:1px solid black;
}
Using JQuery, you can make this call:
$( "#box1" ).click(function() {
$('#box1').css('background-color', 'red');
});
And now whenever your div is clicked, the colour will change, you can customise this however much you like.
Here is a JSFiddle demo.
Also, since you didn't specify exactly what you want to change the colour of, in my example jquery, it is telling the browser that when a div with an id of box1is clicked, change the background-color of the div with an id of box1, you can change anything though.
If you have a <p> tag you can change that too when the div is clicked, hope this helped!
You can use the following method to change the background color of an element by class:
const free_seat = document.getElementsByClassName('FreeSeat');
free_seat[0].style.backgroundColor = '#ff0';
Each element can be referenced by its index:
free_seat[0] // first div
free_seat[1] // second div
Therefore, we can create a function that will be called whenever the click event is delivered to the target:
const change_color = () => {
this.style.backgroundColor = '#ff0';
};
for (let i = 0; i < free_seat.length; i++) {
free_seat[i].addEventListener('click', change_color);
}
Note: You can also use document.querySelectorAll('.FreeSeat') to obtain a NodeList of elements of a certain class.
You can use simply the css focus pseudo-class for this:
#foo:focus {
background-color:red;
}
<div id="foo" tabindex="1">hello world!</div>
Dont forget to set the tabindex.

Enable/disable button on contentEditable keyup

I have a couple of divs on my website that utilize the HTML5 contentEditable attribute. The goal is for the user to be able to start writing a journal entry, and have the save button change from disabled to enabled.
Here's the HTML I have so far:
<div id="entry-create-partial">
<div id="title-create-partial" name="title" contenteditable="true" data-placeholder='Title it' style="color:black"></div>
<div id="content-create-partial" name="content" contenteditable="true" style="color:gray">Write anything</div>
<button type="button" id="create-entry" class="btn" disabled="true">Save</button>
</div>
And here's the jQuery:
$(document).ready(function(){
$('#title-create-partial').keyup(function(){
if ($(this).value == '') {
$('#create-entry').attr('disabled', 'disabled');
} else {
$('#create-entry').attr('disabled', false);
}
});
});
While this does work, it only checks on the first keyup; if the user backspaces and deletes everything they typed, the button doesn't disable itself again. Does anyone know why?
It's a <div> element not an <input>, so use text() instead of val() (and be sure to trim so it isn't enabled on whitespace). Also could use prop() to set the property instead of attr().
$('#title-create-partial').keyup(function(){
if ($.trim($(this).text()) === '') {
$('#create-entry').prop('disabled', true);
} else {
$('#create-entry').prop('disabled', false);
}
});
jsFiddle here.

Categories