Hide/show element if input has value - javascript

I want to hide or show an element based on if an input field has a value. Right now I have this, but the issue here is that it will add visible class every time a key is pressed and the value is not empty. Which is not correct and will lead to many problems down the line.
Is there a built in JavaScript event that I can use to check if the element is empty or not? What is the best way to do this with using the least amount of resources?
const query_input = document.getElementsByClassName("query")[0];
query_input.addEventListener('input', event => {
if (query_input.value == ""){
document.getElementsByClassName("submit")[0].classList.add("hidden");
console.log ("empty");
}else{
console.log ("not empty");
document.getElementsByClassName("submit")[0].classList.add("visible");
}
});

I think there is no such built-in thing.
You can do some improvement:
const query_input = document.querySelector(".query");
let btn = document.querySelector(".submit");
query_input.addEventListener('input', event => {
if (query_input.value.trim() == ""){
btn.classList.remove("visible");//remove
btn.classList.add("hidden"); //add
console.log ("empty");
}else{
console.log ("not empty");
btn.classList.remove("hidden"); //remove
btn.classList.add("visible"); //add
}
});

const query_input = document.getElementsByClassName("query")[0];
query_input.addEventListener('blur', event => {
if (query_input.value == ""){
document.getElementsByClassName("submit")[0].classList.add("hidden");
console.log ("empty");
} else {
console.log ("not empty");
document.getElementsByClassName("submit")[0].classList.add("visible");
}
});

Related

Checkbox is still showing true when unchecked jQuery

Ok, so I'm currently having an issue with the $.prop('checked') functionality. When unchecking some of my boxes, and using this function to read the checkboxes, all of them are still showing up as true when some of them should be showing up as unchecked. The part of the function that checks this is below, but some background: I'm using a table with input values in each td element and due to the way it's written, I'm having to gather all the info / validate / and check by using a td.each() function.
$("td", ele).each(function(idx){
var before = $('.e_content', this),
b_name = $('input:last[type!="hidden"], textarea:last, checkbox:last, select:last', this).attr('name'),
b_val = $('input[name="'+b_name+'"], select:last, textarea[name="'+b_name+'"]', this).val(),
b_chx = $('input:checkbox[name="'+b_name+'"]', this).prop('checked'),
after = function(){
before.hide();
$(ele).css("background", color);
$('td.edit', ele).show();
$('td.save', ele).hide();
$('span', this)
// WORKING ON TAKING THE VALUE OF THE .e_content FORM AND REPLACING THE SPAN WITH IT
.html(function(){
console.log(b_name+' : '+b_chx);
if(b_val != undefined && b_val != ''){
if(b_name == 'StageType'){
if(b_val == 1){ return 'Voice'; }
if(b_val == 2){ return 'Text'; }
if(b_val == 3){ return 'Email'; }
}
else if(b_name == 'qtrhour') {
return $('select', before).find(':selected').text();
}
else if(b_chx == true) { return '✓'; }
else if(b_chx == false) { return '✗'; }
else {
if(before.find('input:last').prop('type') != 'checkbox')
return b_val.replace(/\n\r?/g, '<br />');
}
}
})
.show();
};
$(this).html(after);
});
The problem is with this line:
b_chx = $('input:checkbox[name="'+b_name+'"]', this).prop('checked'),
It's coming up always as true even when the checkbox has been unchecked before the save button is hit. This function fires on the .save click event. Hopefully this is enough to determine what might be going wrong.
You can try the following,
$('input:checkbox[name="'+b_name+'"]', this).is(':checked');
To avoid issues regarding to checking or unchecking checkboxes, I normally use jQuery.attr()
$(...).attr('checked')
$(...).attr('checked','checked')
$(...).removeAttr('checked')
Also sometimes I check or uncheck them binding or triggering a .click() function.

jquery - Check specific inputs for empty value and add class to ONLY those inputs that are empty

I have form that has input fields that are required, I point this out with made up class name.
I have piece of code that kind of works. If I focus on required input and then press submit, that input will become red, if empty (which I want). But it only works only on one at a time and if I have focus on the input.
My code is as follows:
function checkIfEmpty(){
$('#register-form input.gv-form-required').blur(function(){
if( !$(this).val()){
$(this).parent().parent().addClass("has-error");
return false;
}else{
return true;
}
});
}
I am almost certain that the blur() method is not suitable for my situation.
So help a man out here, please.
Try this : You have to use .each() to check every input inside form and put removeClass in else condition.
function checkIfEmpty(){
var empty = false;
$('#register-form input.gv-form-required').each(function(){
if($(this).val().trim()==""){
empty = true;
$(this).parent().parent().addClass("has-error");
}else{
$(this).parent().parent().removeClass("has-error");
}
});
return empty;
}
The blur event indeed doesn't seem right in your situation. What I would do is that I would itterate through each field and checked whether it is filled or not. If it is, remove (if any) has-error class. If it isn't filled, give it the has-error class
function checkIfEmpty(){
$('#register-form input.gv-form-required').each(function(){
if($(this).val() === ""){
$(this).parent().parent().addClass("has-error");
}else{
$(this).parent().parent().removeClass("has-error");
}
});
}
change your code to the following:
function checkIfEmpty(){
$('#register-form input.gv-form-required').each(function(){
if( !$(this).is(':empty')){
$(this).parent().parent().addClass("has-error");
}else{
$(this).parent().parent().removeClass("has-error");
}
});
}
try
in else condition
$(this).parent().parent().removeClass("has-error");
js code
if( !$(this).val()){
$(this).parent().parent().addClass("has-error");
}else{
$(this).parent().parent().removeClass("has-error");
}

check whether text is given in all all fields of the same page

I need to take text from fields which have the same class. But when I apply the condition that if field is empty, give an alert, it checks the condition for the first time and ignores all the others as fields are all on the same page with the same class. I cannot have unique classes for every field because the divs are dynamically generated.
Here's my code,
$(document).on('click', '.submit-button', function(){
var maintain=$('form input.inputs-field').val ();
if(maintain == ''){
alert('Please fill that field');
return false;
}
else{
$(document).trigger('save-single-answer', {
answer: $(this).siblings('.inputs-field').val()
});
return true;
}
});
Use .each() to check all the fields. Current you just get the value of first matched element in maintain.
$(document).on('click', '.submit-button', function () {
var maintain = $(this).siblings('.inputs-field').val(); //OR $(this).val()
if (maintain == '') {
alert('Please fill that field');
return false;
} else {
$(document).trigger('save-single-answer', {
//here I assume `this` meant button before (in your code)
answer: maintain
});
return true;
}
});

Enabled and Disabled submit button when multiple fields are empty isn't working

I have here script for Enabled and Disabled submit button. I tried to use each function but isn't working. Every fields had it's value from database. The process should not allowed to submit if one of the fields was empty. Every fields has a value because I used it for editing window. Any help will appreciate. Thanks..
And this my fiddle http://jsfiddle.net/cj6v8/
$(document).ready(function () {
var saveButton = $("#save");
var empty = true;
$('input[type="text"]').change(function () {
$('.inputs').each(function () {
if ($(this).val() != "") {
empty = false;
} else {
empty = true;
}
});
if (!empty) {
saveButton.prop("disabled", false);
} else {
saveButton.prop("disabled", true);
}
});
}); // END OF DOCUMENT READY
The problem is the first else statement.
When $('.inputs').each(... iterates through your fields the empty variable is re-assigned a new value for every input field. In other words, the way you did it, only the last field was significant. (To test it, try this: leave the last one empty, and the button will be disabled, no matter what you put in the first two fields.)
Instead, try initializing empty at false just before the loop (you assume your fields are all filled with something), and then, when you iterate, as soon as you come across an empty field, set empty to true.
var empty = false;
$('.inputs').each(function() {
if($(this).val() == "")
empty = true;
});
As you can see, I removed the problematic else.
you need to init empty to false and cange it only if you find empty inputs inside to loop. http://jsfiddle.net/cj6v8/1/
If you don't want to submit when at least one field is empty you'll need to do this:
....
var empty = true;
$('input[type="text"]').change(function () {
empty = false;
$('.inputs').each(function () {
if ($(this).val() == "") {
empty = true;
break;
}
}
...
each is asynchronous, http://jsfiddle.net/cj6v8/4/
$(document).ready(function() {
var saveButton = $("#save");
$('input[type="text"]').change(function() {
var empty = true;
var inputs = $('.inputs');
inputs.each(function(i) {
if ($(this).val().length == 0) {
console.log($(this).val());
empty = false;
}
if (i === inputs.length-1) saveButton.attr("disabled", !empty);
});
});
});// END OF DOCUMENT READY

how to validate a textarea using javascript

I want to check a textarea whether it is empty or not. For this I write the following code:
function validateForm(theForm) {
var problem_desc = document.getElementById("problem_desc");
if (problem_desc.value == '') {
alert("Please Write Problem Description");
return false;
} else {
return true;
}
}​
For the first time it is working fine. But If I remove the text from the textarea the above function is returning true value i.e., it is assuming the previous text I've entered into the textbox. Can anybody kindly tell me where is the problem?
I am getting it correctly. This is what I did.
Click on validate, it said Please Write Problem Description.
Write something and click. Nothing happened.
Remove the text. Click on validate, it said Please Write Problem Description.
Note: Use a trim function to eliminate empty spaces.
Code:
function validateForm(theForm) {
var problem_desc = document.getElementById("problem_desc");
if ($.trim(problem_desc.value) == '') {
alert("Please Write Problem Description");
return false;
} else {
return true;
}
}
Demo: http://jsfiddle.net/TZGPM/1/ (Checks for Whitespaces too!)
Do check for white space in the value like this
if (problem_desc.value.match (/\S/)) { ... }
or other way check for length
problem_desc.value.length == 0;
Remove spaces and calculate length of the value attribute.
function validateForm(theForm) {
var problem_desc = document.getElementById("problem_desc");
if (problem_desc.value.replace(/ /g,'').length) {
return true;
} else {
alert("Please Write Problem Description");
return false;
}
}
<textarea id="problem_desc"></textarea>
<button onclick="validateForm()">Validate</button>

Categories

Resources