Check if input text is filled and display different divs - javascript

I have 3 input text and I want to display a div if one over 3 is filled, a different div if 2 input over 3 are filled and so on. How can I do it with javascript?
<input type="text" id="text1" name="text1" />
<input type="text" id="text2" name="text2" />
<input type="text" id="text3" name="text3" />
I tried this but it doesn't work
function display() {
if ($('#text').val() != '') {
document.getElementById('green').style.display = 'block';
}   
}

CSS
#a, #b, #c {
visibility:hidden;
}
HTML
<div id="a"></div>
<div id="b"></div>
<div id="c"></div>
JavaScript
var istext1filled = document.querySelector('input#text1').value.length>0;
var istext2filled = document.querySelector('input#text2').value.length>0;
var istext3filled = document.querySelector('input#text3').value.length>0;
if(istext1filled) {
document.querySelector('div#a').style.visibility = 'visible';
}
if(istext2filled) {
document.querySelector('div#b').style.visibility = 'visible';
}
if(istext3filled) {
document.querySelector('div#c').style.visibility = 'visible';
}

I think there's a misunderstanding here. #Domenico asked
I have 3 input text and I want to display a div if one over 3 is filled, a different div if 2 input over 3 are filled and so on.
If I am not misunderstanding his statement: I think he is talking about the number of inputs that were filled and not necessarily the particular input that was filled.
Hence JSFiddle:
#div_1, #div_2, #div_3{
display: none;
}
<input type="text" id="text_1" name="text1" value="" />
<input type="text" id="text_2" name="text2" value=""/>
<input type="text" id="text_3" name="text3" value="" />
<div id="div_1">Only ONE input is filled</div>
<div id="div_2">Only TWO inputs are filled</div>
<div id="div_3">All THREE inputs are filled</div>
$(document).ready(function() {
$("input[id*='text']").blur(function() {
var counter=0;
$("input[id*='text']").each(function(ind, val){
if($(val).val().trim()!==""){
counter++;
}
});
$("#div_1, #div_2, #div_3").hide();
$("#div_"+counter).show();
});
});
But if you want it the other way round, here is the solution too:
#div_1, #div_2, #div_3{
display: none;
}
<input type="text" id="text_1" name="text1" value="" />
<input type="text" id="text_2" name="text2" value=""/>
<input type="text" id="text_3" name="text3" value="" />
<div id="div_1">Input ONE is filled</div>
<div id="div_2">Input TWO is filled</div>
<div id="div_3">Input THREE is filled</div>
$(document).ready(function() {
$("input[id*='text']").blur(function() {
$("#div_1, #div_2, #div_3").hide();
$("input[id*='text']").each(function(ind, val) {
if ($(val).val().trim() !== "") {
console.log("div_"+$(val).prop("id").split("_")[1])
$("#div_"+$(val).prop("id").split("_")[1]).show();
}
});
});
});

Related

jQuery, how to set inputs are required notifications for more than one input

Let's say I have 3 inputs, two of which are required, so I want to add a class (invalid) for each required input and show the label text below that this field is required if it is empty or empty by user (on change )
<input type="text" name="name" id="name" class="requiredfiled">
<div class="error_required s-help-block cart_hidden">
<label style="color: #fb6100;">Name is required</label>
</div>
<input type="text" name="phone" id="phone" class="requiredfiled">
<div class="error_required s-help-block hidden">
<label style="color: #fb6100;">Phone is required</label>
</div>
<input type="text" name="address" id="address" class="">
I tried this code but not worked with me
$(".requiredfiled").change(function() {
$('input[type="text"]').each(function() {
if ($(this).val() == "" && $(this).hasClass("requiredfiled")) {
$(this).addClass("invalid");
$(".error_required").removeClass("hidden");
} else {
$(this).removeClass("invalid");
$(".error_required").addClass("hidden");
}
});
});
You can try this logic:
No need to loop through all required text fields as you're already inside one text field during change event.
No need to use $(this).hasClass('requiredfiled') as you are already running the event handler on that selector. So, the input already has that class otherwise event won't have fired.
You can use keyup event for better effect & validation.
You can just transverse the next error_required after current text field using $(this).next('.error_required')
You can use .toggleClass(className, state) syntax to minimise the code.
DEMO HERE:
$('.requiredfiled').keyup(function() {
$(this).toggleClass('invalid', $(this).val() == "");
$(this).next('.error_required').toggleClass('hidden', $(this).val() != "");
});
$('#updateaddress').click(function() {
// Check if all required fields have some valid text
var isFilled = $('.requiredfiled').filter(function () {
return $.trim($(this).val()).length == 0
}).length === 0;
if(isFilled){
alert('Address was saved successfully!')
} else {
// Show the validation error in UI to inform the users
$('.requiredfiled').each(function() {
$(this).toggleClass('invalid', $(this).val() == "");
$(this).next('.error_required').toggleClass('hidden', $(this).val() != "");
});
alert('Please enter the required fields!')
}
});
.hidden {display: none}
.invalid {border: 2px solid red}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="name" id="name" class="requiredfiled" placeholder="Name"/>
<div class="error_required s-help-block hidden">
<label style="color: #fb6100;">Name is required</label>
</div>
<br>
<input type="text" name="phone" id="phone" class="requiredfiled" placeholder="Phone"/>
<div class="error_required s-help-block hidden">
<label style="color: #fb6100;">Phone is required</label>
</div>
<br><br>
<input type="text" name="address" id="address" class="" placeholder="Address" />
<br><br>
<button type="button" id="updateaddress">Update</button>
I've changed $('.error_required') to $(this).next('.error_required') so we can select the correct .error_required after the input field.
Working demo
$('.requiredfiled').change(function() {
$('input[type="text"]').each(function() {
if (($(this).val() == "") && ($(this).hasClass('requiredfiled'))) {
$(this).addClass('invalid');
$(this).next('.error_required').removeClass('hidden');
} else {
$(this).removeClass('invalid');
$(this).next('.error_required').addClass('hidden');
}
});
});
.hidden{visibility: hidden;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="name" id="name" class="requiredfiled">
<div class="error_required s-help-block cart_hidden ">
<label style="color: #fb6100;">Name is required</label>
</div>
<input type="text" name="phone" id="phone" class="requiredfiled">
<div class="error_required s-help-block">
<label style="color: #fb6100;">Phone is required</label>
</div>
<input type="text" name="address" id="address" class="">
Here is the html code
<div class="error_required s-help-block name_error">
<label style="color: #fb6100;">Name is required</label>
</div>
<input type="text" name="phone" id="phone" class="requiredfiled">
<div class="error_required s-help-block phone_error">
<label style="color: #fb6100;">Phone is required</label>
</div>
<input type="text" name="address" id="address" class="">
Here is the Jquery Code
$(document).ready(function(){
$(".requiredfiled").on("input", function(){
if ($("#name").val().length > 0) {
$(".name_error").css("visibility", "hidden");
} else if ($("#name").val().length == 0) {
$(".name_error").css("visibility", "visible");
$("#name").addClass("invalid");
}
if ($("#phone").val().length > 0) {
$(".phone_error").css("visibility", "hidden");
} else if ($("#phone").val().length == 0) {
$(".phone_error").css("visibility", "visible");
$("#phone").addClass("invalid");
}
});
});
CSS for invalid input field
.invalid {
border: 2px solid red;
}
What we are doing here is detecting the input change using $(".requiredfiled").on("input", function() then we detect the length of the input field and based on that we can perform any action. Here i have changed the visibility of the error message. When the input field will be empty the error message will appear.

JS - Change the text depending on the user's input

First of all, sorry if the question seems really dumb, I'm not really used to Javascript.
I'm looking for a script changing some text depending on what the user wrote. Here's what I'm looking for :
There is 3 inputs (A, B and C) for 1 Text.
The "Text" will show the addition of A, B and C.
Example : Input A is 3, B is 5, C is 10. Text = 18.
I got some script ready, but it's only the "bones" of the script..
function ShowPointsNeeded(text){
document.getElementById("result").innerHTML =text; }
#result {
height:50px;
width:50px;
border:1px solid #999;
font-size:25px;
text-align:center;
margin-left:15px;
}
<div id="text">
<input id="slide" type="text" value=""
onchange="ShowPointsNeeded(this.value);" />
</div>
<div id="result"></div>
-> It's just a basic script, showing the content of the input in a little box. Now, what I would like to have is 3 inputs and the little box to show the addition of them.
Thanks !
If want to calculate sum, of all inputs then you can use below logic :
function ShowPointsNeeded(){
//while doing calculation you have to consider all textboxes every time,
//so you have to derive a way to get all your related textboxes at once,
//e.g. : i have use name attribute to make all input boxes relate to each
//other.
var allInputs = document.getElementsByName("numbers");
var sum=0.0;
for(var i=0;i<allInputs.length;i++){
if(allInputs[i].value.length>0)
sum= sum+parseFloat(allInputs[i].value);
//parsing float because user can input decimals as well
}
document.getElementById("result").innerHTML=sum;
}
<div id="text">
<input id="slide" type="text" value="" name="numbers"
onchange="ShowPointsNeeded();" />
<input id="slide" type="text" value="" name="numbers"
onchange="ShowPointsNeeded();" />
<input id="slide" type="text" value="" name="numbers"
onchange="ShowPointsNeeded();" />
</div>
<div id="result" style="height:50px;width:50px;border:1px solid #999; font-size:25px; text-align:center; margin-left:15px;"></div>
you will need to sum all input values every time ShowPointsNeeded() is called. you can use reduce() for this.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function ShowPointsNeeded(){
document.getElementById("result").innerHTML = $('input').toArray().reduce((acc,cur) => acc + Number(cur.value), 0);
}
</script>
<div id="text">
<input id="slide1" type="text" value=""
onchange="ShowPointsNeeded();" />
<input id="slide2" type="text" value=""
onchange="ShowPointsNeeded();" />
<input id="slide3" type="text" value=""
onchange="ShowPointsNeeded();" />
</div>
<div id="result" style="height:50px;width:50px;border:1px solid #999; font-size:25px; text-align:center; margin-left:15px;"></div>
JavaScript Number() function for convert from text to number:
function ShowPointsNeeded() {
var values = [];
var elements = document.getElementsByTagName('input');
for (var i = 0; i < elements.length; i++) {
values.push(elements[i].value);
}
var sum = values.reduce(sumElements, 0);
var resultElement = document.getElementById("result");
resultElement.innerHTML = sum;
}
function sumElements(total, num) {
return Number(total) + Number(num);
}
<div id="text">
<input type="text" value="" onchange="ShowPointsNeeded(this);" />
<input type="text" value="" onchange="ShowPointsNeeded(this);" />
<input type="text" value="" onchange="ShowPointsNeeded(this);" />
</div>
<div id="result" style="height:50px;width:50px;border:1px solid #999; font-size:25px; text-align:center; margin-left:15px;"></div>
For inputs don't needs id attribute.

Using DOM to create an input

I currently have been working on this code and I can't seem to figure it out. I am planning to make it so that if the radio button is pressed that shipping is not free, that an input field pops up to specifying what the addition cost will be using DOM. I am also trying to figure out how to add text to describe the input field, and to validate the input field.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
function myFunction() {
var x = document.createElement("INPUT");
var c = 1;
if (c = 1) {
x.setAttribute("type", "text");
var sp2 = document.getElementById("emailP");
// var br = document.createElement("br");
// sp2.appendChild(br);
// alert("added break");
var sp2 = document.getElementById("emailP");
var parentDiv = sp2.parentNode;
parentDiv.insertBefore(x, sp2);
c++;
alert("Added Text Box");
}
}
</script>
<form action="#" method="post" onsubmit="alert('Your form has been submitted.'); return false;">
<p class="boldParagraph">Upload an Image:</p>
<input type="file" id="pic" accept="image/*" required>
<p class="boldParagraph">Name of seller:</p>
<input class="averageTextBox" type="text" id="seller" value="" required>
<p class="boldParagraph" id = "tip3P">Shipping costs are free:</p>
<input type="radio" name="tip3" value="3" checked /> Yes
<input type="radio" name="tip3" value="4" onclick="myFunction(); this.onclick=null;"/> No
<p class="boldParagraph" id = "emailP">Email of seller:</p>
<input class="averageTextBox" type="email" id="emailAddress" value="" required>
<p class="boldParagraph">Closing date for auction:</p>
<input type="date" id="closeDate" value="" required>
<br><br>
<button>Submit</button>
</form>
</body>
</html>
Create a label element and populate text using innerHTML. and then append to DOM.
Example Snippet:
function myFunction() {
var label = document.createElement("label");
label.innerHTML = "<br>Shipment Cost : ";
var x = document.createElement("INPUT");
var c = 1;
if (c = 1) {
x.setAttribute("type", "text");
var sp2 = document.getElementById("emailP");
// var br = document.createElement("br");
// sp2.appendChild(br);
// alert("added break");
var sp2 = document.getElementById("emailP");
var parentDiv = sp2.parentNode;
parentDiv.insertBefore(x, sp2);
parentDiv.insertBefore(label, x);
c++;
alert("Added Text Box");
}
}
<form action="#" method="post" onsubmit="alert('Your form has been submitted.'); return false;">
<p class="boldParagraph">Upload an Image:</p>
<input type="file" id="pic" accept="image/*" required>
<p class="boldParagraph">Name of seller:</p>
<input class="averageTextBox" type="text" id="seller" value="" required>
<p class="boldParagraph" id="tip3P">Shipping costs are free:</p>
<input type="radio" name="tip3" value="3" checked />Yes
<input type="radio" name="tip3" value="4" onclick="myFunction(); this.onclick=null;" />No
<p class="boldParagraph" id="emailP">Email of seller:</p>
<input class="averageTextBox" type="email" id="emailAddress" value="" required>
<p class="boldParagraph">Closing date for auction:</p>
<input type="date" id="closeDate" value="" required>
<br>
<br>
<button>Submit</button>
</form>
OR
You can keep the text box hidden and show it when user clicks no. Also, apply validations only when no is selected for shipment radio button.
I suggest use jQuery, see the snippet below:
jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript.
var radioButtons = $("[name=tip3]");
radioButtons.on("change", function() {
if ($("[name=tip3]:checked").val() == "3") {
$("#shipmentDetail").hide();
} else {
$("#shipmentDetail").show();
}
})
$("#submit").on("click", function() {
var flag = true;
if ($("[name=tip3]:checked").val() == "4") {
if ($("#shipmentDetail").val() == "") {
flag = false;
alert("enter some value");
}
}
//other validations here
if (flag) {
$("#form").submit()
}
})
#shipmentDetail {
display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form" action="#" method="post">
<p class="boldParagraph">Upload an Image:</p>
<input type="file" id="pic" accept="image/*" required>
<p class="boldParagraph">Name of seller:</p>
<input class="averageTextBox" type="text" id="seller" value="" required>
<p class="boldParagraph" id="tip3P">Shipping costs are free:</p>
<input type="radio" name="tip3" value="3" checked />Yes
<input type="radio" name="tip3" value="4" />No
<label id="shipmentDetail" for="price">Shipment Cost:
<input id="price" type="text" value="" />
</label>
<p class="boldParagraph" id="emailP">Email of seller:</p>
<input class="averageTextBox" type="email" id="emailAddress" value="" required>
<p class="boldParagraph">Closing date for auction:</p>
<input type="date" id="closeDate" value="" required>
<br>
<br>
<button id="submit">Submit</button>
</form>
replace
alert("Added Text Box");
with:
var additional_fees = prompt("Type in");
x.setAttribute("value", additional_fees)

How to show form fields on keyup

I've been working on this for weeks now and I can't seem to get the hang of this. I'm trying to show the hidden fields only when the previous fields are entered. Here's my example code:
HTML
<form>
<div id="group1">
<label>Field 1:</label>
<input type="text" class="field1" />
<br/>
<label>Field 2:</label>
<input type="text" class="field2" />
<br/>
<label>Field 3:</label>
<input type="text" class="field3" />
<br/>
</div>
<div id="group2">
<label>Field 4:</label>
<input type="text" class="field4" />
<br/>
<label>Field 5:</label>
<input type="text" class="field5" />
<br/>
<label>Field 6:</label>
<input type="text" class="field6" />
<br/>
</div>
<div id="group3">
<label>Field 7:</label>
<input type="text" class="field7" />
<br/>
<label>Field 8:</label>
<input type="text" class="field8" />
<br/>
<label>Field 9:</label>
<input type="text" class="field9" />
<br/>
<input type="submit" value="Submit">
</div>
</form>
CSS
#group2 {
visibility: hidden;
}
#group3 {
visibility: hidden;
}
Script
$(document).ready(function () {
$('#group1').find('input[type="text"]').keyup(function () {
CheckSubmit();
});
function CheckSubmit() {
var x = true;
$('#group1').find('input[type="text"]').keyup(function () {
if ($(this).val().length === 0) {
x = false;
return;
}
});
if (x) {
$('#group2').css('visibility', 'visible');
$('#group3').css('visibility', 'visible');
} else {
$('#group2').css('visibility', 'hidden');
$('#group3').css('visibility', 'hidden');
}
CheckSubmit();
});
I'm not sure what I'm doing wrong here. Can someone please assist?
I changed your code a bit. I stored the relevant selectors in variables, so you don't need to do a lot of re-querying every time something changes.
Here's the updated code:
JavaScript
var inputs = $('#group1').find('input[type="text"]');
var hidden = $('#group2, #group3');
inputs.keyup(function() {
var test = true;
inputs.each(function(key, value) {
if (!$(this).val().length) {
test = false;
return false;
}
});
hidden.css('visibility', ( test ? 'visible' : 'hidden' ) );
});
Demo
Try before buy
You can make this more dynamic by checking the inputs in the current div and if they all have a value, then show the next div (if there is one).
If they clear a value, then hide all the later divs.
$(document).ready(function() {
// you can restrict this to inputs in a specific div or just any input
$('#group1 input').on('keyup', function () {
var parentDiv = $(this).closest('div')
var hasValues = parentDiv.find('input').filter(function() {
return this.value == '';
}).length == 0;
if(hasValues) {
//parentDiv.next().css('visibility', 'visible'); // show just the next section
parentDiv.nextAll().css('visibility', 'visible'); // show all later sections
} else {
parentDiv.nextAll().css('visibility', 'hidden');
}
});
});
DEMO
I made a quick pen with a solution. It may not be the prettiest but it get's it done. Basically on every keyup event I check #group1's children for their value length and if they all have a length that's more than 0 I change a flag in an array. If all 3 flags are true I show #group2.
Here's the pen
$('#group2').hide();
$('#group3').hide();
$('#group1').keyup(function() {
var flags = {
0: false,
1: false,
2: false
}
$('#group1 > input').each(function(i, ele) {
if(ele.value.length !== 0)
{
flags[i] = true;
}
});
if(flags[0] && flags[1] && flags[2])
{
$('#group2').show();
}
});
$('#group2').keyup(function() {
var flags = {
0: false,
1: false,
2: false
}
$('#group2 > input').each(function(i, ele) {
if(ele.value.length !== 0)
{
flags[i] = true;
}
});
if(flags[0] && flags[1] && flags[2])
{
$('#group3').show();
}
});
Hope it helps :D
If I understand your question well, you want to show the fields in #group2/-3 if all the fields in the previous fields have a value. Using a few data-*-attributes (see MDN), you can create a handler like this (if you prefer: jsFiddle, containing a more complete example):
$('[data-nextgroup] [type=text]').on('keyup', function (e){
var fieldgroup = $(this.getAttribute('data-group'))
,fields = fieldgroup.find('[type=text]')
,canshow = fields.length ===
fields.filter( function (i,el) { return el.value.length; } ).length;
void( canshow && $(fieldgroup.attr('data-nextgroup')).fadeIn() );
});
[data-hidden] {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="group1" data-nextgroup="#group2">
<label>Field 1:</label>
<input type="text" class="field1" data-group="#group1"/>
<br/>
<label>Field 2:</label>
<input type="text" class="field2" data-group="#group1"/>
<br/>
<label>Field 3:</label>
<input type="text" class="field3" data-group="#group1"/>
<br/>
</div>
<div id="group2" data-nextgroup="#group3" data-hidden>
<label>Field 4:</label>
<input type="text" class="field4" data-group="#group2"/>
<br/>
<label>Field 5:</label>
<input type="text" class="field5" data-group="#group2"/>
<br/>
<label>Field 6:</label>
<input type="text" class="field6" data-group="#group2"/>
<br/>
</div>
<div id="group3" data-groups data-hidden>
<label>Field 7:</label>
<input type="text" class="field7" />
<br/>
<label>Field 8:</label>
<input type="text" class="field8" />
<br/>
<label>Field 8:</label>
<input type="text" class="field9" />
<br/>
<input type="submit" value="Submit">
</div>

Validate multiple input values trough regular expression doesn't work

I'm trying to validate more than one input field by checking first if it's empty and then if it's a numeric non zero value. This is the HTML code:
<section style="" id="variations_holder">
<div class="con_var">
<input type="text" class="pupc" name="variation[pupc][]">
<input type="text" class="pprice" name="variation[pprice][]">
<input type="text" class="pqty" name="variation[pqty][]">
<input type="text" class="pupc" name="variation[pupc][]">
<input type="text" class="pprice" name="variation[pprice][]">
<input type="text" class="pqty" name="variation[pqty][]">
</div>
</section>
Right now there are only two set of input but can be three or more for example:
<section style="" id="variations_holder">
<div class="con_var">
<input type="text" class="pupc" name="variation[pupc][]">
<input type="text" class="pprice" name="variation[pprice][]">
<input type="text" class="pqty" name="variation[pqty][]">
<input type="text" class="pupc" name="variation[pupc][]">
<input type="text" class="pprice" name="variation[pprice][]">
<input type="text" class="pqty" name="variation[pqty][]">
<input type="text" class="pupc" name="variation[pupc][]">
<input type="text" class="pprice" name="variation[pprice][]">
<input type="text" class="pqty" name="variation[pqty][]">
</div>
</section>
Since they are generated dinamically. Now this is the jQuery code I made to validate what I said before:
$('#variations_holder input.pprice').each(function() {
pprice = $(this).val();
if (!$.trim(this.value).length) {
alert($(this).prev('label').text() + ' no se puede dejar vacío!!!');
$(this).focus();
is_valid = false;
return false;
}
if (pprice.match('^[1-9]\d*$') === false) {
pprice.addClass('error');
}
});
But it's not working for the following reasons:
Only check for first field and not for the rest
Doesn't check for regular expression since validation pass even if I write letters instead of numbers
What is wrong?
The return you do returns from the callback you pass to each and, as you return false, it breaks the loop.
match never returns false. Use test instead.
you try to add a class to pprice, which is a string.
You can fix that like this :
var is_valid = true;
$('#variations_holder input.pprice').each(function() {
pprice = $.trim(this.value);
if (!pprice.length) {
alert($(this).prev('label').text() + ' no se puede dejar vacío!!!');
$(this).focus();
is_valid = false;
} else if (!/^[1-9]\d*$/.test(pprice)) {
$(this).addClass('error');
is_valid = false;
}
});

Categories