Show hidden input javascript/jquery - javascript

Why is the hidden form not shown when it looses focus? The alert is coming up nicely when leaving the input but the other hidden form is still not there.
html
<body>
<input type="text" id="myinput" value="">
<input type="hidden" id="validation_message_email" value="enter a valid email">
</body>
javascript
window.onload = function() {
$("#myinput").blur(myAlert);
};
function myAlert() {
alert("This input field has lost its focus.");
$("#validation_message_email").show();
}

You can't display a hidden input like that.A span will suit better for this purpose,
<input type="text" id="myinput" value="">
<span style="display:none" id="validation_message_email">enter a valid email</span>

validation_message_email doesn't have its display style property as none, so show() will not make it visible from type="hidden".
You need to replace
$("#validation_message_email").show();
with
$("#validation_message_email").attr( "type", "text" );
However, if the intent is to only show a message, then you don't need to use a hidden input for the same.
<body>
<input type="text" id="myinput" value="">
</body>
and
window.onload = function() {
$("#myinput").blur(function(){
alert("This input field has lost its focus.");
$(this).append('<span id="emailValidationMessage">enter a valid email</span>')
});
$("#myinput").focus(function(){
$("#emailValidationMessage").remove();
});
};

No need to use type="hidden" as hidden elements are not display:none they are hidden by default.
Use type="text" and hide it with css and show where you want
<input type="text" id="myinput" value="" style="display:none;">

use like this
<input type="text" id="myinput" value="">
<input type="hidden" id="validation_message_email" value="enter a valid email">
<script>
window.onload = function() {
$("#myinput").blur(myAlert);
};
function myAlert() {
$("#validation_message_email").attr("type","text");
}
</script>

<div class="form-group" id="usernamediv">
<input class="form-control" name="username" id="username"
placeholder="Username" type="text" required=""> </div>
<div class="form-group" id="passworddiv">
<input name="password" class="form-control" id="password" placeholder="Password" type="password" required="">
</div>
<button id="#loginButton">Login</button>
<button id="#forgotpassword">Forgot Password</button>
<script>
$("#forgotpassword").hide();
$("#forgotpassword").click(function(e){
$("#loginButton").hide();
$("#usernamediv").show();
$("#passworddiv").hide();
})
</script>

Check this jsfiddle link, it might help you.
$("#myinput").blur( function(){
myAlert();
});
function myAlert() {
$("#validation_message_email").attr("type", "text");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<input type="text" id="myinput" value="">
<input type="hidden" id="validation_message_email" value="enter a valid email">

Related

compare the value of two form email fields

I have created a form requiring email validation. So user must type in their email address twice and if they don't match they won't be able to submit. I did this by simply comparing the values of email fields 1 and 2. If they match "disabled" is removed from the submit button.
All was working perfectly when I had the value set to "Insert your email address and "confirm your email address again". However, so that the user does not have to delete that text, I removed the value and used "placeholder" in the HTML instead.
The problem now is that the moment you type anything it's returning as true. I guess it's seeing the blank values as the same, but it's not picking up on the changes to the value as the user types it in.
Why are the two fields always returning as a match?
<html>
<body>
<form class="theForm">
<p> Subscribe to my mailing list</p>
<input type="text" id="name" class="fields" name="name" placeholder="Name">
<input type="text" id="email1" class="fields" name="email" placeholder="Email Address" >
<input type="text" id="email2" class="fields" placeholder="Confirm Email Address" >
<input name="submit" id="submit" class="fields" type="submit" disabled value="Email Addresses
Do Not Match">
</form>
<script>
function verify (){
console.log(`email1.value: ${email1}: Email2: ${email2}`);
if(document.getElementById("email1").value === document.getElementById("email2").value) {
document.getElementById("submit").removeAttribute("disabled");
document.getElementById("submit").style.backgroundColor = "#004580";
document.getElementById("submit").style.cursor = "pointer";
} else {
document.getElementById("submit").setAttribute("disabled", "disabled");
}
}
$(".fields").on("change paste keyup", verify);
</script>
</body>
</html>
try this
<html>
<body>
<form class="theForm">
<p> Subscribe to my mailing list</p>
<input type="text" id="name" class="fields" name="name" placeholder="Name">
<input type="text" id="email1" class="fields" name="email" placeholder="Email Address" >
<input type="text" id="email2" class="fields" placeholder="Confirm Email Address" >
<input id="submit" type="button" onclick="verify()" value="click">
</form>
<script>
function verify()
{
if(document.getElementById("email1").value === document.getElementById("email2").value) {
alert("matched")
} else {
document.getElementById("submit").setAttribute("disabled", "disabled");
alert("not matched")
}
}
</script>
</body>
</html>
This worked for me:
Change the email inputs to [type='email'].
Add the required attribute to #email1.
Add a check to the validity of #email1 in your conditional.
Reset styles to initial (or what you prefer) if the button is reset back to 'disabled'.
Use 'input' event to get the the values updating on every keystroke, 'change' only fires on 'blur' or when the form is submitted.
It'd end up looking like this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
<form class="theForm">
<p> Subscribe to my mailing list</p>
<input type="text" id="name" class="fields" name="name" placeholder="Name">
<input type="email" id="email1" class="fields" name="email" placeholder="Email Address" required>
<input type="email" id="email2" class="fields" placeholder="Confirm Email Address" >
<input name="submit" id="submit" class="fields" type="submit" disabled value="Email Addresses Do Not Match">
</form>
<script>
function verify (){
console.log(`email1: ${email1.value}: Email2: ${email2.value}`);
if(document.getElementById("email1").checkValidity() && document.getElementById("email1").value === document.getElementById("email2").value) {
document.getElementById("submit").removeAttribute("disabled");
document.getElementById("submit").style.backgroundColor = "#004580";
document.getElementById("submit").style.cursor = "pointer";
} else {
document.getElementById("submit").setAttribute("disabled", "disabled");
document.getElementById("submit").style.backgroundColor = "initial";
document.getElementById("submit").style.cursor = "initial";
}
}
$(".theForm").on("input paste keyup", "input[type=email]", verify);
</script>
</body>
</html>
MDN Docs for input and change events:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event
Instead of:
$(".fields").on("change paste keyup", verify)
Try:
$(".fields").blur(verify)
EDIT:
How about:
$("#email2").blur(verify)
?

add dynamically generated fields from form

Hi guys i want to dynamically add a group of input fields when a button is pressed. This works with 1 group, but not with more than one. Here is my HTML:
<form action="address.php" method="POST">
<div id="list">
<input type="text" name="address" placeholder="Address">
<input type="text" name="suburb" placeholder="Suburb">
<input type="text" name="state" placeholder="State">
<input type="text" name="country" placeholder="Country">
<button id="addMore">Add Address</button>
</div>
</form>
I'm calling the addMore function with this javascript:
$(function(){
$("#addMore").click(function(e){
e.preventDefault();
$("#list").append("<input type="text" name="address" placeholder="Address"><input type="text" name="suburb" placeholder="Suburb"><input type="text" name="state" placeholder="State"><input type="text" name="country" placeholder="Country"><button id="addMore2">Add Address</button></div>");
});
});
I've added a button at the end with an id of addMore2 because i wanna generate a similar set of input controls but with different names. I want to call that id with this function:
$(function(){
$("#addMore2").click(function(e){
e.preventDefault();
$("#list").append("<input type="text" name="address2" placeholder="Address"><input type="text" name="suburb2" placeholder="Suburb"><input type="text" name="state2" placeholder="State"><input type="text" name="country2" placeholder="Country"><button id="addMore3">Add Address</button></div>");
});
});
... and then another set of controls with the function addMore3. Same as above, but with the number 3.
If i use each function alone, it works. But if i try to use all 3 together, it doesn't work. How can i dynamically reproduce a set of input controls with different names?
you could do something like this
$(var count = 0;
$("#addMore2").click(function(e){
e.preventDefault();
$("#list").append("<input type='text' name='address2'"+count+" placeholder="Address"><input type="text" name='suburb2'"+count+" placeholder="Suburb"><input type="text" name='state2'"+count+" placeholder="State"><input type="text" name='country2'"+count+" placeholder="Country"><button id='addMore3'"+count+">Add Address</button></div>");
count++;
});
});
#rayzor
You need to append your code before button
Please use below code:
jQuery("#addMore").click(function(e){
jQuery('<br><input type="text" name="address" placeholder="Address"><input type="text" name="suburb" placeholder="Suburb"><input type="text" name="state" placeholder="State"><input type="text" name="country" placeholder="Country">').insertAfter("input:last");
return false;
});
And remove code for $("#addMore2").click event
There's no need to add Addmore 2,3,etc manually. the js will add it automatically, as much as your want. Feel free to see this one: https://phppot.com/jquery/jquery-ajax-inline-crud-with-php/

Add multiple fields to form

I would like to add a function that generates multiple fields to my form.
This is how my form looks like:
<form action="form_sent.php" method="post">
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
<button>Add more fields</button><br><br>
<input type="submit">
</form>
In my case I want 3 new fields (name, phone, email) when clicking on "Add more fields".
How can I do this?
https://jsfiddle.net/374cxt5s/
Try this: https://jsfiddle.net/Twisty/q8zj00s0/1/
HTML
<form action="form_sent.php" method="post">
<ul id="fieldList">
<li>
<input name="name[]" type="text" placeholder="Name" />
</li>
<li>
<input name="phone[]" type="text" placeholder="Phone" />
</li>
<li>
<input name="email[]" type="text" placeholder="E-Mail">
</li>
</ul>
<button id="addMore">Add more fields</button>
<br>
<br>
<input type="submit">
</form>
CSS
ul {
padding: 0;
margin: 0;
}
ul li {
list-style: none;
}
JQuery
$(function() {
$("#addMore").click(function(e) {
e.preventDefault();
$("#fieldList").append("<li> </li>");
$("#fieldList").append("<li><input type='text' name='name[]' placeholder='Name' /></li>");
$("#fieldList").append("<li><input type='text' name='phone[]' placeholder='Phone' /></li>");
$("#fieldList").append("<li><input type='text' name='email[]' placeholder='E-Mail' /></li>");
});
});
This allows you to store the results in array when you submit the form. Since you could have 5 names, phones, and emails, an array is the best way to address that. Then in PHP, you would have $_POST['name'][0] as the first one.
I'm assuming you probably want to create a dynamic form that allows you to add multiple contacts, etc.
CodePen Example
http://codepen.io/anon/pen/yeVRgw
The Basic HTML Setup
So that you can loop through things, and for sake of your own sanity, you'll probably want to segment out each chunk within the form. We'll also set up a hidden input to track how many partitions of name,phone,email have been created. We'll default at 1
<form action="form_sent.php" method="POST">
<input type="hidden" name="contacts" id="contacts" value="1">
<div class="form-contacts-container">
<div class="form-contact" id="form-contact-1">
<input type="text" name="name-1" id="name-1" placeholder="Name">
<input type="text" name="email-1" id="email-1" placeholder="E-mail">
<input type="text" name="phone-1" id="phone-1" placeholder="Phone">
</div>
<!-- We'll be adding additional inputs here -->
</div>
<div class="form-contacts-add">
<input type="button" value="Add More Fields" id="add-fields">
</div>
<div class="form-contacts-submit">
<input type="submit" name="submit" id="submit" value="Submit">
</div>
</form>
The JavaScript
This assumes you are using jQuery, so ensure that this is in your <head>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
Now we need to do a few things - firstly, attach an event listener to our button and secondly, add a new <div class="form-contact"> with included fields to our form. We'll also need to ensure that we're counting up to make sure each section has a unique name/id, and we'll increase the hidden input value to count how many contacts have been added in total.
<script type="text/javascript">
var total = 1; // Our default for how many contacts we have
$( document ).on( 'click', '#add-fields', function() {
var addBlockId = total = total + 1;
var addBlock = document.createElement('div');
$(addBlock).addClass('form-contact');
$(addBlock).attr('id','form-contact-' + addBlockId);
var inputName = document.createElement('input');
$(inputName).attr('type','text');
$(inputName).attr('name','name-' + addBlockId);
$(inputName).attr('id','name-' + addBlockId);
$(inputName).attr('placeholder','Name');
$(inputName).appendTo($(addBlock));
var inputEmail = document.createElement('input');
$(inputEmail).attr('type','text');
$(inputEmail).attr('name','email-' + addBlockId);
$(inputEmail).attr('id','email-' + addBlockId);
$(inputEmail).attr('placeholder','E-mail');
$(inputEmail).appendTo($(addBlock));
var inputPhone = document.createElement('input');
$(inputPhone).attr('type','text');
$(inputPhone).attr('name','phone-' + addBlockId);
$(inputPhone).attr('id','phone-' + addBlockId);
$(inputPhone).attr('placeholder','Phone');
$(inputPhone).appendTo($(addBlock));
$(addBlock).appendTo($('.form-contacts-container'));
$('#contacts').val(total);
});
</script>
Processing your Form
The last piece of the puzzle is to process your form properly. Not goign to give you all the answers here, but the basic logic would be to grab the $_POST['contacts'] value we've been updated and run a loop through to grab all of your inputs and associated values. For instance in PHP:
$total = $_POST['contacts'];
$contacts = array();
for( $i = 1; $i < $total; $i++ ) {
$this_contact = $array(
'Name' => $_POST['name-' . $i],
'Email' => $_POST['email-' . $i],
'Phone' => $_POST['phone-' . $i]
);
array_push($contacts, $this_contact);
}
var_dump( $contacts );
try something like this :
(function() {
var button=document.getElementById("add-user");
button.addEventListener('click', function(event) {
event.preventDefault();
var cln = document.getElementsByClassName("user")[0].cloneNode(true);
document.getElementById("users").insertBefore(cln,this);
return false;
});
})();
<form id="users" action="form_sent.php" method="post">
<div class="user">
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
</div>
<button id='add-user'>Add more fields</button><br><br>
<input type="submit">
</form>
https://jsfiddle.net/9955n4fo/
It might not be a bad idea to wrap your input fields in a div just so when you append the other inputs they appear consecutively. Try something like this in your html
<form action="form_sent.php" method="post">
<div id="fields">
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
</div>
<button>Add more fields</button><br><br>
<input type="submit">
</form>
and then your javascript can be completed as so
$(function() {
$('button').click(function() { addFields(); });
});
function addFields() {
var html = "<input name='name' type='text' placeholder='Name'><br>
<input name='phone' type='text' placeholder='Phone'><br>
<input name='email' type='text' placeholder='E-Mail'><br><br>";
$('#fields').append(html);
}
You need to implement jQuery to change the HTMLs DOM.
So, you add this in your <head></head> tags:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
You need to modify your HTML like this:
<form action="form_sent.php" method="post">
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
<button extra="0">Add more fields</button><br><br>
<input type="submit">
</form>
Then you need to use this jQuery code:
<script>
$("button").on("click",function(){
var extra = $(this).attr("extra") + 1;
$("form").append("<input type='text' placeholder='Other Field' name='field' />");
$(this).attr("extra",extra);
}
</script>
This is the end!! :)
Try This :
Jquery append() function seems to sort out your answer
HTML Code should be as follow :
<form action="form_sent.php" method="post">
<div class = 'xyz'>
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
</div>
<button>Add more fields</button><br><br>
<input type="submit">
</form>
you JS should be as follow :
$(button).click(function(event){
$('.xyz').append("<input type ='text' class ='name' placeholder = 'Enter name'/><br/>");
$('.xyz').append("<input type='text' class='phone' placeholder='Enter phone'/><br/>");
$('.xyz').append("<input type='mail' class='phone' placeholder='Enter e-mail'/><br/>");
event.preventDefault();
});
This is how I would solve it.
HTML:
<form action="form_sent.php" method="post">
<div id="inputHolder">
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
</div>
<button id="addMoreFields">Add more fields</button><br><br>
<input type="submit">
</form>
JS:
$( document ).ready(function() {
$("#addMoreFields").click(function(event) {
event.preventDefault();
$("#inputHolder").append('<input name="name" type="text" placeholder="Name"><br>');
$("#inputHolder").append('<input name="phone" type="text" placeholder="Phone"><br>');
$("#inputHolder").append('<input name="email" type="text" placeholder="E-Mail"><br><br>');
});
});
https://jsfiddle.net/r71odb7t/
First you want to clone the elements you want to be adding. Do that when the page loads. Then when the button is clicked, clone the copy and add a copy to the page. And, you could either add type="button" to the button or use e.preventDefault() so your form does not get submitted when the button is clicked.
$(function() {
var inputs = $('form > button').prev().prev().prevUntil().clone().add('<br><br>');
$('form > button').on('click', function(e) {
e.preventDefault();
$(this).before(inputs.clone());
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="form_sent.php" method="post">
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
<button>Add more fields</button><br><br>
<input type="submit">
</form>

how can i check all form element isn't empty on one function?

<form action="surl.php" method="get" id="surl">
<input type="text" placeholder="name of column" name="column_name"/>
<textarea placeholder="description for column name" name="description"></textarea>
<div class="surl"><input type="url" placeholder="first url" name="url1"/></div>
<div class="surl"><input type="url" placeholder="second url" name="url2"/></div>
<div class="surl"><input type="url" placeholder="third url" name="url3"/></div>
<input type="submit" class="surl_submit">
</form>
if one of my input fields or textarea is empty while submit button click, i don't want to post the form.how can i control this form's input and textarea fields at the same time instead of controling one by one?
Call the validation function on click of submit and submit form only when if the all requirements are fullfilled.
DEMO
HTML
<form action="surl.php" method="get" id="surl">
<input id="mytext1" type="text" placeholder="name of column" name="column_name" value="" />
<textarea id="mytext2" placeholder="description for column name" name="description"></textarea>
<div class="surl"><input class="inputUrl" type="url" placeholder="first url" name="url1" value=""/></div>
<div class="surl"><input class="inputUrl" type="url" placeholder="second url" name="url2" value=""/></div>
<div class="surl"><input class="inputUrl" type="url" placeholder="third url" name="url3"/ value=""></div>
<input type="submit" class="surl_submit" onclick="return validateForm()" value="submit">
</form>
SCRIPT
function validateForm(){
var input1 = document.getElementById('mytext1');
var textarea1 = document.getElementById('mytext2');
var allInputs = document.getElementsByClassName('inputUrl');
for(var i=0; i<allInputs.length; i++){
if(!allInputs[i].value){
return false;
}
}
if(!input1.value){
return false;
}else if(!textarea1.value){
return false;
}
}
Add a class to the input/textarea tags, call a function on submit and do something like this:
document.querySelector('.surl_submit').onclick = function(e) {
var input = document.getElementsByClassName('classname');
var i = input.length;
while(i--) {
if(input[i].value == '') {
// you could display some sort of message here
e.preventDefault();
return;
}
}
};
you can add a class for all relevant fields somthing like: "tovalidate" and using jquery:
if ($('.tovalidate').filter(function(){return $(this).val()=='';}).length>0)
//do not submit
else
//submit

Jquery .show Issue on IE

I have a form, and when certain inputs are filled another div will display beneath the form. The following is the code:
<form>
<div class="fieldtitle">Full Name:* </div><input type="text" value="" name="fullname" id="fullname" />
<div class="fieldtitle">Email:* </div><input type="text" value="" name="email" id="emailfield" />
<div class="fieldtitle">Contact No:* </div><input type="text" value="" name="contact" id="contact" />
</form>
<div id="demo1" style="width:300px; display:none;"></div>
<script type="text/javascript">
$("#formarea").keyup(function(){
if($(fullname).val() && $(emailfield).val() && $(contact).val() && $(quantity).val()) {
$("#demo1").show();
if($.browser.msie){
$('#demo1').css({"visibility":"visible"});
}
} else {
$("#demo1").hide();
}
});
</script>
It is working on all browsers, except for IE - any suggestions as how to solve this?
The html is missing the quantity field, which will cause logic issues in the Javascript.
<form>
<div class="fieldtitle">Full Name:* </div><input type="text" value="" name="fullname" id="fullname" />
<div class="fieldtitle">Email:* </div><input type="text" value="" name="email" id="emailfield" />
<div class="fieldtitle">Contact No:* </div><input type="text" value="" name="contact" id="contact" />
<div class="fieldtitle">Quantity:* </div><input type="text" value="" name="quantity" id="quantity" />
</form>
<div id="demo1" style="width:300px; display:none;">Test</div>
The Javascript binds the event to the wrong element. It should bind toinputs instead of the form. Also the selectors passed in for each input should be string literals using the css id selector.
$("input").keyup(function(){
if($("#fullname").val() && $("#emailfield").val() && $("#contact").val() && $("#quantity").val()) {
$("#demo1").show();
} else {
$("#demo1").hide();
}
});
There is also no need for the IE conditional. Jquery's show()/hide() methods are cross browser compatible.
Example: http://jsfiddle.net/DEfVS/1/
IE dont like suggested id or name selector, you dont use it in the right way. Specify which selector you are targetting.
e.g:
Replace
$(fullname)
With
$('#fullname')
And so on...
By the way, cannot see in your sample code any form with ID 'formarea'.
And remove this: if($.browser.msie){...} its useless.

Categories

Resources