What event is used when the input value is not blank - javascript

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

Related

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

How to disable submit button? [duplicate]

I wrote this code to disable submit buttons on my website after the click:
$('input[type=submit]').click(function(){
$(this).attr('disabled', 'disabled');
});
Unfortunately, it doesn't send the form. How can I fix this?
EDIT
I'd like to bind the submit, not the form :)
Do it onSubmit():
$('form#id').submit(function(){
$(this).find(':input[type=submit]').prop('disabled', true);
});
What is happening is you're disabling the button altogether before it actually triggers the submit event.
You should probably also think about naming your elements with IDs or CLASSes, so you don't select all inputs of submit type on the page.
Demonstration: http://jsfiddle.net/userdude/2hgnZ/
(Note, I use preventDefault() and return false so the form doesn't actual submit in the example; leave this off in your use.)
Specifically if someone is facing problem in Chrome:
What you need to do to fix this is to use the onSubmit tag in the <form> element to set the submit button disabled. This will allow Chrome to disable the button immediately after it is pressed and the form submission will still go ahead...
<form name ="myform" method="POST" action="dosomething.php" onSubmit="document.getElementById('submit').disabled=true;">
<input type="submit" name="submit" value="Submit" id="submit">
</form>
Disabled controls do not submit their values which does not help in knowing if the user clicked save or delete.
So I store the button value in a hidden which does get submitted. The name of the hidden is the same as the button name. I call all my buttons by the name of button.
E.g. <button type="submit" name="button" value="save">Save</button>
Based on this I found here. Just store the clicked button in a variable.
$(document).ready(function(){
var submitButton$;
$(document).on('click', ":submit", function (e)
{
// you may choose to remove disabled from all buttons first here.
submitButton$ = $(this);
});
$(document).on('submit', "form", function(e)
{
var form$ = $(this);
var hiddenButton$ = $('#button', form$);
if (IsNull(hiddenButton$))
{
// add the hidden to the form as needed
hiddenButton$ = $('<input>')
.attr({ type: 'hidden', id: 'button', name: 'button' })
.appendTo(form$);
}
hiddenButton$.attr('value', submitButton$.attr('value'));
submitButton$.attr("disabled", "disabled");
}
});
Here is my IsNull function. Use or substitue your own version for IsNull or undefined etc.
function IsNull(obj)
{
var is;
if (obj instanceof jQuery)
is = obj.length <= 0;
else
is = obj === null || typeof obj === 'undefined' || obj == "";
return is;
}
Simple and effective solution is
<form ... onsubmit="myButton.disabled = true; return true;">
...
<input type="submit" name="myButton" value="Submit">
</form>
Source: here
This should take care of it in your app.
$(":submit").closest("form").submit(function(){
$(':submit').attr('disabled', 'disabled');
});
A more simplier way.
I've tried this and it worked fine for me:
$(':input[type=submit]').prop('disabled', true);
Want to submit value of button as well and prevent double form submit?
If you are using button of type submit and want to submit value of button as well, which will not happen if the button is disabled, you can set a form data attribute and test afterwards.
// Add class disableonsubmit to your form
$(document).ready(function () {
$('form.disableonsubmit').submit(function(e) {
if ($(this).data('submitted') === true) {
// Form is already submitted
console.log('Form is already submitted, waiting response.');
// Stop form from submitting again
e.preventDefault();
} else {
// Set the data-submitted attribute to true for record
$(this).data('submitted', true);
}
});
});
Your code actually works on FF, it doesn't work on Chrome.
This works on FF and Chrome.
$(document).ready(function() {
// Solution for disabling the submit temporarily for all the submit buttons.
// Avoids double form submit.
// Doing it directly on the submit click made the form not to submit in Chrome.
// This works in FF and Chrome.
$('form').on('submit', function(e){
//console.log('submit2', e, $(this).find('[clicked=true]'));
var submit = $(this).find('[clicked=true]')[0];
if (!submit.hasAttribute('disabled'))
{
submit.setAttribute('disabled', true);
setTimeout(function(){
submit.removeAttribute('disabled');
}, 1000);
}
submit.removeAttribute('clicked');
e.preventDefault();
});
$('[type=submit]').on('click touchstart', function(){
this.setAttribute('clicked', true);
});
});
</script>
How to disable submit button
just call a function on onclick event and... return true to submit and false to disable submit.
OR
call a function on window.onload like :
window.onload = init();
and in init() do something like this :
var theForm = document.getElementById(‘theForm’);
theForm.onsubmit = // what ever you want to do
The following worked for me:
var form_enabled = true;
$().ready(function(){
// allow the user to submit the form only once each time the page loads
$('#form_id').on('submit', function(){
if (form_enabled) {
form_enabled = false;
return true;
}
return false;
});
});
This cancels the submit event if the user tries to submit the form multiple times (by clicking a submit button, pressing Enter, etc.)
I have been using blockUI to avoid browser incompatibilies on disabled or hidden buttons.
http://malsup.com/jquery/block/#element
Then my buttons have a class autobutton:
$(".autobutton").click(
function(event) {
var nv = $(this).html();
var nv2 = '<span class="fa fa-circle-o-notch fa-spin" aria-hidden="true"></span> ' + nv;
$(this).html(nv2);
var form = $(this).parents('form:first');
$(this).block({ message: null });
form.submit();
});
Then a form is like that:
<form>
....
<button class="autobutton">Submit</button>
</form>
Button Code
<button id="submit" name="submit" type="submit" value="Submit">Submit</button>
Disable Button
if(When You Disable the button this Case){
$(':input[type="submit"]').prop('disabled', true);
}else{
$(':input[type="submit"]').prop('disabled', false);
}
Note: You Case may Be Multiple this time more condition may need
Easy Method:
Javascript & HTML:
$('form#id').submit(function(e){
$(this).children('input[type=submit]').attr('disabled', 'disabled');
// this is just for demonstration
e.preventDefault();
return false;
});
<!-- begin snippet: js hide: false console: true babel: false -->
<form id="id">
<input type="submit"/>
</form>
Note: works perfectly on chrome and edge.
The simplest pure javascript solution is to simply disable the button:
<form id="blah" action="foo.php" method="post" onSubmit="return checkForm();">
<button id="blahButton">Submit</button>
</form>
document.getElementById('blahButton').disabled = true ;
It works with/without onSubmit. Form stays visible, but nothing can be sumbitted.
In my case i had to put a little delay so that form submits correctly and then disable the button
$(document).on('submit','#for',function()
{
var $this = $(this);
setTimeout(function (){
$this.find(':input[type=submit]').attr('disabled', 'disabled')
},1);
});

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

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