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

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);
}
});

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">

.preventDefault() no longer functioning as should

I have got to be missing something simple. This script was functioning as anticipated until I added a new element to toggle the input box with a button in the nav bar. Now the form will redirect on submission.
The behaviour expected is that when input is submitted it appears as a comment underneath the comment box.
Currently my .preventDefault(); is no longer working on the click as I am being redirected. I have put too many hours into trying to figure out what went wrong and need some insight on what I changed or implemented incorrectly.
$(function () {
//Toggle compose input box
$(".compose").click(function () {
event.preventDefault();
$(".new").slideToggle("slow");
textarea.focus()
})
//compose input to comment
$('.Form').on('submit', function (event) {
event.preventDefault();
// 1. Grab the content of the form
let formData = $('.Form').serialize();
let entry = $('.textarea input').val();
console.log(entry)
if (entry === null || entry === '') {
alert('text too short!')
} if (entry.length > 140) {
alert('text too long!')
} else {
// 2. Submit using ajax
$.ajax('/comments', {
method: 'POST',
data: formData,
}).then(function (success) {
console.log('succesful')
// 4. Make sure the new comments shows
return $.ajax('/comments');
}).then(renderComments());
}
});
});
Html:
<main class="container">
<section class="new">
<form action='/comments' Method='POST' id="Form">
<h2>Compose Comment</h2>
<textarea id="textarea" name="text" onfocus='this.select()' placeholder="What are you humming about?"></textarea>
<input class="submit" type="submit" value="Submit">
<span class="counter">140</span>
</form>
</section>
Your form has id="Form", but you are selecting class with jQuery.
i.e you need:
//compose input to comment
$('#Form').on('submit', function(event) {
event.preventDefault();
}
Be careful, serializing logic is using class also, update your references.
//Toggle compose input box
$( ".compose" ).click(function() {
event.preventDefault();
$( ".new" ).slideToggle( "slow" );
textarea.focus()
})
You are not passing the 'event' parameter in this binding as shown below in order to get preventDefault to function appropriately.
//Toggle compose input box
$( ".compose" ).click(function(event) {
event.preventDefault();
$( ".new" ).slideToggle( "slow" );
textarea.focus()
})

How to unable button if textbox suddenly have values

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

Disable opposite input if I type into another of a pair

How do I disable one input field if I type into another out of a pair and then if I removed the input by hitting backspace for example so there is nothing in the input field reenable the second input field and vice versa. Code I have so far is below but is not working.
JavaScript:
//disable the opposite input field
var ATGvalue = $('input#atgOrderId').val();
var BQvalue = $('input#bqOrderId').val();
if ( ATGvalue.length > 0) {
$('input#bqOrderId').prop("disabled", true);
} else {
$('input#bqOrderId').removeAttr("disabled");
}
if ( BQvalue.length > 0) {
$('input#atgOrderId').prop("disabled", true);
} else {
$('input#atgOrderId').removeAttr("disabled");
}
HTML:
<label for="bqOrderId">bqOrderId </label><input name="bqOrderId" id="bqOrderId" type="text" />
<label for="atgOrderId">atgOrderId </label><input name="atgOrderId" id="atgOrderId" type="text" />
Your code does work, but only once - to have it continuously update, you first wrap the JS in an event-handler function and attach it to your input elements:
function mutuallyExclusive( e ) { ... }
$( '#bqOrderId' ).on( 'change keyup', mutuallyExclusive );
$( '#atgOrderId' ).on( 'change keyup', mutuallyExclusive );
See this JSFiddle.
I attached it to both the change and keyup events: change to handle programatic (scripted) changes, and keyup to "instantly" update the fields' statuses - otherwise it waits till the user removes focus from the input to call the change event.
you need to include your code inside an event to check when a user type something like this:
$(document).on('keyup','#bqOrderId',function(){
//your code
});
$(document).on('keyup','#atgOrderId',function(){
//your code
});
after to change this:
$('input#bqOrderId').prop("disabled", true);
$('input#atgOrderId').prop("disabled", true);
to this:
$('input#bqOrderId').attr("disabled",true);
$('input#atgOrderId').attr("disabled", true);

how to add event handler for input text box

My program should contain both name search and ID search functionality, when user clicks the name search button, a name search validation is triggered to make sure that the required text field is not empty, on the other hand, when user clicks the id search button, an id search validation is triggered to make sure that a different required text field is not empty. So on the HTML file, I have the following jQuery and HTML codes.
$(document).ready(function() {
$('#submitIDSearch').bind('click', validateIDSearch);
$('#submitNameSearch').bind('click', validateNameSearch);
$('#searchLastName').bind('click', validateNameSearch);
$('#searchFirstName').bind('click', validateNameSearch);
$('#searchID').bind('click', validateIDSearch);
});
var validateNameSearch = function(event) {
var btnSrchLastName = getRef('searchLastName');
if (null != btnSrchLastName) {
var len = btnSrchLastName.value.length;
if (0 == len) {
alert('Last Name is a required field, please input Last Name.');
$('#searchLastName').focus();
return false;
}
}
return true;
}
var validateIDSearch = function(event) {
var btnSrchID = getRef('searchID');
if (null != btnSrchID) {
var len = btnSrchID.value.length;
if (0 == len) {
alert('ID is a required field, please input ID.');
$('#searchID').focus();
return false;
}
}
return true;
}
And I have the following HTML code:
<form id="infoForm" name="checkAbsenceForm" method="post" action="absenceReport.htm">
<label class="q">ID * <input id="searchID" name="searchID" maxlength="9" /></label>
<input id="submitIDSearch" type="submit" value="Search ID"/>
<hr />
<label class="q">First Name <input id="searchFirstName" name="searchFirstName" maxlength="23"></label>
<br />
<label class="q">Last Name * <input id="searchLastName" name="searchLastName" maxlength="23" /></label>
<input id="submitNameSearch" type="submit" value="Search Name"/>
<hr />
</form>
The code behaves correctly except for one problem, when ever the user clicks on the textbox, a click event is fired, which cause a pre-generation of the alert message box.
I observed that when the user types 'enter' key from a text field, a click event is triggered, instead of 'submit', so I guess my listener can only be bind to the click event.
May I ask if there's a workaround method to avoid event triggering from mouse clicking on the textbox?
Thanks a lot!
In case you still need help... http://jsfiddle.net/jaxkodex/Cphqf/
$(document).ready(function() {
$('#submitNameSearch').click(function(event) {
event.preventDefault();
if (validate($('#searchLastName'), 'Last name field is required.')) {
$('#infoForm').submit();
}
});
$('#submitIDSearch').click(function(event) {
event.preventDefault();
if (validate($('#searchID'), 'ID field is required.')) {
$('#infoForm').submit();
}
});
});
function validate(input, errorMsg) {
if (input.val() == null || input.val().length == 0) {
alert(errorMsg);
return false;
}
return true;
}
Since you are using jQuery, You can submit the form whenever a button is clicked with $('#infoForm').submit(); If you check you'd need to use button inputs and no submit inputs any more, since they will trigger the submit event. This is just one approach. If you are looking for live validation, you could use the blur events instead of click but in the text inbut and the click event to the buttons to make sure it works. I guess that overwritting the submit function would work when you have to do some ajax. Hope it helps.
[Edit] If you want to keep the buttons as submit you can do some thing like: http://jsfiddle.net/jaxkodex/S5HBx/1/
You can use the submit event from the form, so it will check every time someone submits the form. jQuery - Submit
$('#infoForm').submit(function (event){
if (!validateIDSearch() && !validateNameSearch()){
event.preventDefault(); // Prevent the submit event, since didn't validate
}
// Will continue to the dafault action of the form (submit it)
});
You just need to set what button the user has selected and do validation based on that during form submit.
searchLastName searchFirstName submitNameSearch are calling validateNameSearch, and submitIDSearch searchRUID are calling validateIDSearch
$(function () {
var validateFx = null; //none selected;
$('#submitNameSearch, #searchLastName, #searchFirstName')
.bind('click', function () {
validateFx = validateIDSearch;
});
$('#searchIDSearch, #searchRUID')
.bind('click', function () {
validateFx = validateNameSearch;
});
$('#infoForm').submit(function (event){
event.preventDefault();
if (validateFx != null && validateFx ()) {
$(this).submit();
}
});
});

Categories

Resources