How to Console log the Entire HTML Form? - javascript

I'm trying to console log the entire form but the JavaScript Code is getting too long. Can anyone please help me how to follow DRY(Do not repeat Yourself), coz I have repeated a lot of code in my script tag
<form class="form" action="register.jsp" method="post">
<ul class="fieldlist">
<li>
<label for="simple-input"> UserName < /label> < input id="simple-input1" name="userid" type="text" class="k-textbox" style="width: 100%;" />
</li>
<li>
<label for="simple-input">Password</label>
<input id="simple-input2" name="pwd" type="password" class="k-textbox" style="width: 100%;" />
</li>
<li>
<input onclick="myFunction()" id="button" type="submit">
</li> </ul>
</form>
This is my Script tag. I want to follow DRY rules. I have tried saving the values to each separate variables.
<script>
var nameInput = document.getElementById('simple-input1');
document.querySelector('form.form').addEventListener('submit', function(e) {
//prevent the normal submission of the form
e.preventDefault();
console.log("Username: " + nameInput.value);
});
var nameInput1 = document.getElementById('simple-input2');
document.querySelector('form.form').addEventListener('submit', function (e) {
//prevent the normal submission of the form
e.preventDefault();
console.log("Password: " + nameInput1.value);
});
</script>

You can get the form elements using document.querySelector('form.form').elements
document.querySelector('form.form').addEventListener('submit', function(e) {
e.preventDefault();
let x = document.querySelector('form.form').elements;
console.log("Username: ", x['userid'].value);
console.log("Password: ", x['pwd'].value);
});
<form class="form" action="register.jsp" method="post">
<ul class="fieldlist">
<li>
<label for="simple-input"> UserName</label>
<input id="simple-input1" name="userid" type="text" class="k-textbox" style="width: 100%;">
</li>
<li>
<label for="simple-input">Password</label>
<input id="simple-input2" name="pwd" type="password" class="k-textbox" style="width: 100%;">
</li>
<li>
<input id="button" type="submit">
</li>
</ul>
</form>

You could use FormData and pass the form element as a parameter. Then use FormData.entries() to get an iterator of all values
document.querySelector('form.form').addEventListener('submit', function(e) {
e.preventDefault();
const formData = new FormData(this);
const entires = formData.entries();
for (var input of entires) {
console.log(input[0] + ': ' + input[1]);
}
});
<form class="form" action="register.jsp" method="post">
<ul class="fieldlist">
<li>
<label for="simple-input"> UserName </label> <input id="simple-input1" name="userid" type="text" class="k-textbox" style="width: 100%;" />
</li>
<li>
<label for="simple-input">Password</label>
<input id="simple-input2" name="pwd" type="password" class="k-textbox" style="width: 100%;" />
</li>
<li>
<input id="button" type="submit">
</li>
</ul>
</form>

Both your listeners are listening for the same thing - a submit. Make your code much simpler by merging them into a simplified listener, using template literals and newlines for the console.log():
document.querySelector("form.form").submit = function(e) {
e.preventDefault();
console.log(`Username: ${nameInput.value}\nPassword: ${nameInput1.value}`);
}

Related

Form that changes class attribute to active

I have a web page associated with 3 <li> and each has its own onclick() function. By default, one of them is active. Now I have a form, if this form is submitted I want it to take me to one of the other two <li>.
In other words, I want it to remove the active class from the default one, and add it to one of the other two. How can I do that?
HTML:
<div class="container">
<ul class="editor-nav">
<li id="content-w" class="en-nav active">1. Add Status</li>
<li id="setting-w" name="setting-w" class="en-nav">2. Upload Image</li>
<li id="cover-w" class="en-nav">3. Upload Video</li>
</ul>
</div>
<div class="be-large-post-align" id="firstdiv">
<form class="" action="work.php" method="post">
<textarea id="special" name="post" rows="10" cols="80" placeholder="What's on your mind, <?=$_SESSION['name']?>?"></textarea>
<input type="submit" name="submitMe" class="buttons-navbar btn btn-primary" value="POST" /></form>
</div>
<div class="be-large-post-align" id="seconddiv" style="display:none;">
<form class="" action="work.php" method="post" enctype="multipart/form-data">
<!-- <label class="btn btn-primary" for="my-file-selector">
<input id="my-file-selector" type="file" multiple="multiple" style="display:none"
onchange="$('#upload-file-info').html(this.files[0].name)">
Button Text Here
</label>
<span class='label label-info' id="upload-file-info"></span> -->
Select Image Files to Upload:
<input type="file" name="files[]" multiple>
<textarea id="special" name="post2" rows="10" cols="80" placeholder="What's on your mind, <?=$_SESSION['name']?>?"></textarea>
<input type="submit" name="submitIt" class="buttons-navbar btn btn-primary" value="Upload" />
</form>
</div>
<div class="be-large-post-align" id="thirddiv" style="display:none;">this is working! </div>
JQuery:
<script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" > </script>
<script src = "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/jquery-ui.min.js"> </script>
<script type = "text/javascript" >
$("#setting-w").on("click", function() {
$("#firstdiv").fadeOut(1, function() {
$("#seconddiv").fadeIn(1, function() {});
$("#thirddiv").fadeOut(1, function() {});
});
});
$("#content-w").on("click", function() {
$("#seconddiv").fadeOut(0.1, function() {
$("#firstdiv").fadeIn(0.1, function() {});
$("#thirddiv").fadeOut(0.1, function() {});
});
});
$("#cover-w").on("click", function() {
$("#seconddiv").fadeOut(0.1, function() {
$("#firstdiv").fadeOut(0.1, function() {});
$("#thirddiv").fadeIn(0.1, function() {});
});
});
</script>
Use data attribute to fade your div.
$('.editor-nav li').click(function(e) {
$('.editor-nav li').removeClass('active');
var data = $(this).data('myval');
if (data == "2" || data == "3") {
$(this).addClass('active');
var tstDiv = data - 1;
$(this).attr('disabled', true);
$(document).find($('*[data-val="' + data + '"]')).fadeIn();
$(document).find($('*[data-val="' + tstDiv + '"]')).fadeOut();
}
});
.active {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="container">
<ul class="editor-nav">
<li data-myval="1" id="content-w" class="en-nav active">1. Add Status</li>
<li data-myval="2" id="setting-w" name="setting-w" class="en-nav">2. Upload Image</li>
<li data-myval="3" id="cover-w" class="en-nav">3. Upload Video</li>
</ul>
</div>
<div data-val="1" class="be-large-post-align" id="firstdiv">
<form class="" action="work.php" method="post">
<textarea id="special" name="post" rows="10" cols="80" placeholder="What's on your mind, <?=$_SESSION['name']?>?"></textarea>
<input type="submit" name="submitMe" class="buttons-navbar btn btn-primary" value="POST" /></form>
</div>
<div data-val="2" class="be-large-post-align" id="seconddiv" style="display:none;">
<form class="" action="work.php" method="post" enctype="multipart/form-data">
<!-- <label class="btn btn-primary" for="my-file-selector">
<input id="my-file-selector" type="file" multiple="multiple" style="display:none"
onchange="$('#upload-file-info').html(this.files[0].name)">
Button Text Here
</label>
<span class='label label-info' id="upload-file-info"></span> -->
Select Image Files to Upload:
<input type="file" name="files[]" multiple>
<textarea id="special" name="post2" rows="10" cols="80" placeholder="What's on your mind, <?=$_SESSION['name']?>?"></textarea>
<input type="submit" name="submitIt" class="buttons-navbar btn btn-primary" value="Upload" />
</form>
</div>
<div data-val="3" class="be-large-post-align" id="thirddiv" style="display:none;">this is working! </div>
After page submit if your page is reloaded page loose state. So set your value when page submit like:
localStorage.setItem('key', 'your form Number')
Get localStorage when page load like:
var formID = localStorage.getItem('key');
After that check for null before add class:
if (localStorage.getItem("key") != null) {
(".editor-nav ul li").eq(formID ).addClass("active"); // Check this one on page load
}
You can use removeClass() and addClass() if you wish to add/remove any class based on their id.
Example:
$("#setting-w").on("click", function(){
$("#content-w").removeClass('active');
$("#cover-w").removeClass('active');
$("#setting-w").addClass('active');
}

I need to display jquery popup only once with a function onload

I need to display jquery popup only once with a function onload. This is my popup with a window.onload function delay and to addclass is-visible, however I'm looking to add a cookie function so the popup will only load once per browser or cache.
Any suggestions would be fantastic! - J query & html in code
jQuery(document).ready(function($){
window.onload = function (){
jQuery(".bts-popup").delay(1000).addClass('is-visible');
}
//open popup
jQuery('.bts-popup-trigger').on('click', function(event){
event.preventDefault();
jQuery('.bts-popup').addClass('is-visible');
});
//close popup
jQuery('.bts-popup').on('click', function(event){
if( jQuery(event.target).is('.bts-popup-close') || jQuery(event.target).is('.bts-popup') ) {
event.preventDefault();
jQuery(this).removeClass('is-visible');
}
});
//close popup when clicking the esc keyboard button
jQuery(document).keyup(function(event){
if(event.which=='27'){
jQuery('.bts-popup').removeClass('is-visible');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="bts-popup" role="alert">
<div class="bts-popup-container">
<div id="contact-form">
<form method="post" action="">
<input type="hidden" name="form_uid" value="e880e632-8e7c-4b51-8928-b63cd1b6cdb5">
<ul>
<li class="namefield">
<input name="name" type="text" class="name" placeholder="Your Name">
</li>
<li class="emailfield">
<input name="submit_by" type="text" class="email-contact" placeholder="Your Email">
</li>
<li class="telfield">
<input name="telephone" type="text" class="phone" placeholder="Contact Number">
</li>
<li class="commentsfield">
<textarea name="comments" class="query" placeholder="How Can We Help?"></textarea>
</li>
<li>
</li>
<li>
<input name="submit-button" type="submit" value="Submit" class="submit">
<p class="gdpr-small">*By clicking ‘submit’ you are consenting to us replying, and storing your details. (see our privacy policy).</p>
</li>
</ul>
<input type="hidden" name="required" value="name,submit_by,telephone,comments">
<input type="hidden" name="data_order" value="name,submit_by,telephone,comments,marketing-opt-in">
<input type="HIDDEN" name="automessage" value="mymessage">
<input name="ok_url" type="hidden" value="">
<input name="not_ok_url" type="hidden" value="">
</form>
</div>
<i class="fa fa-times-circle"></i>
</div>
</div>
How to simple manage cookies, i think you can watch here: link
I think it's pretty simple (pseudo-code):
if (getCookie("popup") doesnt exist OR is set to 0)
showPopup();
setCookie("popup",1);
else
destroyPopup();
endif
You can use this simple way to handle multiple popoups too.
If you use PHP, you can use $_COOKIE instead of a javascript function.
Hope it helps.

html/javascript - Trying to validate the form

I did a website and made a form ,and I have done the most of the validation but I am stuck at one. what I am trying to achieve here is when the the submit button of the form is clicked, a alert message show appear on screen saying thanks'customer name' for feed back and you chose 'radiobutton' and your comment was 'textincommentfield'.for one or another reason validation is not working. Any help would be great and thanks in advance , btw I am new to this.
Code: http://jsfiddle.net/92tSw/
HTML:
<title> Contact</title>
<body>
<div class="container">
<div id="wrap">
<div id="logo">
<img class="p" src="images/logo.png" align="left">
</div>
<img class="d" src="images/title.gif" align="middle">
<div id="menu">
<div id="menu2">
<ul>
<li><a href="homepage.html" ><span>Home</span></a></li>
<li><a href="about.html" ><span>About Us</span></a></li>
<li><a href="clubs.html" ><span>Clubs</span></a></li>
<li><a href="shop.html" ><span>Shop</span></a></li>
<li><a href="contact.html" ><span>Contact Us</span></a></li>
</ul>
</div>
</div>
<form>
<fieldset>
<legend style="font-size:20px; padding-top:20px;">Fill in the form Below to contact Us:</legend>
<p><label for="full name">Full Name:</label>
<input id="full name" type="text" size="40" name="customername" placeholder="Type first and last name" autofocus/></p>
<p><label for="Address">Address:</label>
<input type="text" name="address1" placeholder="Address Line 1" size="42%">
<input type="text" name="address2" placeholder="Address Line 2" size="42%">
<p><label for="Address"> </label>
<input type="text" name="city" placeholder="City/Town" size="20%">
<input type="text" name="postcode" placeholder="Post Code" size="20%"></p>
<p><label for="Telephone No.">Telephone Number:</label>
<input type="text" name="Telephone No." maxlenght="12"placeholder=" Enter Telephone No." size="42%"></p>
<p><label for="email">Email:</label>
<input name="email" type="email" size="25" placeholder="youremail#you.com" /></p>
<legend style="font-size:20px;" >Comments</legend>
<p><label for="quantity"> How great is the website?Choose one<em>*</em> :</label>
<input type="radio" name="myRadio" value="VG" >Very Great
<input type="radio" name="myRadio" value="G" >Great
<input type="radio" name="myRadio" value="NVG">Not Very Great
<input type="radio" name="myRadio" value="U" >Useless
<BR>
<BR>
<BR>
<BR>
<p><label for="comment">Your Message:</label>
<textarea cols="35" rows="5" name="comments" Placeholder="eg. please knock on the dooor, ring the bell etc." >
</textarea></p>
</fieldset>
<fieldset>
<input type="checkbox" name="Terms and Condition"value="Terms and Condition" required> Accept Terms and Condition<br>
<input id="bor" type="reset" value="Reset">
<input id="chor" type="submit" name="button" value="Submit" onclick="getMyForm(this.form)" >
</fieldset>
</div>
</div>
CSS:
form{ padding-top:100px; color:White;}
fieldset { background-color:#980000 ; margin: 1%;}
label { float:left; width:20%; text-align:right;}
legend{font-weight:bold;}
.foot {
padding-top:.75pt;
padding-bottom:.75pt;
padding-right:auto;
padding-left:auto;
width:100%;
}
JS:
function getMyForm(frm)
{
var myinfo = getRadioValue(frm.myRadio);
var customername = document.getElementById("customer").value;
var comment = document.getElementById("comment").value;
alert("Dear"+ customername + ",Thank you very much for your feedback.You have rated our site as" + myinfo +"your comment was Very informative website."+ comment +".");
}
function getRadioValue(radioArray){
var i;
for (i = 0; i < radioArray.length; i++){
if (radioArray[i].checked) return radioArray[i].value;}
return "";
}
It may be better to have the event on the form
<form id="form1" onsubmit="return getMyForm(this)">
To prevent the form from actually submitting, you have to return false; from the javascript method.
To submit the form programmatically in JS
frm.submit();
Or
document.getElementById("form1").submit();
Then return true; from the function under the right conditions to allow the submit to complete.
(I noticed you didn't include the action and method attributes on the form. I assumed this was just for the example.)
http://jsfiddle.net/92tSw/2/
Use JQuery if you are new to javascript.. its much more comfortable:
$(document).ready(function() {
$("#yourmockform").submit(function(e) {
var customername = $(this).find('#fullname').val();
var comment = $(this).find('#comment').val();
var myinfo = $(this).find('[name="myRadio"]:checked').attr('value');
alert("Dear"+ customername + ",Thank you very much for your feedback.You have rated our site as" + myinfo +"your comment was Very informative website."+ comment +".");
return false;
});
});

Form submit with javascript and input required

I was trying to submit things using a div, HTML5, JavaScript. If I use a submit button the validator (required attribute in the inputs) works the button doesn't submit info. But if I use a div tag it doesn't validate and send the info. Any way to fix it? Or should I do the whole code to validate the info and stop the submit?
<form action="index.php" method="get" name='myform'>
<ul>
<li class="row">
<label class="labels" for="username">Username</label>
<input type="text" id="txtUser" required>
</li>
<li class="row">
<label class="labels" for="password">Password</label>
<input type="password" id="txtPass" required>
</li>
<li id="row2">
<div class="button">Submit</div>
<input type="submit">
</li>
</ul>
</form>
http://www.dropmocks.com/mCyfGJ
Im using the following code.
Javascript submit:
http://www.javascript-coder.com/javascript-form/javascript-form-submit.phtml
HTML
enter code here
If you are submitting via JS then you need to call the form validation yourself. I don't see any issues in your post that would prevent the submit though (without validation). But here's a working example. Keep in mind that not all browsers support html5 validation.
function submitform() {
// Get first form element
var $form = $('form')[0];
// Check if valid using HTML5 checkValidity() builtin function
if ($form.checkValidity()) {
console.log('valid');
$form.submit();
}
else {
console.log('not valid');
}
return false
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="index.php" method="get" name='myform'>
<ul>
<li class="row">
<label class="labels" for="username">Username</label>
<input type="text" id="txtUser" name="sds" required>
</li>
<li class="row">
<label class="labels" for="password">Password</label>
<input type="password" id="txtPass" required>
</li>
<li id="row2">
<div class="button">Submit</div>
<input type="submit">
</li>
</ul>
</form>
I had a similiar problem and solved it this way.
<input type="submit" id="Guardar" name="Guardar" value="Guardar" onClick="if(this.form.checkValidity()){this.form.submit(); this.disabled=true; this.value='Enviando…';}else{this.form.checkValidity();}">
You can use a function to not handle it on element.

One form two actions depending on which button?

I have two files, preview.php & save.php
<form id="create-template" class="form" action="" method="post">
<p class="_50">
<label for="t-name">Template name</label>
<input type="text" name="t-name" class="required"/>
</p>
<p class="_100">
<label for="t-html">Template HTML</label>
<textarea id="t-html" name="t-html" class="required" rows="10" cols="40"></textarea>
</p>
<div class="clear"></div>
<div class="block-actions">
<ul class="actions-left">
<li><a class="button red" id="reset-template" href="javascript:void(0);">Clear</a></li>
</ul>
<ul class="actions-right">
<li><div id="preview"><input type="submit" class="button" value="Preview template" onclick="return false;"></div></li>
<li><input type="submit" class="button" value="Create template"></li>
</ul>
</div>
</form>
Current JS:
$("#preview").click(function() {
$.post('preview.php', {body:$('#t-html').val().replace(/\n/g,'<br />'), function (result) {
//maybe use .ajax instead?
//open preview.php in new window
});
});
How can I use the same form but have two different actions depending on what button one presses?
Preview template => preview.php => opens to a new tab
Create template => save.php => posts on same page
You can have a click event handler for both the button and attach simultaneous ajax call with each other.
and you can use javascript to open window in new tab.
window.open(<url>)
Try setting "target" attribute of the form based on what button was clicked.
Change your form to the following:
<form id="create-template" class="form" action="" method="post" target="_blank">
<p class="_50">
<label for="t-name">Template name</label>
<input type="text" name="t-name" class="required"/>
</p>
<p class="_100">
<label for="t-html">Template HTML</label>
<textarea id="t-html" name="t-html" class="required" rows="10" cols="40"></textarea>
</p>
<div class="clear"></div>
<div class="block-actions">
<ul class="actions-left">
<li><a class="button red" id="reset-template" href="javascript:void(0);">Clear</a></li>
</ul>
<ul class="actions-right">
<li><input id="preview-form" type="submit" class="button" value="Preview template" /></li>
<li><input type="submit" id="submit-form" class="button" value="Create template" /></li>
</ul>
</div>
</form>​
And add this JavaScript:
$('#preview-form').click(function(ev) {
$('#create-template').attr('action', 'preview.php');
$('#create-template').attr('target', '_blank');
});
$('#submit-form').click(function(ev) {
$('#create-template').attr('action', 'submit.php');
$('#create-template').attr('target', '');
});
​
I haven't tested this across all browsers, so you might want to do that.

Categories