Validate multiple input values trough regular expression doesn't work - javascript

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;
}
});

Related

Form not submitting its values on console

I'm attempting to build an object of the input values in the form below, then log that object to the console; but it the values are not being retrieved properly.
What is wrong with my code?
document.getElementById('myForm').addEventListener('submit', contactPerson);
function contactPerson(e) {
var personName = document.getElementsByClassName('personName').value;
var personEmail = document.getElementsByClassName('personEmail').value;
var personMessage = document.getElementsByClassName('personMessage').value;
var contact = {
name: personName,
email: personEmail,
message: personMessage
}
console.log(contact);
e.preventDefault();
}
<form id="myForm">
<label for="inputHorizontalSuccess">Name</label>
<input type="text" class="form-control form-control-success" id="inputHorizontalSuccess" class="personName" placeholder="Name"><br>
<label for="inputHorizontalSuccess">Email</label>
<input type="email" class="form-control form-control-success" id="inputHorizontalSuccess" class="personEmail" placeholder="name#example.com"><br>
<label for="inputHorizontalSuccess">Message</label>
<input type="text" class="form-control form-control-success" id="inputHorizontalSuccess" class="personMessage" placeholder="Your Message"><br>
<button type="submit">Submit</button>
</form>
You have multiple Ids:
<input type="text" class="form-control form-control-success" id="inputHorizontalSuccess" id="personName" placeholder="Name">
You can either remove inputHorizontalSuccess.
Or add a name and get value from it instead, incase you must have inputHorizontalSuccess.
This should do it:
<input type="text" class="form-control form-control-success" id="inputHorizontalSuccess1" name="personName" placeholder="Name">
<input type="email" class="form-control form-control-success" id="inputHorizontalSuccess2" name="personEmail" placeholder="name#example.com">
<input type="text" class="form-control form-control-success" id="inputHorizontalSuccess3" name="personMessage" placeholder="Your Message">
var personName = document.querySelector('[name="personName"]').value;
var personEmail = document.querySelector('[name="personEmail"]').value;
var personMessage = document.querySelector('[name="personMessage"]').value;
I recommend you read this question on how to get value from the DOM.
How do I get the value of text input field using JavaScript?
Only the first class attribute in an element definition is applied. This means that when you write the following:
<input type="text" class="form-control form-control-success" ... class="personName" placeholder="Name">
The later "class" attribute will not apply. This means that the element cannot be selected by this class.
Document.getElementsByClassName returns a live HTMLCollection even if there is only a single element. This means that when you write:
var personName = document.getElementsByClassName('personName').value;
There is no value property in the live HTMLCollection returned by the call to Document.getElementsByClassName, so it will return undefined.
document.getElementById('myForm').addEventListener('submit', contactPerson);
function contactPerson(e) {
var personName = document.getElementsByClassName('personName')[0].value;
var personEmail = document.getElementsByClassName('personEmail')[0].value;
var personMessage = document.getElementsByClassName('personMessage')[0].value;
var contact = {
name: personName,
email: personEmail,
message: personMessage
}
console.log(contact);
e.preventDefault();
}
<form id="myForm">
<label for="inputHorizontalSuccess">Name</label>
<input type="text" class="form-control form-control-success personName" id="inputHorizontalSuccess" placeholder="Name"><br>
<label for="inputHorizontalSuccess">Email</label>
<input type="email" class="form-control form-control-success personEmail" id="inputHorizontalSuccess" placeholder="name#example.com"><br>
<label for="inputHorizontalSuccess">Message</label>
<input type="text" class="form-control form-control-success personMessage" id="inputHorizontalSuccess" placeholder="Your Message"><br>
<button type="submit">Submit</button>
</form>
However, you should probably use ID's instead of classes and Element#querySelector, to avoid conflict:
document.getElementById('myForm').addEventListener('submit', contactPerson);
function contactPerson(e) {
var personName = document.querySelector('#personName').value;
var personEmail = document.querySelector('#personEmail').value;
var personMessage = document.querySelector('#personMessage').value;
var contact = {
name: personName,
email: personEmail,
message: personMessage
}
console.log(contact);
e.preventDefault();
}
<form id="myForm">
<label for="inputHorizontalSuccess">Name</label>
<input type="text" class="form-control form-control-success" id="personName" placeholder="Name"><br>
<label for="inputHorizontalSuccess">Email</label>
<input type="email" class="form-control form-control-success" id="personEmail" placeholder="name#example.com"><br>
<label for="inputHorizontalSuccess">Message</label>
<input type="text" class="form-control form-control-success" id="personMessage" placeholder="Your Message"><br>
<button type="submit">Submit</button>
</form>

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>

Check if input text is filled and display different divs

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();
}
});
});
});

Change input type with javascript and chechbox, how to?

I would like to create a registration form with hide-able and revealable password input. I tried this (JS):
function showhide(melyik,hol) {
var melyiket = document.getElementById(melyik);
var melyikkel = document.getElementById(hol);
if (melyikkel.value == '1') {
document.getElementById(melyikkel).value='0';
document.getElementById(melyiket).type='password';
} else {
document.getElementById(melyikkel).value='1';
document.getElementById(melyiket).type='text';
}
}
Form:
<div style="margin-top:20px;">
<p>SQL host: <input type="text" name="sql_host" value="localhost"/></p>
<p>SQL adatbázis: <input type="text" name="sql_db"/></p>
<p>SQL felhasználó: <input type="text" name="sql_user"/></p>
<p>SQL jelszó: <input type="text" name="sql_password" id="sql_password"/>
<input type="checkbox" name="show_password_1" id="show_password_1" value="0" onclick="showhide('sql_password','show_password_1');">
</p>
</div>
I want to do this:
If checkbox is checked the password input type is text. When not checked the password type is password... I wrote this JavaScript, but not working. :-(
Use .checked to see if the checkbox is selected, not value. Here's a working example.
HTML:
<input type="password" name="pwd" id="pwd" />
<input type="checkbox" name="show" id="show" onclick="showhide('pwd','show');">​
JS:
function showhide(pwd,show)
{
var epwd = document.getElementById(pwd);
var eshow = document.getElementById(show);
epwd.type = eshow.checked ? 'text' : 'password';
}​

Categories