Enable/disable button on contentEditable keyup - javascript

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.

Related

Check if a div is disabled jQuery

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>

$('form:not(.some-class)').keydown is still applying keydown event to .some-class

JQuery's ':not' selector is not preventing the intended-to-be-excluded class (which decorates an element) from firing the .keydown event. Why?
From the following code, when I press a key in the .newOwnerEntryInput field, I expect to see the alert for '1' only. But I see both alerts '1' and '2'.
Javascript:
$('.newOwnerEntryInput').keydown(function (event) {
alert('1');
});
// Prevent Enter from submitting form.
$('form:not(.newOwnerEntryInput)').keydown(function (event) {
alert('2');
});
HTML:
<li style="position: relative">
#Html.DropDownList("cftMemberID", null, String.Empty, new { #class = "actionOwnerDropDown hidden" })
<div class="newOwnerEntryDiv">
<input class="newOwnerEntryInput" />
<div class="float-right closeNewOwner">
<img src="~/Images/cancel_x.png" alt="close" />
</div>
</div>
</li>
I have tried a variety of quotes styles, with and without surrounding the excluded class with quotes, as well as adding 'input' after the class, as in $('form:not(.newOwnerEntryInput input)').keydown
Thanks!
Thanks for those who helped. I do need the form to fire for ALL types of input fields, not just those of type input. So that was out.
Here is what solved my problem:
$('form').keydown(function (event) {
if (! event.which.hasClass('.newOwnerEntryInput')) {
alert('2');
}
});
In this case, for my input of class .newOwnerEntryInput, if a key is pressed, it will NOT fire the event and push '2' out to the alert screen.
Again, thanks, it took a couple responses, all of which had a piece of the solution, for me to answer this myself. :)
Try this:
HTML:
<div>
<input class="newOwnerEntryInput" type="text"/><br />
<!-- I know you have MVC dropdown list, but I replaced it with a html textbox (for simple testing) -->
<input class="newOwnerEntryInput1" type="text"/>
</div>
JavaScript:
$('input.newOwnerEntryInput').keydown(function (e) {
alert('1');
});
$('input:not(.newOwnerEntryInput)').keydown(function (e) {
alert('2');
});
I checked with the documentation that in their example, I saw they had the element input followed by the function with the selector.
The documentation is available is here: jQuery :not()
I hope this helps!
Cheers!
Try this :
$('form input:not(.newOwnerEntryInput)').on('keydown',function (event)
{
alert('2');
});
http://jsfiddle.net/rzseLj27/

hide and show the div depending on the button using jquery

i need to hide and shoe the div depending on the button using html and jquert
is the button name=show status i click the button change to the name=hide and display the div, the same function in reverse also
You could do something like this (Note the custom display attribute):
$("#btn").click(function() {
var item = $("input[name=yourInput]");
if (item.attr("display")) {
item.show();
item.attr("display", false);
} else {
item.hide();
item.attr("display", true);
}
});
<input name="yourInput" display="true" />
http://jsfiddle.net/Jrz5Y/1/
You can create a boolean variable set to a default value, and change it to it's inverse value whenever you click on the button.
depending on the state of the boolean you can execute the correct path in your method
you can use this
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
function ShowHide()
{
if ($("#divdata").css('display') == 'none'){
$("#divdata").show();
$("#btnClick").val("Hide");
}
else{
$("#divdata").hide();
$("#btnClick").val("Show Status");
}
}
</script>
your div will be like this.
<div id="divdata" style="display:none">
I have to show and hide this div.
</div>
Button will be like this.
<input id="btnClick" type="button" value="Show Status" onclick="ShowHide()" />
I hope It will work.

How to make box appear when text is entered into input?

I have this HTML code:
<div class="center1">
<form>
<input type="text" class="input1" autofocus="focus" />
</form>
</div>
<br><br>
<div class="center1">
<div class="box"></div>
</div>
I have added it to this JSFiddle link: http://jsfiddle.net/PDnnK/4/
As you can see there is:
INPUT FIELD
&
BOX
I want the box to appear only when text is typed in the input. How is this done?
Start the box out with display: none. Then, you can capture the keypress event for the input:
document.getElementById('myInput').onkeypress = function () {
document.getElementById('myBox').style.display = 'block';
}
Something like this with jQuery:
$("#id-of-input").change(function() { $("#id-of-box"}.css('display', 'block'); } );
or change .change to .click
Binding to "change" is usually not super-handy, since it usually doesn't fire until you tab or click away from the element.
However, polling isn't the answer either.
original answer:
http://jsfiddle.net/xNEZH/2/
super-fantastic new answer:
http://jsfiddle.net/4MhKU/1/
$('.input1').bind('mouseup keyup change cut paste', function(){
setTimeout(function(){
var hasInput = $('.input1').val() != "";
$('.box')[hasInput ? 'show' : 'hide']();
}, 20);
});
The setTimeout is because cut and paste events fire BEFORE the text is cut or pasted.

Javascript OnMouseOver and Out disable/re-enable item problem

I wanted to have some radio buttons that disabled when the mouse went over and enabled again when it went out (just for fun).
<form>
<input type="radio" name="rigged" onMouseOver="this.disabled=true" onMouseOut="this.disabled=false">
</form>
When the mouse goes on it it does what it should be when it goes back off the button wont re-enable. Also, how do I make it default to enable so that when you refresh the page it doesn't stay disabled.
Thanks in advance.
You could achieve the same effect by wrapping your radio buttons in a div tag and setting the onmouseover and onmouseout events.
<div id="container" onmouseout="this.disabled=false" onmouseover="this.disabled=true">
<input name="rigged" type="radio">
</div>
The above solution only works in IE, for a solution that works in FireFox do the following.
<script type="text/javascript">
function toggleDisabled(el) {
try {
el.disabled = el.disabled ? false : true;
}
catch(E){
}
if (el.childNodes && el.childNodes.length > 0) {
for (var x = 0; x < el.childNodes.length; x++) {
toggleDisabled(el.childNodes[x]);
}
}
}
</script>
*This javaScript function was borrowed from here: Enable or disable DIV tag and its inner controls using Javascript
<div id="container" onmouseover="toggleDisabled(this)" onmouseout="toggleDisabled(this)">
<input name="rigged" type="radio">
</div>
The inputs do not fire the mouseout events because they are disabled.
So you have to wrap it in a div and catch the div's events.
If you want pure javascript, use Phaedrus's example "toggleDisabled" script.
If you want jQuery and not-so-newbie friendly:
<html>
<head>
<title>Page</title>
<script src="jquery-1.3.2.min.js"></script>
<script>
$(function() {
function toggleDisabled(d) {
var disable = d;
this.disableChildren = function() { $(this).children().each(function() { this.disabled = d; }); }
}
$("form .radios").hover(new toggleDisabled(true).disableChildren, new toggleDisabled(false).disableChildren);
});
</script>
</head>
<body>
<form>
<div class="radios">
<input type="radio" name="rigged" value="1"/> Item One<br />
<input type="radio" name="rigged" value="2"/> Item Two<br />
<input type="radio" name="rigged" value="3"/> Item Three<br />
<input type="radio" name="rigged" value="4"/> Item Four
</div>
</form>
</body>
</html>
I had a similar problem with wanting an image to expose, and then go regular when the mouse left the image. I was using jQuery and ended up hooking into mouseenter and mouseout, instead of the events you are using. You might want to try those.
$('#rigged').mouseenter(function() {
$(this).disabled = true;
}).mouseout(function() {
$(this).disabled = false;
});
Something like that.
Again, that's using jQuery.
(You'll have to give the input radio button the id 'rigged')
I think when it's becoming disabled, it's not going to fire any events.
You could try a few things.
On mouseover, make an invisible div overlay the radio box. This will make it impossible to use. Then on the mouseout of this invisible div, remove the div.
You could play with mouse x and y coords, and see if they overlay your radio elements. This isn't an optimal solution though.
Markup for the first, in jQuery, would go something like this
$('#rigged').after('<div id="overlay" style="display: none;"></div>'); // make this the size of the radio button and/or associated label (if present). also, maybe with absolute and relative positioning, make sure it will overlap the radio element
$('#rigged').bind('mouseover', function() {
$('#overlay').show();
});
$('#overlay').live('mouseout', function() {
$(this).hide();
});
You'll need to adapt this to work with multiple elements.

Categories