Enable and disable button by if - javascript

I have a problem with my js code. I have managed to disable the submit button, if there is no input value, but now I want to enable it again when a value is present.
Thank you very much
// submit message
submitButton.addEventListener("click", (e) =>{
if(userMessage.value = " ") {
submitButton.setAttribute("disabled", true);
alert("fill field");
} if(userMessage.value != " ") {
submitButton.setAttribute("disabled", false);
alert("send");
}
// prevent default
e.preventDefault();
})

You assign a variable instead of condition and second one you are giving single space.
submitButton.addEventListener("click", (e) =>{
if(userMessage.value == "") {
submitButton.setAttribute("disabled", true);
alert("fill field");
} if(userMessage.value != "") {
submitButton.setAttribute("disabled", false);
alert("send");
}
// prevent default
e.preventDefault();
})

You could add an event listener to the input element and listen for the keyup event. like:
inputField.addEventListener('keyup', e => {
submitButton.setAttribute("disabled", e.target.value === "");
});

Maby i dont understand it right but you want to click on a disabled button? To enable it? I dont think that works maby try it when the user types in the input field. So
// submit message
InputField.addEventListener("keyup", (e) =>{
if(e.target.value = "") {
submitButton.setAttribute("disabled", true);
alert("fill field");
} else if(e.target.value != "") {
submitButton.setAttribute("disabled", false);
alert("send");
}
})
something like this

add event on input
//when page loads to be disabled
submitButton.setAttribute("disabled", true);
//check when something is changed
userMessage.addEventListener("keyup", (e) =>{
submitButton.setAttribute("disabled", this.value.trim() == "");
})

There are several problems with your code:
You assign the value of " " with = to the userMessage, but you probably intended to check if the value is empty or not. Either use == or even better ===.
You are checking against a value that consists out of just one space (" " !== ""). Use .trim() to actually trim all whitespace around a value.
The second if statement is exactly the opposite of the first one and can be written as an else statement.
You also need to check if the input has changed, so the button would then be enabled again. You could just add an event listener on the input event of your text field here and enable/disable the button.
Setting the attribute disabled to false with setAttribute won't work here as setAttribute converts it into a String. So technically it is still trueish. Instead directly set disabled on your input element, or use removeAttribute to get it enabled again.
Here is an example, using the input event for disabling and enabling the button. Note, that the button is not initially disabled. To fix that, I created the checkIfSet function, so I can just set it on the addEventListener and also just call it to check if the button needs to be disabled or not.
const submitButton = document.querySelector('#submitButton');
const userMessage = document.querySelector('#userMessage');
const checkIfSet = () => {
const trimmedInput = userMessage.value.trim();
if (trimmedInput == '') {
submitButton.disabled = true;
console.log('disabled');
} else {
submitButton.disabled = false;
console.log('enabled');
}
};
const submit = (e) => {
console.log('send');
e.preventDefault();
}
// submit message
userMessage.addEventListener('input', checkIfSet);
submitButton.addEventListener('click', submit);
checkIfSet();
button:disabled {
background: red;
opacity: .5;
}
<input type="text" id="userMessage" />
<button id="submitButton">button</button>

Simple and short approach:
Disable submit <button> by default
Attach oninput event to <input/> which toggles the disabled status of the<button>
try
<input type="text" id="userMessage" value="" oninput="this.value == '' ? document.querySelector('#submitButton').disabled = true : document.querySelector('#submitButton').disabled = false"/>
<button disabled id="submitButton">Submit</button>

Related

How to disable submit button if (http), (https), or (www) are found in textarea

I already have a code I created in javascript that disables the submit button on a form if a dropdown choice is chosen but I also want to turn off the submit button if the string (http), (https), or (www) is typed into textarea of the form. Any help in the right direction would be awesome.
Try this
<textarea id="my-textarea"></textarea>
document.querySelector('#my-textarea').addEventListener('input', (event) => {
if (event.target.value.includes('http') || event.target.value.includes('https') || event.target.value.includes('www')) {
console.log('invalid');
} else {
console.log('valid');
}
});
Here is the sample fiddle: https://jsfiddle.net/2qorhekd
You could listen for the keyup event and check the input when the event fires.
Something like:
let illegalWords = ["http", "https", "www"];
function checkText(text) {
if (text.length >= 1) {
for (let word of illegalWords) {
if (text == word) {
// word found, remove submit button
console.log("found");
document.getElementById("submit").style.display = "none";
}
}
}
}
<textarea onkeyup='checkText(this.value);'></textarea>
<button type="submit" id="submit">Submit</button>
You could add an else block to this code to make the submit button appear (if not currently visible) when the illegal words are removed.
Function to test if string has contains http, https or www
var valid = function(text){
var regex = /(https?|www)/;
return !regex.test(text);
}

jQuery - Validation

I'm having an issue with my validation process. I'm not using a standard "submit" button, rather I have <span class="button" id="print">Print</span> and jQuery listens for a click. This is the validation code I have when that "button" is clicked:
var validation = "";
function validate() {
$("#servDetails").find("input").each(function () {
if ($(this).prop("required") && $(this).val() == "") {
validation = false;
}
else {
validation = true;
}
});
$("#checklist").find("input[required]").each(function () {
if ($(this).prop("required") && $(this).val() == "") {
validation = false;
}
else {
validation = true;
}
});
}
$("#print").on("click", function() {
validate();
if (validation == false) {
alert("Please fill out all required inputs!");
return false;
}
else {
window.print();
}
});
If I click the button without filling anything out (all items blank), I get my alert as expected.
If I fill out all of the required elements, it pulls up the print dialouge as expected.
However, if I leave some of the boxes blank while others are correctly filled, it still goes to print instead of giving me the alert like I need. Any thoughts?
The code have to be rewritten, or better replace it with any validation plug-in.
But in your case, I suppose, you just forgot to return, in case you found some not filled field. So if you have any filled input it override your validation variable.
The simplest solution is to remove
else {validation = true;} code blocks, and add
validation = true;
at the beggining of the function.

enable submit button after validation the form in jquery validation plugin [duplicate]

I have an enabled and disabled state for the submit button on my form.
The conditions are as follows:
If all input fields have been entered and are valid enable the submit button.
If some fields have not been entered do not enable the submit button.
So far the validation is being done within the onkeyup event and is only working for the first input:
//Custom onkeyup validation
onkeyup: function(element) {
//Check if input is empty remove valid class from parent
var formInput = $(element),
formInputParent = $(element).parent('fieldset');
if(formInputParent.hasClass('form--valid') && formInput.val() === "") {
formInputParent.removeClass('form--valid');
}
//Check if all fields are not empty to remove submit--disabled class
var formInputs = $('form').find(':input');
console.log(formInputs);
formInputs.each(function(){
if(formInputs.length > 0) {
formInputs.parents('form').find('.submit-form').removeClass('submit--disabled');
}
});
}
Check here for a DEMO
You would simply construct a blur (or even a keyup) handler function to toggle the button based on the form's validity. Use the plugin's .valid() method to test the form.
$('input').on('blur', function() {
if ($("#myform").valid()) {
$('#submit').prop('disabled', false);
} else {
$('#submit').prop('disabled', 'disabled');
}
});
DEMO: http://jsfiddle.net/sd88wucL/
Instead, you could also use both events to trigger the same handler function...
$('input').on('blur keyup', function() {
if ($("#myform").valid()) {
$('#submit').prop('disabled', false);
} else {
$('#submit').prop('disabled', 'disabled');
}
});
DEMO 2: http://jsfiddle.net/sd88wucL/1/
Source: https://stackoverflow.com/a/21956309/594235
The code below is what I ended up with so far:
$('#formId').on('blur keyup change', 'input', function(event) {
validateForm('#formId');
});
function validateForm(id) {
var valid = $(id).validate().checkForm();
if (valid) {
$('.form-save').prop('disabled', false);
$('.form-save').removeClass('isDisabled');
} else {
$('.form-save').prop('disabled', 'disabled');
$('.form-save').addClass('isDisabled');
}
}
// Run once, so subsequent input will be show error message upon validation
validateForm('#formId');
It uses checkForm() instead of the form() and my disable button has the classform-save
It is based on #Sparky's answer
There is an issue filed on the jquery-validation git repo.
$('form').find(':input').each(function(index, value){
//action for every element
$(value);
});
In this case you can do this that way: (but I dont like this solution)
var areSomeFieldsEmpty = false;
$('form').find(':input').each(function(i, v){
if ($(v).val().length <= 0){
areSomeFieldsEmpty = true;
}
});
if (!areSomeFieldsEmpty){
//unlock form
}
http://jsfiddle.net/89y26/335/
<html>
<form id="form">
name<br>
<input type="text"><br>
Roll Number<br>
<input type="number"><br>
<input id="next" type="submit" disabled="disabled">
</form>
</html>
Initially, I have set submit button disabled and for each change in the input tag I will call a function to validate the form using jquery
$("input[type='text'], input[type='number']").on("input", function () {
validate();
});
function validate(){
var show = true;
$("input[type='text'], input[type='number']").each(function(){
if($(this).val()==''){
show = false;
}
});
if(show){
$('#next').css({cursor:'pointer'})
$('#next').removeAttr('disabled')
}
else {
$('#next').css({cursor:'not-allowed'})
}
}
});

Javascript or jQuery form validation only for exact action

I have a form with several action buttons, and every button has a different action.
For example, one button is "Save and continue" and another is "Save and finished". I want to validate values from selections on the form, and if the value is equаl to some number, only then can it run the action "finished". I want to validate only for this exact action.
I try this but it did not work:
function OnSubmitForm() {
if(document.pressed == 'SOME ACTION') {
var x=document.forms["FORM NAME"]["INPUT NAME"].value;
var i="";
if (x==null || x!=i) {
alert("You can't do this");
return false;
}
}
else
return true;
}
My idea is to validate only when clicking on the exact action on the form.
Hmm, I have an idea. Why don't you listen for the change event on your <select> element and update the buttons disabled attribute, like so.
$('#mySelectBox').change(function() {
var value = this.value,
disabled = null;
if( value === 1 ) {
disabled = true;
} else if( value === 2 ) {
disabled = false;
}
$('#theButton').prop('disabled', disabled);
});
Or if you want to do it the nerdy way you could do this.
$('#mySelectBox').change(function() {
var value = this.value,
disabled = value === 1 ? true : false;
$('#theButton').prop('disabled', disabled);
});
That should work, hope it helps.

Jquery- disabling 'on change' event handler before it runs

http://jsfiddle.net/B9Fub/
<tr class="fis">
Test: <input type="text" name="test" id="test" value="Test">
<tr class="fis">
Empty: <input type="text" name="empty" id="empty">
<input type="button" value="find" id="find">
$('#find').click(function() {
alert('wont work if any other fields are filled other than TEST');
});
$('#test').change(function() {
// needs to fill the form for other functionality
$('#empty').val('empty');
alert('change');
});
So here I have fields that are filled when the first input is 'changed'
But I don't want it to run [change] if they input in the first field and click the 'find' button.
I was wondering if there was a way to do this. From what I found, 'change' happens before the 'find' button if you click on it.
I've tried changing 'change' to 'focus' and give it to the other field so the first field has no event handlers, but that may give me trouble further down the way.
I need the fields to be filled but I don't want them filled if the user clicks the find button.
The mousedown event fires before the change event, so by using that and jQuery's data() method you can set a flag to see if the activeElement is in fact #test when the find button is clicked, and if so don't set the value :
$('#find').on('mousedown', function() {
$('#test').data('flag', document.activeElement.id === 'test');
});
$('#test').on('change', function() {
if ( ! $(this).data('flag') ) $('#empty').val('empty');
});
FIDDLE
Still, not sure what you want. Maybe this will help.
var frm = $('form')[0]; //assuming you have one form on that page
var fnd = $('#find');
fnd.click(function(){
var te = 0, fe = 0;
if(frm.elements[0].value !== '')te = 1;
for(var i=1,l=frm.length; i<l; i++){
if(frm.elements[i].value !== '')fe = 1;
}
if(fe === 1){
return false;
}
else{
// do your thing here
return true; // some editors show an error if you don't always return a value
}
});
$('#test').change(function(){
if(fnd.val() !== ''){
return false;
}
else{
// do your thing here
return true;
}
});
I've found the answer. Using e.stopPropagation(); on $('#find') allowed me to stop the .change() from occurring

Categories