How to disable all elements within a div using jquery - javascript

I have a div and when a checkbox is clicked I want to disable all the elements inside the div, including disabling the onClick of one of the elements. Here is the codepen: https://codepen.io/anon/pen/JVwMOq
HTML:
<input type="checkbox" onChange="checkMe(this)">
<div id="test">
<input type="text">
<span class="test">
<img id="like" src="https://cdn4.iconfinder.com/data/icons/game-interface-outline/100/objects-15-512.png" height="40px" onclick="likeMe()">
</span>
</div>
JS:
function checkMe(element){
if($(element).prop('checked') === true){
$('#test').prop('disabled', true).off("click");
}
else{
$('#test').prop('disabled', false).on("click");
}
}
Any advice? Thanks!

You can use this, disabled with CSS.
you can't add disabled on div, it's working with input, etc..
$('#clickCheckbox').change(function() {
if($(this).is(":checked")) {
$('#test').addClass('disable-button');
}else{
$('#test').removeClass('disable-button')
}
$('#clickCheckbox').val($(this).is(':checked'));
});
.disable-button {
pointer-events: none;
cursor: not-allowed;
text-decoration: none;
color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="clickCheckbox">
<div id="test">
<input type="text">
<span class="test">
<img id="like" src="https://cdn4.iconfinder.com/data/icons/game-interface-outline/100/objects-15-512.png" height="40px" onclick="likeMe()">
</span>
</div>

I have a working solution below.
I have added in an additional input field to check it works on multiple items.
I created an checking function to see if your item is checked.
const isChecked = (element) => document.getElementById(element.id).checked ? true : false
Then updated the likeMe function to pass in the current id and returned null if the checkbox is checked.
function likeMe(element) {
if (isChecked(element)) {
return null
} else {
console.log('Calling likeMe()');
}
}
Then I updated your checkMe function to pass in the current element and the targetdiv so this would be more reusable across other parts of your code.
function checkMe(element, targetDiv) {
const targetDivInput = `#${targetDiv} input`
const targetDivClassName = `.${targetDiv}`
if (isChecked(element)) {
$(targetDivInput).prop('disabled', true);
$(targetDivClassName).toggleClass('disabled')
} else {
$(targetDivInput).prop('disabled', false);
$(targetDivClassName).toggleClass('disabled')
}
}
Then made some small changes to the markup to pass in the ids into your functions
<div id="test">
<input type="text">
<input type="text">
<span class="test">
<img id="like" src="https://cdn4.iconfinder.com/data/icons/game-interface-outline/100/objects-15-512.png" height="40px" onclick="likeMe('test')">
</span>
</div>
and added a disabled state to your css so the user wouldn't see the cursor.
#like{
cursor: pointer;
}
.disabled #like {
cursor: inherit;
}
This is the final result.
#like{
cursor: pointer;
}
.disabled #like {
cursor: inherit;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
const isChecked = (element) => document.getElementById(element.id).checked ? true : false
function likeMe(element) {
if (isChecked(element)) {
return null
} else {
console.log('Calling likeMe()');
}
}
function checkMe(element, targetDiv) {
const targetDivInput = `#${targetDiv} input`
const targetDivClassName = `.${targetDiv}`
if (isChecked(element)) {
$(targetDivInput).prop('disabled', true);
$(targetDivClassName).toggleClass('disabled')
} else {
$(targetDivInput).prop('disabled', false);
$(targetDivClassName).toggleClass('disabled')
}
}
</script>
<input id="textCheck" type="checkbox" onChange="checkMe(this,'test')">
<div id="test">
<input type="text">
<input type="text">
<span class="test">
<img id="like" src="https://cdn4.iconfinder.com/data/icons/game-interface-outline/100/objects-15-512.png" height="40px" onclick="likeMe('test')">
</span>
</div>

Related

Making a button that shows a hidden image on click

I've found tutorials that make an image hidden with some css, javascript and html but I'm having trouble making the image hidden first, and then having the button be able to make it visible and then hidden if pressed again.
edit: hopefully this code should help! Again, sorry I can't figure some of this out, I don't really know how this site works and I'm pretty new to coding,,,,
edit 2: I added where the function is being called. It's suppose to be a multiple choice that shows an image when correct!
<style>
div.notdropdown {
margin-top: 100px;
margin-bottom: 100px;
border: 1px solid black;
background-color: rgb(181, 204, 180, 0.9);
}
.hide{
display:none;
}
</style>
</body>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
<div id="myDIV">
<img class= "hide" src="https://www.merriam-webster.com/assets/mw/static/art/dict/frig_bi.gif">
<br>
<a class= "hide" href="https://www.merriam-webster.com/dictionary/frigate%20bird">https://www.merriam-webster.com/dictionary/frigate%20bird </a>
<br>
</div>
<h1>What is a Frigate?</h1><br>
<form >
<input type="radio" name="choice" value="Bird"> A type of Bird
<input type="radio" name="choice" value="Mangrove"> A type of Mangrove tree
<input type="radio" name="choice" value="Sea Creature"> A type of Sea Creature
<input type="radio" name="choice" value="None"> None of These
</form>
<button onclick="submitAnswer();"> Submit Answer</button>
</body>
<script>
function submitAnswer() {
var radios = document.getElementsByName("choice");
var i = 0, len = radios.length;
var checked = false;
var userAnswer;
for( ; i < len; i++ ) {
if(radios[i].checked) {
checked = true;
userAnswer = radios[i].value;
}
}
if(!checked) {
alert("please select choice answer");
return;
}
// Correct answer
if(userAnswer === "Bird") {
myFunction();
alert("Answer is correct!");
}
// incorrect answer
else {
alert("Answer is wrong!");
}
}
</script>
</body>
</html>
in fact it's very simple, just use the toggle method, which allows you to easily enable and disable a class in an element
function toggleImage(){
document.querySelector('#image').classList.toggle('hidden');
}
.hidden{
display: none;
}
.w-100{
width: 100%;
}
.mb-10{
margin-bottom: 10px;
}
<button onClick="toggleImage()" class="w-100 mb-10">Show/Hide</button>
<img src="https://images.pexels.com/photos/462118/pexels-photo-462118.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" id="image" class="hidden w-100"/>
to work with a link to just change the tag to a and use href="#"
function toggleImage(){
document.querySelector('#image').classList.toggle('hidden');
}
.hidden{
display: none;
}
.w-100{
width: 100%;
}
.mb-10{
margin-bottom: 10px;
}
<a onClick="toggleImage()" class="w-100 mb-10" href="#">Show/Hide</a>
<img src="https://images.pexels.com/photos/462118/pexels-photo-462118.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" id="image" class="hidden w-100"/>
You just need to call your function on button tag. Add a button in your html file on which you want your div to toggle. As you are using function name myFunction, call it on that function using
onClick="myFunction()"
And your code should work fine. Don't need to add any new class or even hide your div by default.
check this code. I think this will help you.
<button id = "showhide" onclick = "showhide()">Show Hide Image</button>
<div id = "image" style="width: 100px; height : 100px;">
<h4> Image Code </h4>
</div>
<script>
$('#showhide').on('click', function(e){
$("#image").toggle();
});
</script>

change background image of a div when checkbox is checked

I hide the default checkbox and use a div with custom checkbox image instead:
<aui:form>
<c:if
test="<%=company.isAutoLogin() && !PropsValues.SESSION_DISABLED%>">
<div class="rememberImage ftr" id="rememberImg">
<aui:input checked="<%=rememberMe%>" name="rememberMe" id="rememberMe"
type="checkbox" cssClass="remember"/>
</div>
</c:if>
</form>
//omiited
<aui:script use="aui-base">
function changeBG() {
if (this.checked) {
document.getElementById('rememberImg').style.backgroundImage = 'url(../img/chk_none.png)';
} else {
document.getElementById('rememberImg').style.backgroundImage = 'url(../img/chk_check.png)';
}
}
document.getElementById('_58_rememberMe').addEventListener('change', changeBG);
var password = A.one('#<portlet:namespace />password');
if (password) {
password.on(
'keypress',
function(event) {
Liferay.Util.showCapsLock(event, '<portlet:namespace />passwordCapsLockSpan');
}
);
}
</aui:script>
This does not work at all. Any suggestions?? Much appreciated!
UPDATE: add more lines of code that I think maybe have problems
I saw a proper answer already above, but to avoid intruding HTML tags with JS listeners, what considered as not the best practice, I will offer you this solution...
function changeBG() {
if (this.checked) {
document.getElementById('myElement').style.backgroundImage = 'url(.....)';
} else {
document.getElementById('myElement').style.backgroundImage = 'url(.....)';
}
}
document.getElementById('myInput').addEventListener('change', changeBG);
Hope it will help you :)
You can do it like this: Add an onclick attribute to the checkbox that triggers a toggle function. As I cant test it with your code (missing the rest) I can only provide you an enxample where the body background gets changed
<input id="check" type="checkbox" onclick="toggle();"> Click me
<script>
function toggle() {
if( document.getElementById("check").checked ) {
document.getElementsByTagName("body")[0].style.backgroundColor="red";
}
}
</script>
div{
margin: 20px 0;
}
input[type=checkbox] {
display: none
}
input[type=checkbox]+label {
background: url(http://s17.postimg.org/phsoii5vf/check.png) no-repeat;
padding-left: 30px;
padding-bottom: 5px;
padding-top: 2.5px;
height: 18px;
}
input[type=checkbox]:checked+label {
background: url(http://s2.postimg.org/zbjg138np/check_tick.jpg) no-repeat;
}
<div>
<input type="checkbox" id="chk1">
<label for="chk1">Custom Checkbox1</label>
</div>
<div>
<input type="checkbox" id="chk2">
<label for="chk2">Custom Checkbox2</label>
</div>
<div>
<input type="checkbox" id="chk3">
<label for="chk3">Custom Checkbox3</label>
</div>
<div>
<input type="checkbox" id="chk4">
<label for="chk4">Custom Checkbox4</label>
</div>
not required javascript.you can do it from css.
<div>
<input type="checkbox" id="chk">
<label for="chk">Custom Checkbox1</label>
</div>
input[type=checkbox] {
display: none
}
input[type=checkbox]+label {
background: url(../images/check.png) no-repeat;
padding-left: 30px;
padding-bottom: 5px;
padding-top: 2.5px;
height: 18px;
}
input[type=checkbox]:checked+label {
background: url(../images/check_tick.png) no-repeat;
}
you can try this one:
document.getElementById('rememberImage').style.background = 'url(../img/chk_check.png)';
function SetBackground(elm){
if($(elm).is(":checked"))
{
$("#rememberImage").css({"background-color":"gray"});
}
else
{
$("#rememberImage").css({"background-color":"white"});
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="rememberImage ftr" id="rememberImage">
<input checked="<%=rememberMe%>" name="rememberMe" id="rememberMe" type="checkbox" onchange="SetBackground(this)"/>
</div>
I don't know how your custom checkbox works but, you can add onchange event and check if checkbox is checked then change the background of div.
Best regards

how can i select item in a form, change the background and submit

I am trying to select one of the Item element, then change the background color to blue when selected (disable any other item from changing background color i.e. only one element can be selected) and then submit the form. I would only like to submit when one of the item is selected else alert.
$(document).ready(function(){
$('form').on('click', 'div', function(e) {
e.preventDefault();
$('#done').attr('disabled','disabled');
$('input').removeClass('bluebg');
$('div').removeClass('bluebg');
$(this).addClass('bluebg');
});
$('#ok').click(function() {
if($('div').hasClass('bluebg'))
{
document.location.href='page.aspx';
}
else { alert('Item is not selected');}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<div id="item1">Item1</div>
<div id="item2">Item2</div>
<div id="item3">Item3</div>
<input type="button" value="OK" id="ok" />
</form>
Here's how output should look:
In order to run your example, I downloaded the jquery version that I am showing in the head and basically I applied 3 things:
1) Keep the id of the selected item with the variable selectedId.
2) Change your button input for a submit input and add the image with CSS.
3) Add a hidden input to store your selection.
<html>
<head>
<script src="js/jquery-1.11.3.min.js"></script>
<style type="text/css">
.bluebg {
background-color: blue;
}
.ok-button {
/* Change this for your image location */
background: url(OK.gif);
/* Adjust according to your image */
width: 20px;
height: 20px;
}
</style>
<script>
var selectedId = null;
$(document).ready(function() {
$('form').on('click', 'div', function(e) {
e.preventDefault();
$(this).addClass('bluebg');
if (selectedId != null) {
$('#' + selectedId).removeClass('bluebg');
}
selectedId = $(this).attr('id');
$('#myItem').val(selectedId);
});
$('#myForm').submit(function() {
if (selectedId != null) {
return true;
}
alert('Item is not selected');
return false
});
});
</script>
</head>
<body>
<form id="myForm" action="page.aspx" method="POST">
<div id="item1">Item1</div>
<div id="item2">Item2</div>
<div id="item3">Item3</div>
<input id="myItem" name="myItem" type="hidden" />
<input type="submit" class="ok-button" value="" />
</form>
</body>
your code works:
EDIT: my suggestion is to add an identifier to your form, and use more specific selectors, because with $('div').removeClass('bluebg'); you're removing the class from all of your divs inside the page.
$(document).ready(function(){
$('#myform').on('click', 'div', function(e){
e.preventDefault();
$('#done').attr('disabled','disabled');
$('#myform input').removeClass('bluebg');
$('#myform div').removeClass('bluebg');
$(this).addClass('bluebg');
});
$('#ok').click(function(){
if($('#myform div').hasClass('bluebg'))
{
document.location.href='page.aspx';
}
else { alert('Item is not selected');}
});
});
form div {
padding:10px 0;
}
.bluebg {
background:blue
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform">
<div id="item1">Item1</div>
<div id="item2">Item2</div>
<div id="item3">Item3</div>
<input type="image" src="OK.gif" id="ok" />
<form>

onClick Div checked unchecked checkbox

I have multiple Divs based rows. Each row contains a check box.
I want to click on that row anywhere, it should check uncheck that specific checkbox.
Here is the what I tried till now DEMO: http://jsfiddle.net/kERYB/19/
JS :
$('.row').click(function ()
{
$(this).closest(":checkbox").attr("checked", checked");
});
HTML:
<div class="row">
<div class="left">
<input type="checkbox" class="cb-element" value="1" />
</div>
<div class="left">
<select><option>choose</option></select>
</div>
<div class="right">
This is First Record
</div>
<div class="clear"></div>
</div>
<div class="row">
<div class="left">
<input type="checkbox" class="cb-element" value="1" />
</div>
<div class="left">
<select><option>choose</option></select>
</div>
<div class="right">
This is Second Record
</div>
<div class="clear"></div>
</div>
<div class="row">
<div class="left">
<input type="checkbox" class="cb-element" value="1" />
</div>
<div class="left">
<select><option>choose</option></select>
</div>
<div class="right">
This is Third Record
</div>
<div class="clear"></div>
</div>
CSS:
.row {
width:300px;
padding:4px;
border:1px solid #000;
margin:2px;
}
.left {
float:left;
width:50px;
}
.right {
float:right;
}
.clear {
clear:both;
}
}
You can do this without if condition.
Working Demo
Jquery
$('.row').click(function ()
{
$(this).find('input[type=checkbox]').prop("checked", !$(this).find('input[type=checkbox]').prop("checked"));
});
Update (with variable) See Demo
jQuery
$('.row').click(function ()
{
var checkbox = $(this).find('input[type=checkbox]');
checkbox.prop("checked", !checkbox.prop("checked"));
});
Update 2: Fixed Bug on Cliking input See Demo
$('input[type=checkbox]').click(function (e)
{
e.stopPropagation();
return true;
});
Update 3: Without jQuery See Demo
Wrap the row with label
<label>
<div class="row">
...
</div>
</label>
Update 4: To exclude select tag See Demo
$('input[type=checkbox], .row select').click(function (e)
{
e.stopPropagation();
return true;
});
Try with this one :
$('.row').click(function ()
{
$(this).find('div:first input:checkbox').prop('checked', true)
}
);
Try in fiddle
Updated:
$('.row').click(function ()
{
if($(this).find('div:first input:checkbox').is(':checked')){
$(this).find('div:first input:checkbox').prop('checked', false)
}
else{
$(this).find('div:first input:checkbox').prop('checked', true)
}
});
Try in fiddle
You can do it simply with HTML.
<input type="checkbox" class="cb-element" id="my-checkbox" value="1" />
<label for="my-checkbox">here you click to check or uncheck.</label>
id of 'input' should be value of 'for' attribute of 'label' tag.
Here checkbox id is 'my-checkbox' and in label --for="my-checkbox")--.
You can see an example: http://jsfiddle.net/kERYB/21/
You can use .find for this.
$(this).find('input[type=checkbox]').prop("checked", true);
http://api.jquery.com/find/
To check uncheck, use this -
$('.row').click(function ()
{
var cb = $(this).find(':checkbox');
if (cb.is(':checked')) {
cb.prop('checked', false);
} else {
cb.prop('checked', true);
}
});
Update Fiddle - http://jsfiddle.net/kERYB/14/
$(document).ready(function (){
$('.row').click(function (e){
var cur = $(this).find('input[type=checkbox]');
if(cur.prop("checked"))
{
$(this).find('input[type=checkbox]').prop("checked", false);
}
else
{
$(this).find('input[type=checkbox]').prop("checked", true);
}
});
});
this will be good for you....
$('.row').click(function ()
{
if ( $(this).find(".cb-element").prop('checked') == true){
$(this).find(".cb-element").prop('checked', false);
}
else{
$(this).find(".cb-element").prop('checked', true);
}
});
http://jsfiddle.net/kERYB/13/

Jquery Div hide

I have a div tag which includes input controls. This div is opened when the user clicks on a menu item. I want to hide this tag when the click is outside that div area.
Currently I am able to hide the div when clicking outside it, but my div hides when I click any of the input controls that are in the div. How can I solve this?
My code is:
$(document).click(function (e) {
var elem = $(e.target).attr('id');
console.log(e.target);
if (elem !== 'btnLogin') {
// if (elem != 'TxtUserName' && elem != 'TxtPassword')
HideLoginDetails();
}
if (elem !== 'hpUseFul') {
// if(elem !== 'y')
}
});
Demo: http://jsfiddle.net/3fbpA/
var aboveDiv = false;
$('#yourDiv').click(function () {
aboveDiv = true;
});
$(document).click(function () {
if (!aboveDiv) $('#yourDiv').hide();
aboveDiv = false;
});
jQuery(document).ready(function()
{
$('the div you want').hover(function(){
mouse_inside=true;
}, function(){
mouse_inside=false;
});
$("body").mouseup(function(){
if(! mouse_inside) $('the div you want').hide();
});
});
Also check "Use jQuery to hide a DIV when the user clicks outside of it".
I have done complete bins for above issue. you can check demo link here...
Demo http://codebins.com/bin/4ldqp71
HTML
<div id="loginDialog">
<div class="field">
<label>
User Name:
</label>
<span class="input">
<input type="text" value="" id="txtuser" size="15"/>
</span>
</div>
<div class="field">
<label>
Password:
</label>
<span class="input">
<input type="password" value="" id="txtpassword" size="15"/>
</span>
</div>
<div class="field">
<input type="button" id="btn_ok" value="Login" />
</div>
</div>
<div>
<a href="javascript:void(0);" id="btnLogin">
Login
</a>
<a href="javascript:void(0);" id="btnMenu1">
Menu1
</a>
<a href="javascript:void(0);" id="btnMenu2">
Menu2
</a>
</div>
JQuery
$(function() {
$("#btnLogin").click(function() {
$("#loginDialog").show(500);
});
$(document).click(function(e) {
e.preventDefault();
var elem = $(e.target).attr('id');
if ($(e.target).parents("#loginDialog").length) {
$("#loginDialog").show();
} else {
if ($(e.target).attr('id') !== "btnLogin") {
$("#loginDialog").hide(300);
}
}
});
});
CSS
#loginDialog{
border:1px solid #333;
padding:4px;
background:#2A2A2A;
width:250px;
color:#dfdfdf;
display:none;
}
#loginDialog input{
border:1px solid #efefef;
}
#loginDialog input[type=button]{
background:#ababab;
}
#loginDialog input[type=button]:hover{
background:#cfcfcf;
}
#loginDialog .field{
text-align:center;
margin-bottom:5px;
}
#loginDialog label{
display:inline-block;
width:100px;
}
a{
display:inline-block;
margin-left:8px;
}
Demo http://codebins.com/bin/4ldqp71

Categories