I'm trying to make website which will enable button when the certain condition is met. But when I run it within simple if the condiiton is checked only at the beginning and it doesn't enable and disable on changing condition. Condition is changing inside other event listener so the condition is dynamically. The condition is met when the dicitonary consists only of true which means that input is proper
`var submitButton = document.getElementById("submit_button");`
And after some event listeners connected to inputs
`if(Object.values(check_dict).filter(x=>x==true).length === 6)
{
submitButton.disabled = false;
}
else
{
submitButton.disabled = true ;
}`
pretty straight forward. add an eventlistener to the input you want to watch and then disable the submit button inside the function
document.getElementById('test').addEventListener('input',myFunc)
function myFunc(){
if(event.target.value == "x")document.getElementById("submit_button").disabled = true;
else document.getElementById("submit_button").disabled = false;
}
<input id ='submit_button' type='submit'>
<input id='test'>
You could use removeAttribute() and setAttribute() to toggle the state of the submit button using a conditional.
See the snippit for a very simple example of how to toggle states using classes with .classList along with add/remove attribute method.
const checkInput = (e) => {
if(e.target.value.length >= args.rules.length){
e.target.classList.remove('error')
e.target.classList.add('success')
submitBtn.removeAttribute('disabled')
inputDisplay.textContent = args.success.value
}else{
e.target.classList.add('error')
e.target.classList.remove('success')
submitBtn.setAttribute('disabled', 'true')
inputDisplay.textContent = args.error.value
}
}
const args = {
rules: {
length: 8
},
success: {
value: "Success! You may submit now!"
},
error: {
value: "Input must contain 8 or more characters!"
}
}
const fname = document.getElementById('fname')
const submitBtn = document.getElementById('submit')
const inputDisplay = document.getElementById('input-display')
inputDisplay.textContent = args.error.value
submitBtn.disabled = 'true'
fname.addEventListener('input', checkInput)
.success {
color: darkgreen;
background-color: lightgreen;
}
.error {
color: darkred;
background-color: pink;
}
<input name="firstname" id="fname" placeholder="Please enter your first name">
<button id="submit" type="button">Submit</button>
<div id="input-display"></div>
Related
I am having trouble with using JavaScript so that when a user tries to submit my HTML/CSS form while either of the input fields are blank, then the relevant field would appear 'highlighted' or outlined. My aim was to add a class (a transparent layer of some kind) to one of the input fields depending on if the field's value is blank or not. I have so far tried using: element.classList.add("className"); with no luck. The input fields are defined with no classes so I just wanted to add.
Any help appreciated.
I would just loop over my inputs and check if their values are true or not, then change class name accordingly. A input's value returns false if it's blank.
const form = document.querySelector("form");
const inputs = document.querySelectorAll("input");
form.addEventListener("submit", (event) => {
event.preventDefault();
checkInputs();
});
const checkInputs = () => {
inputs.forEach(input => {
if (input.value) {
input.className = "your-class-name-1"
} else {
input.className = "your-class-name-2"
}
})
};
As everyone told above, you should use the required parameter, but if you want to use your solution you should tell us what is not working.
I've checked your code and created a little form for this purpose like:
<form id='form'>
<input type="text"/ id='form-field1' placeholder='1'>
<input type="text"/ id='form-field2' placeholder='2'>
<button type='submit'/>
</form>
Your code:
const form = document.getElementById('form');
const a = document.getElementById('form-field1');
const b = document.getElementById('form-field2');
form.addEventListener('submit', (e) => {
e.preventDefault();
checkInputs();
});
function checkInputs() {
const aValue = a.value.trim();
const bValue = b.value.trim();
console.log(aValue);
console.log(bValue);
if (aValue === "") {
a.classList.add("red-transparent-overlay");
} else {
a.classList.add("green-transparent-overlay");
}
}
and submitting my form when the first field is null adds red-transparent-overlay class to the first field, the same happens with the second statement, so your code is working.
Make sure you remove the other class when you add a class.
if (aValue === "") {
a.classList.add("red-transparent-overlay");
a.classList.remove("green-transparent-overlay");
} else {
a.classList.add("green-transparent-overlay");
a.classList.remove("red-transparent-overlay");
}
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>
I need your help guys.
I use a textarea that automatically expands by changing the number of rows.
In my project, the page does not reload and stays as it is after submitting the form. I need to change dynamically the number of rows (2) on submit.
Also one can send the form by Enter. So I need to change the number of rows after pushing a button or hitting the Enter key.
I've coded a rough sketch of the form that I have in my project so that you could test it: https://codepen.io/C3La-NS/pen/NagZbr
<form id="NewMessage">
<textarea id="shoutbox-comment" data-min-rows="2"></textarea>
<button id="send_message" type="submit" onclick="chatSubmit();">send</button>
</form>
JS:
// auto-resizing textarea
const textarea = document.getElementById("shoutbox-comment");
textarea.addEventListener("input", function() {
this.rows = 2; // Erm...
this.rows = countRows(this.scrollHeight);
});
function countRows(scrollHeight) {
return Math.floor(scrollHeight / 20); // 20px = line-height: 1.25rem
}
// submit by Enter
$(document).ready(function() {
$("#shoutbox-comment").on("keypress", function(event) {
if (event.keyCode == 10 || event.keyCode == 13) {
event.preventDefault();
chatSubmit();
}
});
});
// submit FORM
function chatSubmit() {
$("#NewMessage").submit();
}
Thank you!
jQuery submit accept as parameter a callback that is triggered before submit so, you can do:
$("#NewMessage").submit(function( event ) {
event.preventDefault();
$('#shoutbox-comment').attr('rows', 2);
});
Just couple of changes in your script:
const textarea = $("#shoutbox-comment");
const minRows = textarea.data('minRows');
textarea.on("input", function(e) {
this.rows = 1; // Erm...
this.rows = countRows(this.scrollHeight);
});
function countRows(scrollHeight) {
var toReturn = Math.floor(scrollHeight / 20); // 20px = line-height: 1.25rem
return toReturn > minRows ? toReturn : minRows;
}
// submit by Enter
$(document).ready(function() {
$("#shoutbox-comment").on("input", function(e) {
if (e.keyCode == 10 || e.keyCode == 13) {
e.preventDefault();
chatSubmit();
}
});
});
// submit FORM
function chatSubmit() {
// Send the message via AJAX;
textarea.val('').trigger('input');
return false;
}
#shoutbox-comment {
width: 220px;
outline: none;
resize: none;
line-height: 20px;
overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="NewMessage">
<textarea id="shoutbox-comment" data-min-rows="2"></textarea>
<button id="send_message" type="submit" onclick="chatSubmit();">send</button>
</form>
I've also included data-min-rows attribute inside the script.
Also on CodePen.
I have code similar to this:
<INPUT TYPE="submit" NAME="VAR1" VALUE="X" OnClick="
this.disabled=true;
this.value='Submitting...';
this.form.submit();">
The problem is that I need that name in the handler but it seems that disabling the button also disables the name. I tried adding 'this.name="VAR1";' but that didn't work. Does anyone know how to pass the information that a specific button was pressed? It doesn't have to be a name. Alternative methods welcome.
Here's an example that you can do. Just prevent default event on keypress. This will allow you to access the attributes. You can also do some styling to it by accessing it's data ref.
(function(){
// Attach DOM
var debug = document.getElementById('debug');
var elm = document.querySelectorAll('[data-disabled="false"]');
for (var i = 0; i < elm.length; i++) {
elm[i].addEventListener('click', function(evt) {
// Disable default event
evt.preventDefault();
// Disabled State
evt.target.dataset.disabled = true;
evt.target.value = 'Submitting...';
// Log Information to DOM
debug.innerHTML = this.getAttribute('name') + ' is still accessible, but input is disabled by disabling click so that the user doesn\nt submit anything, but the attributes can still be read.';
// Artificial request, completes in 2 seconds
setTimeout(function() {
evt.target.value = 'Done!';
evt.target.dataset.disabled = false;
}, 2000);
});
}
})();
input {
border: 1px solid black;
padding: 5px;
}
input[data-disabled="true"]{
background: red;
}
<input type="submit" name="superInput" data-disabled="false" value="Submit" />
<div id="debug"></div>
I know it's easy to do using < button > or < input type="submit" but how would you keep this button disabled unless both input fields are filled?
<input id="one" type="text">
<input id="two" type="text">
OK
Tie an event to both inputs, and check that both have values. Then enable the link.
$('#one, #two').blur(function() {
if($('#one').val() !== "" && $('#two').val() !== "") {
$('.button').attr('href','#');
} else {
$('.button').removeAttr('href');
}
});
and change your html to:
<a class="button">OK</a>
so that the link is disabled on page load. Here's a JSFiddle demo.
$(document).ready(function() {
$inputs = $('#one,#tow');
$inputs.change(check);
$submit = $('#submit');
function check() {
var result = 1;
for (var i = 0; i < $inputs.length; i++) {
if (!$inputs[i].value) {
result = 0;
break;
}
}
if (result) {
$submit.removeAttr('disabled');
} else {
$submit.attr('disabled', 'disabled');
}
}
check();
});
suggest use angular form
$(document).ready(function(){
//$(".button").attr('disabled', "disabled");
$(".button").click(function(){
one = $("#one").val();
two = $("#two").val();
if(one && two){
///both fields filled.
return true;
}
//one or both of them is empty
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="one" type="text">
<input id="two" type="text">
OK
This is my implementation if facing this kind of situation.
First, am add disabled class onto anchor tag on page load by using this style :
.disabled {
color : gray // gray out button color
cursor : default; // make cursor to arrow
// you can do whatever styling you want
// even disabled behaviour
}
We add those class using jquery on document ready together with keyup event like so :
$(function () {
// add disabled class onto button class(anchor tag)
$(".button").addClass('disabled');
// register keyup handler on one and two element
$("#one, #two").keyup(function () {
var one = $("#one").val(),
two = $("#two").val();
// checking if both not empty, then remove class disabled
if (one && two) $(".button").removeClass('disabled');
// if not then add back disabled class
else $(".button").addClass('disabled');
});
// when we pressing those button
$('.button').click(function (e) {
// we check if those button has disabled class yet
// just return false
if ($(this).hasClass('disabled')) return false;
});
});
DEMO