Enable submit button only if inputs have data - javascript

I've looked through numerous topics regarding this, but none of the solutions are fitting my need. I need to enable the submit button only if there is data going to be submitted, and disable it again if there is no data.
$("input").each(function() {
$(this).keyup(function() {
console.log("keyup event fired");
$("input").each(function() {
if ( $(this).val() !== "" ) {
empty = false;
} else {
empty = true;
}
});
if ( empty ) {
$("#download-project").addClass("isDisabled");
$("#download-project").click(function(e) {
e.preventDefault();
});
} else {
$("#download-project").removeClass("isDisabled");
$("#download-project").click(function(e) {
e.preventDefault();
$(".editor-form").submit();
});
}
});
});
My current code only enables the button, and than the if the user deletes the data, it doesn't disable the button. Looking at the console it also seems keyup is only firing once.
JSFiddle

You can add an input event listener to each of the input tags, which will fire when the value has been changed, and check if any of the input tags has a value that is only spaces.
const inputs = $('input'), downloadBtn = $('#download-project');
inputs.on('input', function(e){
var invalid = inputs.is(function(index, element){
return !$(element).val().trim();
});
if(invalid){
downloadBtn.addClass("isDisabled").prop("disabled", true);
} else {
downloadBtn.removeClass("isDisabled").prop("disabled", false);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
First Name: <input type="text"/><br/>
Last Name: <input type="text"/><br/>
Age: <input type="number"/><br/>
<button id="download-project" type="submit" disabled>
Submit
</button>
</form>

Try to put change event listener instead of keyup.
$("input#submit").prop("disabled", true);
let isOk = true;
$("input").change(function (){
$("input").each(()=>{
console.log(this);
if($(this).val() === "") {
isOk = false;
}
});
if(isOk) $("input#submit").prop("disabled", false);
})
Test: https://codepen.io/Opalecky/pen/xxwWmyJ

Related

How do you prevent additional .keyup event after selecting data list item in dropdown?

When using AJAX to auto populate html datalist, why does selecting datalist item trigger another event? I am using jquery keyup to auto suggest queries, after I select a list item the string is placed in the input box correctly but then it triggers the keyup event again which makes the datalist dropdown stay open, covering button.
$(function () {
$('#searchTerm').keyup(function (e) {
var search = $(this).val();
$.post(host/search, {search: search}, function (data) {
$('#list').html(data);
});
});
});
I expect clicking a datalist item to populate the input field with the string selected and then the datalist to disappear, but instead it triggers an additional .keyup event and persists.
The auto suggest feature is quite common so I apologize if I am overlooking anything obvious.
$(function() {
var keyupFired = false;
$('#text').keyup(function(e) {
if (!keyupFired) {
console.log("Yes...");
keyupFired = true;
setTimeout(function() {
alert("OK!!!");
keyupFired = false;
}, 3000);
} else {
console.log("No...");
e.preventDefault();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<input type='text' id='text' name='text' placeholder='please enter text....' />
$(function() {
var keyupFired = false; // intialize the flag
if (!keyupFired) {
keyupFired = true; // before starting the task
$('#searchTerm').keyup(function(e) {
var search = $(this).val();
$.post(host / search, {
search: search
}, function(data) {
$('#list').html(data);
keyupFired = false; //completed its task so again make `keyupFired =false`
});
});
} else {
e.preventDefault();
}
});
To implement this functionality you need to maintain one flag.

When user enters text in textbox then append a prefix value

I have a textbox which needs to be filled with website URL. So when user places the cursor in the textbox then the textbox should prefill with "http://" (Not a placeholder).
If the user does not enter anything and moves to the next textbox then the textbox have empty value
If the user fills the textbox then the value is unchanged
I tried below Javascript code but did not work:
if (document.activeElement.id == 'input-textbox-id' && !document.activeElement.value) {
document.querySelector("#input-textbox-id").value="http://";
} else if (document.activeElement.id != 'input-textbox-id' && (!document.activeElement.value || document.activeElement.value == 'http://')) {
document.querySelector("#input-textbox-id").value="";
}
You can use the focus and blur events for this.
Assuming that the variable textBox contains the reference to your textBox element, you can use the following code:
let textBox = document.getElementById("a");
textBox.addEventListener("focus", function() {
if (!this.value) {
this.value += "http://";
}
});
textBox.addEventListener("blur", function() {
if (this.value == "http://") {
this.value = "";
}
});
<input type="text" id="a">
You will need to attach event listener by using addEventListener. Events you need: focus and focusout.
We add .http-prefill class for all inputs. We iterate over inputs array and attach event.
Please do not forget to remove eventListener when you are done eg. you unload the form.
To do so, just copy the code for adding listeners and replace addEventListener with removeEventListener.
inputs.forEach(function(input) {
input.removeEventListener('focus', onFocus);
input.removeEventListener('focusout', onFocusOut);
});
Example code:
var fillValue = 'http://';
var onFocus = function() {
this.value = fillValue;
}
var onFocusOut = function() {
if (this.value === fillValue) {
this.value = '';
}
}
var inputs = document.querySelectorAll('.http-prefill');
inputs.forEach(function(input) {
input.addEventListener('focus', onFocus);
input.addEventListener('focusout', onFocusOut);
});
.http-prefill {
width: 100%;
margin-bottom: 5px;
}
<input class="http-prefill" name="input-0" />
<input class="http-prefill" name="input-1" />
<input class="http-prefill" name="input-2" />
<input class="http-prefill" name="input-3" />
you can use some key events like onKeyDown and when keydown you can get hold of old value and append it with new value.
let keyPressed = true
function onKeyDown(event) {
if(keyPressed && event.keyCode !== 8)
{
keyPressed = false;
let oldvalue = document.getElementById('input-textbox-id').value;
document.getElementById('input-textbox-id').value = "http://"+oldvalue
}
if(!document.getElementById('input-textbox-id').value)
{
keyPressed = true;
}
}
here is working code. http://jsbin.com/zoxiwokepi/edit?html,output

Prevent submit by disabling button until one value is selected

How can I (I guess a solution is to ) disable my submit button until at least one value is selected or typed?
<form name="forma" method="POST" action="used-results.php" id="apliforma">
lots of textboxes and dropdown menus
<a onclick="forma.submit();" class="btn btn-primary">Search</a>
</form>
You have add a listener to change event and check for values
$(document).ready(function (){
validate();
// In case of validating specific fields
$('#name, #email').change(validate);
});
function validate(e){
if ( $('#name').val().length > 0 && $('#email').val().length > 0 ) {
$('#submit').prop('disabled', false);
} else {
$('#submit').prop('disabled', true);
}
}
Please check this one which has the dropdown too
JSFIDDLE
$(document).ready(function (){
validate();
$('input,select').change(validate);
});
function validate(e){
var validation = true;
$('input , select').each(function(){
if($(this).val()=="")
{
validation = false;
}
});
if ( validation ) {
$('#submit').prop('disabled', false);
} else {
$('#submit').prop('disabled', true);
}
}
Yes, this can be done like this.
function ready(){
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
inputs[i].addEventListener('change', function (e) {
document.getElementById('submit').disabled = e.target.value === "" }, false);
}
}
document.addEventListener( "DOMContentLoaded", ready, false )
You'll have to add the following tags to your submit button id='submit' disabled='disabled'.
Cheers.

How to click on one button and if form is save to click on other

I have 3 buttons and 1 form.
1st button is new button. Button that i want to add. When i click on this new button i want jQuery to click on next button:
2nd button: Save - when this button is clicked need to add function like:
if($("#email").val().trim().length>0 && $("#customer_firstname").val().trim().length>0 && $("#customer_lastname").val().trim().length>0 ) {
if this is valid - form is saved successfully jQuery need to click on third button (when this is invalid stop to here. Other js will show errors in form):
3rd button: Send order - after clicked on it do not need nothing. Other js will do the rest.
Other way will be to use "save" button and if is valid to click on "send button" - may be is more is solution?
<p class="orderbutton">
<input type="submit" class="order-button-opc" id="order-button" value="Order Button">
</p>
<p class="submit">
<input type="submit" class="exclusive button" name="submitAccount" id="submitAccount" value="{l s='Save'}" />
</p>
<p class="cart_navigation" id="cart_navigation">
<input type="submit" value="I confirm my order" class="extraorderbutton">
</p>
I try this:
<script>
$(document).ready(function () {
var firstFormValid = false;
var isFormValid = false;
$('#order-button').click(function(){
if(anycondition)
firstFormValid = true;
});
$("#submitGuestAccount").click(function () {
if(firstFormValid ) {
if($("#email").val().trim().length>0 &&$("#customer_firstname").val().trim().length>0 && $("#customer_lastname").val().trim().length>0 ) {
isFormValid = true;
} else isFormValid = false;
} else firstFormValid =false;
});
$("#order-button").click(function () {
if(isValid && firstFormValid)
$('#order-button').submit()
});
});
</script>
But i get error:
Use this hope will help.
$(document).ready(function () {
var firstFormValid = false;
var isFormValid = false;
$('#newbutton').click(function(){
if(anycondition)
firstFormValid = true;
});
$("#savebutton").click(function () {
if(firstFormValid ) {
if($("#email").val().trim().length>0 &&$("#customer_firstname").val().trim().length>0 && $("#customer_lastname").val().trim().length>0 ) {
isFormValid = true;
} else isFormValid = false;
} else firstFormValid =false;
});
$("#sendbutton").click(function () {
if(isValid && firstFormValid)
$('#FORMID').submit()
});
});
Rather than just debug/throw some code at you, you could approach this better by working on each of the areas separately, likely help for this and the future ?
Declare elements/selectors
Validate Function
Form 'check' function
Form 'save' function
Event Handlers.
Say,
1) Declare elements/selectors
var _inputemail = $("#email"),
_inputfirstname =$("#customer_firstname"),
_inputlastname = $("#customer_lastname"),
_button_check = $("#checkbutton"),
_button_send = $("#sendbutton"); /* hidden initially in css */
2) Create a Validate function
function isValid() {
var is=false;
/* add in the checks */
if(_inputemail.val().length>0) { is=true; }
/* return true or false */
return is;
}
3) form 'check' function
function checkForm() {
/* use the validate function */
if(isValid()) {
/* show the 'save' button */
_button_send.show();
}
}
4) form 'send' function
function sendForm() {
/* sendform here */
if(isValid()) {
/* we could run the validate again if we like */
}
}
5) Event Handlers
_button_check.on("click", checkForm);
_button_send.on("click", sendForm);
/* now we have separate functions we can check/send
the form from other events too
eg. Checking as we type */
_inputlastname.on("keyup",checkForm);
Got some reusable / easy to manage 'components' now
will be some things to sort in this code, but hope helps in someway! ( ? )

Respect regular onsubmit handlers from jQuery.submit

I want a jQuery form submit handler to respect any previous submit handlers, including ones added with onsubmit.
I'm trying to detect the previous handler's return value but can't seem to do it:
<form><input type="submit" /></form>
<script type="text/javascript">
$('form')[0].onsubmit = function() { return false; }; // called first
$('form').submit(function(e) {
console.log(e.result); // undefined
console.log(e.isDefaultPrevented()); // false
console.log(e.isPropagationStopped()); // false
console.log(e.isImmediatePropagationStopped()); // false
});
</script>
Is there a way to do this?
I found one non-jQuery way to do this:
var form = $('form')[0];
var old_onsubmit = form.onsubmit;
form.onsubmit = function() {
if ($.isFunction(old_onsubmit)) {
if (old_onsubmit() === false) {
console.log("false");
return false;
}
}
console.log("true");
return true;
}
But I'd much prefer detecting this from the jQuery-bound submit handler

Categories

Resources