How to unable button if textbox suddenly have values - javascript

Can anyone help me how to make my button disable if my texbox suddenly filled with text without clicking the textbox to input something.
My problem is my code wont work. Does anyone know how to do it.
<form method="post">
<input type="text" name="name1" id="name1" class="number" />
<input type="text" name="name2" id="name2" class="number" />
<input type="submit" name="send" id="send" class="hey" value="one" disabled />
</form>
script code:
<script>
$(document).ready(function () {
$('.number').blur(function () {
if ($.trim(this.value) == "") {
$('#send').attr("disabled", true);
}
else {
$('#send').removeAttr("disabled");
}
});
});
</script>

You can use combination of input, blur and keyup events to be safe:
$('.number').on('keyup blur input', function () {
$('#send').prop("disabled", !$.trim(this.value));
});
Demo: http://jsfiddle.net/pb9vw/

$('.number').keyup(function () {
if ($.trim(this.value) == "") {
$('#send').addAttr('disabled');
}
else {
$('#send').removeAttr('disabled');
}
});

Use keyup instead of blur and prop() instead of attr() The blur is triggered when input gets or loose focus. The prop should be use for boolean attributes like checked disabled etc.
Live Demo
$('.number').keyup(function () {
if ($.trim(this.value) == "") {
$('#send').prop("disabled", true);
}
else {
$('#send').prop("disabled", false);
}
});
As of jQuery 1.6, the .attr() method returns undefined for attributes
that have not been set. To retrieve and change DOM properties such as
the checked, selected, or disabled state of form elements, use the
.prop() method, reference.

If you want to make sure the button is only enable when the two textbox are filled, then you can do:
function doCheck() {
var allFilled = true;
$('input[type=text]').each(function () {
if ($(this).val() == '') {
allFilled = false;
return false;
}
});
$('input[type=submit]').prop('disabled', !allFilled);
}
$(document).ready(function () {
$('input[type=text]').keyup(doCheck);
});
Fiddle Demo

Related

What event is used when the input value is not blank

I need to enable/disable a button based on a input field. If the input field has a value, the button should be enabled. If the input field is empty, the button should be disabled. Now when the user selects a value from the input field cookie, How do I capture? I tried with "change" but it didn't work.
The tried the below code with "change" event:
<script>
$(function() {
$("#myInput").change(showSaveBtn);
var showSaveBtn = function() {
validateInput();
if (myInputEntered== true) {
$('#save').removeClass("disabled").prop(
'disabled', "disabled").removeAttr("disabled");
} else {
$('#save').addClass("disabled").prop(
'disabled', "disabled");
}
}
var validateInput= function() {
if ($.trim($("#myInput").val()) === '')
myInputEntered= false;
else
myInputEntered= true;
}
});
</script>
Based on #myInput value, I need to enable/ disable #save button.
Looking forward for the answers.
thanks,
Iswarya
$("#save").prop('disabled', true);
$("#myinput").on('change keydown paste input propertychange click keyup blur', function(){
$("#save").prop('disabled', $('#myinput').val().length>0? false:true);
})
<input type="text" id="myinput">
<button id="save">
save
</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
you can write it like this too. hope this will help you. here is jsfiddle link
It is very likely that by the time you hook the event, the DOM element was not loaded. You need to wait until the DOM is loaded to hook the events.
$(document).ready(function(){
var inputChanged = function() {
var myInputEntered = validateInput();
console.log(myInputEntered);
if (!myInputEntered)
$('#save').hide()
else
$('#save').show();
}
var validateInput= function() {
return $.trim($("#myInput").val()) !== ''
}
$("#myInput").keyup(inputChanged);
inputChanged();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="myInput">
<input type="button" value="save" id="save">

How to enable a button on pasting something using mouse?

I have a textbox and a button. The functionality is that whenever textbox is empty, button is disabled and if not empty then button is enabled. I am doing this using following jQuery code:
$('#user_field').keyup(function(){
if($(this).val().length !=0){
$('#btn_disabled').removeAttr('disabled');
$('#btn_disabled').attr('class', 'upload_button_active');
}
else{
$('#btn_disabled').attr('disabled',true);
$('#btn_disabled').attr('class','upload_button_inactive');
}
})
However, when I am trying to paste input using mouse, the button is not enabling. I have tried binding other mouse events like mousemove, but for that to work we have to move the mouse after pasting. I want to avoid that. Suggest something else.
You should use 'input'
$("#tbx").on('input',function(){
var tbxVal=$(this).val();
if(tbxVal.length===0){
$("#btn").prop("disabled",true);
}else{
$("#btn").prop("disabled",false);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="tbx">
<button id="btn" disabled>Button</button>
You can use the paste event and retrieve the value of the input inside a setTimeout
$('#user_field').on('paste input', function() {
setTimeout(() => {
if ($(this).val().length !== 0) {
$('#btn_disabled').removeAttr('disabled');
$('#btn_disabled').attr('class', 'upload_button_active');
} else {
$('#btn_disabled').attr('disabled', true);
$('#btn_disabled').attr('class', 'upload_button_inactive');
}
}, 1000)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='user_field'>
<button id='btn_disabled' disabled='disabled'>Click</button>
Just Call the function on change.
It will take your input event from mouse as well.
$("#textBox").change(function(
var val=$(this).val();
if(val.length===0){
$("#btn").prop("disabled",true);
}else{
$("#btn").prop("disabled",false);
}
});

jQuery: How to enable/disable button based on input value?

I'm playing around with jQuery and was wondering how you would enable a button once the user has typed into the input field? and if they delete the contents of the input field then the button will be disabled again.
I've created this little demo to help.
Would I have to use 'keyup' to do this?
$( "#target" ).keyup(function() {
alert( "Handler for .keyup() called." );
});
You need to use .prop() to add/remove disabled attribute of button. The function get true/false in second parameter that add/remove target attribute.
$( "#target" ).keyup(function() {
$("button").prop("disabled", !this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="target" />
<button disabled>Next</button>
See result of code demo on your code
I like to use .on() with jQuery, like so:
$("#InputFName").on("keyup", function() {
$("#BtnNext").prop("disabled", false);
if( $("#InputFName").val() == '') {
$("#BtnNext").prop("disabled", true);
}
});
If you want to disable your button :
$('#MyButton').prop('disabled', true);
And if you want to enable it again :
$('#MyButton').prop('disabled', false);
Replace #MyButton by what you need :
$('#id') to get the element by ID
$('.class') to get the element by class
$('tag') to get the element by tag name
Yes, you could also do the check on the blur event of the input
$( "#target" ).blur(function() {
//check if your need to disable the button
});
Keep in mind that is really easy to bypass the disabled state of the button.
Yes, you can use the keyup event, and even better would be the input event, since it catches pasting and other types of inputs.
Inside that event handler, you can just check the inputs value, and make a condition that returns a boolean, that can then be used to set the disabled property of a button
$( "#target" ).on('input', function() {
var val = this.value;
$('#button').prop('disabled', val === "some value")
});
And it will update as the user types
In your case, it looks like you want to check three inputs, and if they all have a value, you enable the button, and you'd do that like this
var elems = $('#InputFName, #InputLName, #InputAge').on('input', function() {
var bool = elems.filter(function() {
return this.value.trim() !== "";
}).length !== elems.length;
$('#BtnNext').prop('disabled', bool);
});
$(document).ready(function() {
// Hide the inputs
$("#InputFName").hide();
$("#InputLName").hide();
$("#InputAge").hide();
$("#BtnNext").prop("disabled", true);
// When the user clicks the First name button
$("#BtnFName").click(function() {
$("#InputFName").show();
$("#InputLName").hide();
$("#InputAge").hide();
});
// When the user clicks the Last name button
$("#BtnLName").click(function() {
$("#InputFName").hide();
$("#InputLName").show();
$("#InputAge").hide();
});
// When the user clicks the Age button
$("#BtnAge").click(function() {
$("#InputFName").hide();
$("#InputLName").hide();
$("#InputAge").show();
});
var elems = $('#InputFName, #InputLName, #InputAge').on('input', function() {
var bool = elems.filter(function() {
return this.value.trim() !== "";
}).length !== elems.length;
$('#BtnNext').prop('disabled', bool);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="Container">
<h3>User Form</h3>
<p>Fill out details:</p>
<button id="BtnFName" class="SrcButton">First name</button>
<button id="BtnLName" class="SrcButton">Last name</button>
<button id="BtnAge" class="SrcButton">Age</button>
<br />
<!-- Input Container -->
<input id="InputFName" placeholder="First Name" />
<input id="InputLName" placeholder="Second Name" />
<input id="InputAge" placeholder="Age" />
<!-- Next Button Container -->
<br />
<button id="BtnNext" class="BtnNext">Next</button>
</div>
$('#InputFName').keyup(function() {
if ($("#InputFName").val() != null) {
$("#BtnNext").removeAttr('disabled');
}
if ($("#InputFName").val() == '') {
$("#BtnNext").attr('disabled', true);
}
});

clear radio buttons when click on text input

I have a group of 4 radio buttons followed by a text input, when users click on the text input field I am trying to clear all radio inputs. here is my code so far.
<input type="radio" name="radio"><label for="radio1">1</label>
<input type="radio" name="radio"><label for="radio2">2</label>
<input type="radio" name="radio"><label for="radio3">3</label>
<input type="radio" name="radio"><label for="radio4">4</label>
<input type="text" id="textInput">
<script>
$('#textinput').click(function () {
radio.checked = false;
});
</script>
You can use .prop() to set checked property of input rabio buttons. Also you have misspelled textInput while event binding
<script>
$('#textInput').click(function () {
$('input[name="radio"]').prop("checked", false);
});
</script>
DEMO
<script>
$('#textInput').click(function () {
$('input[type=radio]').removeAttr("checked");
});
</script>
Or you can try attr() method
$('#textInput').click(function () {
$('input[name="radio"]').attr('checked',false);
});
DEMO
I think the best way to modify your script block (without changing your html) is first by ensuring that the code runs on document ready, and also you should probably ensure that the event is focus, not click, in case someone is using a keyboard or alternate navigation:
$(function() {
$('#textInput').focus(function () {
$('input[name=radio]').prop("checked", false);
});
});
Though it's probably more likely that you want to only clear other selections if they actually enter some data in that field, you might want to instead do:
$(function() {
$('#textInput').on('input', function () {
if($(this).val().length > 0) {
$('input[name=radio]').prop("checked", false);
}
});
});

jquery select all checkboxes

I have a series of checkboxes that are loaded 100 at a time via ajax.
I need this jquery to allow me to have a button when pushed check all on screen. If more are loaded, and the button is pressed, to perhaps toggle all off, then pressed again toggle all back on.
This is what i have, obviously its not working for me.
$(function () {
$('#selectall').click(function () {
$('#friendslist').find(':checkbox').attr('checked', this.checked);
});
});
The button is #selectall, the check boxes are class .tf, and they all reside in a parent div called #check, inside a div called #friend, inside a div called #friendslist
Example:
<div id='friendslist'>
<div id='friend'>
<div id='check'>
<input type='checkbox' class='tf' name='hurr' value='durr1'>
</div>
</div>
<div id='friend'>
<div id='check'>
<input type='checkbox' class='tf' name='hurr' value='durr2'>
</div>
</div>
<div id='friend'>
<div id='check'>
<input type='checkbox' class='tf' name='hurr' value='durr3'>
</div>
</div>
</div>
<input type='button' id='selectall' value="Select All">
I know I'm revisiting an old thread, but this page shows up as one of the top results in Google when this question is asked. I am revisiting this because in jQuery 1.6 and above, prop() should be used for "checked" status instead of attr() with true or false being passed. More info here.
For example, Henrick's code should now be:
$(function () {
$('#selectall').toggle(
function() {
$('#friendslist .tf').prop('checked', true);
},
function() {
$('#friendslist .tf').prop('checked', false);
}
);
});
$('#friendslist .tf')
this selector will suit your needs
Use the jquery toggle function. Then you can also perform whatever other changes you may want to do along with those changes... such as changing the value of the button to say "check all" or "uncheck all".
$(function () {
$('#selectall').toggle(
function() {
$('#friendslist .tf').attr('checked', 'checked');
},
function() {
$('#friendslist .tf').attr('checked', '');
}
);
});
A very simple check/uncheck all without the need of loop
<input type="checkbox" id="checkAll" /> Check / Uncheck All
<input type="checkbox" class="chk" value="option1" /> Option 1
<input type="checkbox" class="chk" value="option2" /> Option 2
<input type="checkbox" class="chk" value="option3" /> Option 3
And the javascript (jQuery) accounting for "undefined" on checkbox value
** UPDATE - using .prop() **
$("#checkAll").change(function(){
var status = $(this).is(":checked") ? true : false;
$(".chk").prop("checked",status);
});
** Previous Suggestion - may not work **
$("#checkAll").change(function(){
var status = $(this).attr("checked") ? "checked" : false;
$(".chk").attr("checked",status);
});
OR with the suggestion from the next post using .prop() combined into a single line
$("#checkAll").change(function(){
$(".chk").attr("checked",$(this).prop("checked"));
});
This is how I toggle checkboxes
$(document).ready(function() {
$('#Togglebutton').click(function() {
$('.checkBoxes').each(function() {
$(this).attr('checked',!$(this).attr('checked'));
});
});
});
maybe try this:
$(function () {
$('#selectall').click(function () {
$('#friendslist .tf').attr('checked', this.checked);
});
});
<div class="control-group">
<input type="checkbox" class="selAllChksInGroup"> All
<input type="checkbox" value="NE"> Nebraska
<input type="checkbox" value="FL"> Florida
</div>
$(document).ready(function(){
$("input[type=checkbox].selAllChksInGroup").on("click.chkAll", function( event ){
$(this).parents('.control-group:eq(0)').find(':checkbox').prop('checked', this.checked);
});
});
I could not get this last example to work for me. The correct way to query the state of the checkbox is apparently :
var status = $(this).prop("checked");
and not
var status = $(this).attr("checked") ? "checked" : false;
as above.
See jQuery receiving checkbox status
It works for me (IE, Safari, Firefox) by just changing your this.checked to 'checked'.
$(function() {
$('#selectall').click(function() {
$('#friendslist').find(':checkbox').attr('checked', 'checked');
});
});
You may try this:
$(function () {
$('#selectall').click(function () {
$('#friendslist input:checkbox').attr('checked', checked_status);
});
});
//checked_status=true/false -as the case may be, or set it via a variable
assuming #selectall is a checkbox itself whose state you want copied to all the other checkboxes?
$(function () {
$('#selectall').click(function () {
$('#friendslist input:checkbox').attr('checked', $(this).attr('checked'));
});
});
try this
var checkAll = function(){
var check_all = arguments[0];
var child_class = arguments[1];
if(arguments.length>2){
var uncheck_all = arguments[2];
$('#'+check_all).click(function (){
$('.'+child_class).attr('checked', true);
});
$('#'+uncheck_all).click(function (){
$('.'+child_class).attr('checked', false);
});
$('.'+child_class).click(function (){
var checkall_checked = true;
$('.'+child_class).each(function(){
if($(this).attr('checked')!=true){
checkall_checked = false;
}
});
if(checkall_checked == true){
$('#'+check_all).attr('checked', true);
$('#'+uncheck_all).attr('checked', false);
}else{
$('#'+check_all).attr('checked', false);
$('#'+uncheck_all).attr('checked', true);
}
});
}else{
$('#'+check_all).click(function (){
$('.'+child_class).attr('checked', $(this).attr('checked'));
});
$('.'+child_class).click(function (){
var checkall_checked = true;
$('.'+child_class).each(function(){
if($(this).attr('checked')!=true){
checkall_checked = false;
}
});
$('#'+check_all).attr('checked', checkall_checked);
});
}
};
To "check all" and "uncheck all" is same checkbox
checkAll("checkall_id", "child_checkboxes_class_name");
To "check all" and "uncheck all" is separate checkbox
checkAll("checkall_id", "child_checkboxes_class_name", "uncheckall_id");
Here is how I achieved it.
function SelectAllCheckBoxes();
{
$('#divSrchResults').find(':checkbox').attr('checked', $('#chkPrint').is(":checked"));
}
The following fires the above line.
<input type=checkbox id=chkPrint onclick='SelectAllCheckBoxes();' />
On the click of chkPrint , every checkbox in the grid divSrchResults' is either checked or unchecked depending on the status of chkPrint.
Of course, if you need advanced functions like unchecking the titled checkbox when every other checkbox has been unchecked, you need to write another function for this.
I created a function that I use on all projects. This is just the initial draft, but maybe it will help:
Function:
function selectAll(wrapperAll, wrapperInputs) {
var selectAll = wrapperAll.find('input');
var allInputs = wrapperInputs.find('input');
console.log('Checked inputs = ' + allInputs.filter(':not(:checked)').length);
function checkitems(allInputs) {
//If all items checked
if (allInputs.filter(':not(:checked)').length === 0) {
console.log('Function: checkItems: All items checked');
selectAll.attr('checked', true);
} else {
console.log('Function: checkItems: Else all items checked');
selectAll.attr('checked', false);
}
}
checkitems(allInputs);
allInputs.on('change', function () {
checkitems(allInputs)
});
selectAll.on('change', function () {
if (this.checked) {
console.log('This checkbox is checked');
wrapperInputs.find(':checkbox').attr('checked', true);
} else {
console.log('This checkbox is NOT checked');
wrapperInputs.find(':checkbox').attr('checked', false);
}
});
}
It accepts the 2 parameters where the inputs are wrapped into and you cand use-it like this:
$(function () {
var wrapperAll = $('.selectallinput');
var wrapperInputs = $('.inputs');
selectAll(wrapperAll, wrapperInputs);
});
See demo: http://jsfiddle.net/cHD9z/
So "checked" is a crappy attribute; in many browsers it doesn't work as expected :-( Try doing:
$('#friendslist').find(':checkbox')
.attr('checked', this.checked)
.attr('defaultChecked', this.checked);
I know setting "defaultChecked" doesn't make any sense, but try it and see if it helps.
<input type="checkbox" onclick="toggleChecked(this.checked)"> Select / Deselect All
Now here are two versions of the toggleChecked function dependent on the semantics of your document. The only real difference is the jQuery selector for your list checkboxes:
1: All checkboxes have a class of “checkbox” (<input type=”checkbox” class=”checkbox” />)
function toggleChecked(status) {
$(".checkbox").each( function() {
$(this).attr("checked",status);
})
}
2: All the checkboxes are contained within a div with an arbitary id:
<div id="checkboxes">
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
</div>
In this case the function would look like this:
function toggleChecked(status) {
$("#checkboxes input").each( function() {
$(this).attr("checked",status);
})
Have fun!
This may work for both (checked/unchecked) selectall situations:
$(document).ready(function(){
$('#selectall').click(function () {
$("#friendslist .tf").attr("checked",function(){return $(this).attr("checked") ? false : true;});
});
});
The currently accepted answer won't work for jQuery 1.9+. The event handling aspect of the (rather heavily) overloaded .toggle() function was removed in that version, which means that attempting to call .toggle(function, function) will instead just toggle the display state of your element.
I'd suggest doing something like this instead:
$(function() {
var selectAll = $('#selectall');
selectAll.on('click', function(e) {
var checked = !(selectAll.data('checked') || false);
$('#friendslist .tf').prop('checked', checked);
selectAll.data('checked', checked);
});
});
That uses a regular click event handler, plus a data attribute to track the "toggled" status and invert it with each click.
Here's a basic jQuery plugin I wrote that selects all checkboxes on the page, except the checkbox/element that is to be used as the toggle. This, of course, could be amended to suit your needs:
(function($) {
// Checkbox toggle function for selecting all checkboxes on the page
$.fn.toggleCheckboxes = function() {
// Get all checkbox elements
checkboxes = $(':checkbox').not(this);
// Check if the checkboxes are checked/unchecked and if so uncheck/check them
if(this.is(':checked')) {
checkboxes.prop('checked', true);
} else {
checkboxes.prop('checked', false);
}
}
}(jQuery));
Then simply call the function on your checkbox or button element:
// Check all checkboxes
$('.check-all').change(function() {
$(this).toggleCheckboxes();
});
As you are adding and removing more checkboxes via AJAX, you may want to use this instead of .change():
// Check all checkboxes
$(document).on('change', '.check-all', function() {
$(this).toggleCheckboxes();
});

Categories

Resources