jQuery: When entering text in input field, doesn't enable the button - javascript

I have a jsfiddle here.
jQuery
$(function() {
//var input = $('form :input[type="text"]')
$('form :input[type="text"]').live('keyup', function() {
$('form .create-playlist-button')
.attr('disabled', $('form :input[type="text"]').val().length == 0);
});
});
Needed
When I start entering the data in the textbox, create should be enabled.
When I remove all text from the textbox, create should be disabled.
I am very new to jQuery and this thing is not working for me.

$('form :input[type="text"]').live('keyup', function() {
var val = $.trim(this.value); // this.value is faster than $(this).val()
$('form .create-playlist-button').prop('disabled', val.length == 0);
});
DEMO
Here, I used .prop() instead of .attr(), according to jQuery doc .prop() should be use. I also used .trim() for removing the whitespace from the beginning and end of value.
About your code
In your code you used $('form :input[type="text"]') two times, one for bind event and one to getting the value of text field. But that is not necessary, because within keyup event handler function this will refers to that input element on which keyup event binded.
If you sometime need to use any selector multiple times for any purpose it will be better to cache that in a variable and reuse that variable. Just for example:
var input = $('form :input[type="text"]');
input.on('click', function() {
alert( this.value );
input.addClass('something');
});
If would be better if you use .on() instead of .live() for delegate event handler, because .live() has been deprecated.
You can use .on() like following:
$('form').on('keyup', ':input[type="text"]', function() {
var val = $.trim(this.value);
$('form .create-playlist-button').prop('disabled', val.length == 0);
});
Note
Syntax of .on() for delegate event handling is like:
$(staticContainer).on( eventName, target, handlerFunction )
Here, staticContainer point to an element which belong to DOM at page load, i.e which is not dynamic and also container of target on which you want to bind your event.
Just for some more go here
.prop() vs .attr()
http://forum.jquery.com/topic/whats-the-difference-between-jquery-attr-and-jquery-prop

Updated:
$(function(){
//var input = $('form :input[type="text"]')
$('form :input[type="text"]').live('keyup',function(){
$(this).closest('form').find('.create-playlist-button').prop('disabled',$(this).val().length==0);
});
});
In the "keyup" handler, you use this (or $(this) to use it via jQuery) to get at the text field that's actually involved. I also changed the code to ensure you'll find the correct "companion" button. It looks up the chain of parent elements to find the enclosing <form>, then finds the button inside that form.
The way you're assigning the event handlers is deprecated. It should be:
$('form').on('keyup', ':input[type="text"]', function(){ ...
Also if you checked for "keypress" instead of "keyup" you'd fix the bug wherein the button doesn't work until the second character.
edit — oh and one more thing: you should usually use .prop() to update attributes, not .attr(). It's a confusing thing about the newer jQuery API, but the times you need to use .attr are kind-of rare. Unfortunately, there's a ton of old instructional material out there that was written back before jQuery 1.6 was released.

You should use the .change() method !
And inside it juste do a test:
if ($(this).val().length > 0)
...
else
...

here ya go... using your original fiddle:
http://jsfiddle.net/9kKXX/4/

Only a small change is necessary.
$(function(){
//var input = $('form :input[type="text"]')
$('form :input[type="text"]').live('keyup',function(){
$('form .create-playlist-button').attr('disabled',$(this).val().length==0);
});
});
Fiddle: http://jsfiddle.net/9kKXX/36/

Related

How to undetect/ignore javascript events in a certain html element?

I have this line of code $('#tbl-purchase-list').on( 'keyup change', 'input[type="text"]' that detects the input of all input[type="text"] field. However, I have an input field that I dont want to be detected when inputting a text on the keyboard or make any changes on it.<input type="text" class="form-control purchase-freight-charge" id="purchase-freight-charge" value="" />. Is there a way in javascript that ignores certain events for a certain element? Something like this $("#purchase-freight-charge").ignoreEvents();? Please help. Thanks a lot.
Ofcourse there is a :not() Pseudo selector:
$('#tbl-purchase-list').on('keyup change',
'input[type="text"]:not(#purchase-freight-charge)',
...);
It will not add the target element in the matched set of selectors. So, there won't be any event for that element which is inside :not().
Event this can also be done:
$('#tbl-purchase-list').on('keyup change', 'input[type="text"]',function(ev){
if(this.id === "purchase-freight-charge"){
this.value = "";
}
});
You can use jQuery's event.stopImmediatePropagation():
$("#purchase-freight-charge").on('keyup change', function( event ) {
event.stopImmediatePropagation();
});
// Future event bindings won't be executed for #purchase-freight-charge
// ...

How can I return a href link to it's default behavior after using e.preventDefault();?

I updated my code and rephrased my question:
I am trying to create the following condition. When a link with an empty href attribute (for example href="") is clicked, a modal is launched and the default behavior of that link is prevented..
But when the href attribute contains a value (href="www.something.com") I would like for the link to work as it normally does using its default behavior.
For some reason my code isn't working. Any help is appreciated.
// Semicolon (;) to ensure closing of earlier scripting
// Encapsulation
// $ is assigned to jQuery
;(function($) {
// DOM Ready
$(function() {
// Binding a click event
// From jQuery v.1.7.0 use .on() instead of .bind()
$('.launch').bind('click', function(e) {
var attrId = $(this).attr('attrId');
if( $('.launch').attr('href') == '') {
// Prevents the default action to be triggered.
e.preventDefault();
// Triggering bPopup when click event is fired
$('div[attrId="' + attrId+'"]').bPopup({
//position: ['auto', 'auto'], //x, y
appendTo: 'body'
});
} else {
$(this).removeAttribute('attrId');
return true;
}
});
});
})(jQuery);
Your jQuery is... very wrong. $('href').attr('') is getting the empty attribute from an element <href>... Did you mean:
if( $(this).attr('href') == '')
A few things: event is undefined, as your event object is simply called e. Secondly, e.stopPropagation(); will not do what you want. stopPropagation simply prevents parent events from firing (eg: clicking a <td> will also fire click on the containing <tr> unless stopped).
Try just replacing your else statement with
return true;
Also your jQuery is incorrect (as stated in the other answer here).
This answer may help as well:
How to trigger an event after using event.preventDefault()
Good luck!

How can I show a DIV by it's attribute value using Jquery

I am working with a Jquery plugin and I would like to trigger the modal (div) by calling it's value instead of calling it's ID name.
So if the attribute value is "554" meaning attrId="554" I will display the modal with the matching "554" attribute. Please keep in mind that the attribute value could be a variable.
My JSFiddle Code Example is here
;(function($) {
// DOM Ready
$(function() {
// Binding a click event
// From jQuery v.1.7.0 use .on() instead of .bind()
$('#my-button').bind('click', function(e) {
// Prevents the default action to be triggered.
e.preventDefault();
// Triggering bPopup when click event is fired
$('#element_to_pop_up').bPopup();
});
});
})(jQuery);
Any help is appreciated. Thanks so much
You can use an attribute equals selector: [attribute="value"]
If your popup div has an attribute like this:
<div id="element_to_pop_up" attrId="554">
<a class="b-close">x</a>
Content of popup
</div>
You can use the following:
var x = '554';
$('div[attrId="' + x + '"]').bPopup();
jsfiddle
Ultimately it needs a unique selector unless you are okay with triggering multiple modals. One way to do it is to use the jQuery each function, and check each div for the matching attribute.
$( "div" ).each(function() {
var criteria = 'example_criteria';
if ($( this ).attr( "attributename" ) == criteria)
{
$(this).bPopup();
}
});

onkeypress textbox issue

I have this:
<input type="text" ID="txtMy" name="txtMy" onkeypress="initialize();"/>
And in my .js file I have:
initialize()
{
var x = $("#txtMy").val();
}
But, if I have '2' in my textbox, and then I enter 4, the value of x is still 2. How to resolve this?
Use keyup
Here is how you do that in the unobtrusive way.
HTML
<input type="text" id="txtMy" />
Script
$(function(){
$("#txtMy").keyup(function (event) {
alert($(this).val())
});
});
Working Sample : http://jsfiddle.net/VmELF/4/
If you want to bind the functionality to a text box which is being injected to the DOM after the dom load( possible by an Ajax call etc...), you may use jQuery on
$(function(){
$("body").on("keyup","#txtSearchKey",function (event) {
alert($(this).val())
});
});
Your spelling of initialize in the onkeypress does not match the declaration (inititalize).
keydown and keypress events both execute BEFORE the entered key has actually appeared in the text box. If you want to get the new value of the input after the key has appeared, use the keyup event instead.
<input type="text" ID="txtMy" name="txtMy" onkeyup="initialize();"/>
initialize()
{
var x = $("#txtMy").val();
}
You should consider binding your event handlers in javascript using .on(), since you're using the library anyways. Keeping your logic (javascript) seperated from your view (html) is a good habit to get in to.
instead of markup event handler you can use jquery:
var x;
$("#txtMy").on("keyup", function(){
x = $(this).val();
alert(x);
})
A few things:
Use the keyup event. keypress is firing before the character is recorded.
Your initialize() function is misspelled in your HTML snippet.
See the working jsfiddle at http://jsfiddle.net/8XTLW/1/

Disable/enable an input with jQuery?

$input.disabled = true;
or
$input.disabled = "disabled";
Which is the standard way? And, conversely, how do you enable a disabled input?
jQuery 1.6+
To change the disabled property you should use the .prop() function.
$("input").prop('disabled', true);
$("input").prop('disabled', false);
jQuery 1.5 and below
The .prop() function doesn't exist, but .attr() does similar:
Set the disabled attribute.
$("input").attr('disabled','disabled');
To enable again, the proper method is to use .removeAttr()
$("input").removeAttr('disabled');
In any version of jQuery
You can always rely on the actual DOM object and is probably a little faster than the other two options if you are only dealing with one element:
// assuming an event handler thus 'this'
this.disabled = true;
The advantage to using the .prop() or .attr() methods is that you can set the property for a bunch of selected items.
Note: In 1.6 there is a .removeProp() method that sounds a lot like removeAttr(), but it SHOULD NOT BE USED on native properties like 'disabled' Excerpt from the documentation:
Note: Do not use this method to remove native properties such as checked, disabled, or selected. This will remove the property completely and, once removed, cannot be added again to element. Use .prop() to set these properties to false instead.
In fact, I doubt there are many legitimate uses for this method, boolean props are done in such a way that you should set them to false instead of "removing" them like their "attribute" counterparts in 1.5
Just for the sake of new conventions && making it adaptable going forward (unless things change drastically with ECMA6(????):
$(document).on('event_name', '#your_id', function() {
$(this).removeAttr('disabled');
});
and
$(document).off('event_name', '#your_id', function() {
$(this).attr('disabled','disabled');
});
// Disable #x
$( "#x" ).prop( "disabled", true );
// Enable #x
$( "#x" ).prop( "disabled", false );
Sometimes you need to disable/enable the form element like input or textarea. Jquery helps you to easily make this with setting disabled attribute to "disabled".
For e.g.:
//To disable
$('.someElement').attr('disabled', 'disabled');
To enable disabled element you need to remove "disabled" attribute from this element or empty it's string. For e.g:
//To enable
$('.someElement').removeAttr('disabled');
// OR you can set attr to ""
$('.someElement').attr('disabled', '');
reference: http://garmoncheg.blogspot.fr/2011/07/how-to-disableenable-element-with.html
$("input")[0].disabled = true;
or
$("input")[0].disabled = false;
There are many ways using them you can enable/disable any element :
Approach 1
$("#txtName").attr("disabled", true);
Approach 2
$("#txtName").attr("disabled", "disabled");
If you are using jQuery 1.7 or higher version then use prop(), instead of attr().
$("#txtName").prop("disabled", "disabled");
If you wish to enable any element then you just have to do opposite of what you did to make it disable. However jQuery provides another way to remove any attribute.
Approach 1
$("#txtName").attr("disabled", false);
Approach 2
$("#txtName").attr("disabled", "");
Approach 3
$("#txtName").removeAttr("disabled");
Again, if you are using jQuery 1.7 or higher version then use prop(), instead of attr(). That's is. This is how you enable or disable any element using jQuery.
Use like this,
$( "#id" ).prop( "disabled", true );
$( "#id" ).prop( "disabled", false );
You can put this somewhere global in your code:
$.prototype.enable = function () {
$.each(this, function (index, el) {
$(el).removeAttr('disabled');
});
}
$.prototype.disable = function () {
$.each(this, function (index, el) {
$(el).attr('disabled', 'disabled');
});
}
And then you can write stuff like:
$(".myInputs").enable();
$("#otherInput").disable();
If you just want to invert the current state (like a toggle button behaviour):
$("input").prop('disabled', ! $("input").prop('disabled') );
this works for me
$("#values:input").attr("disabled",true);
$("#values:input").attr("disabled",false);
Update for 2018:
Now there's no need for jQuery and it's been a while since document.querySelector or document.querySelectorAll (for multiple elements) do almost exactly same job as $, plus more explicit ones getElementById, getElementsByClassName, getElementsByTagName
Disabling one field of "input-checkbox" class
document.querySelector('.input-checkbox').disabled = true;
or multiple elements
document.querySelectorAll('.input-checkbox').forEach(el => el.disabled = true);
You can use the jQuery prop() method to disable or enable form element or control dynamically using jQuery. The prop() method require jQuery 1.6 and above.
Example:
<script type="text/javascript">
$(document).ready(function(){
$('form input[type="submit"]').prop("disabled", true);
$(".agree").click(function(){
if($(this).prop("checked") == true){
$('form input[type="submit"]').prop("disabled", false);
}
else if($(this).prop("checked") == false){
$('form input[type="submit"]').prop("disabled", true);
}
});
});
</script>
An alternate way to disable the input field is by using jQuery and css like this:
jQuery("#inputFieldId").css({"pointer-events":"none"})
and to enable the same input the code is as follows:
jQuery("#inputFieldId").css({"pointer-events":""})
Disable:
$('input').attr('readonly', true); // Disable it.
$('input').addClass('text-muted'); // Gray it out with bootstrap.
Enable:
$('input').attr('readonly', false); // Enable it.
$('input').removeClass('text-muted'); // Back to normal color with bootstrap.
Disable true for input type :
In case of a specific input type (Ex. Text type input)
$("input[type=text]").attr('disabled', true);
For all type of input type
$("input").attr('disabled', true);
<html>
<body>
Name: <input type="text" id="myText">
<button onclick="disable()">Disable Text field</button>
<button onclick="enable()">Enable Text field</button>
<script>
function disable() {
document.getElementById("myText").disabled = true;
}
function enable() {
document.getElementById("myText").disabled = false;
}
</script>
</body>
</html>
I used #gnarf answer and added it as function
$.fn.disabled = function (isDisabled) {
if (isDisabled) {
this.attr('disabled', 'disabled');
} else {
this.removeAttr('disabled');
}
};
Then use like this
$('#myElement').disable(true);
2018, without JQuery (ES6)
Disable all input:
[...document.querySelectorAll('input')].map(e => e.disabled = true);
Disable input with id="my-input"
document.getElementById('my-input').disabled = true;
The question is with JQuery, it's just FYI.
Approach 4 (this is extension of wild coder answer)
txtName.disabled=1 // 0 for enable
<input id="txtName">
In jQuery Mobile:
For disable
$('#someselectElement').selectmenu().selectmenu('disable').selectmenu('refresh', true);
$('#someTextElement').textinput().textinput('disable');
For enable
$('#someselectElement').selectmenu().selectmenu('enable').selectmenu('refresh', true);
$('#someTextElement').textinput('enable');

Categories

Resources