I am trying show content in a div when a user click on a button. I have three button test connection src , test connection dest, next.
When I click on test connection src if there is no input it should display message but when user click on input field it should hide the message, right now I am able to show the message but when I click on input field it is not hiding
same when test connection src clicked if the input field matches the with pattern that is regex it show display message connection successful,
right now I am not able to show connection successful in <div id = "inp_src_success"></div> and <div id = "inp_dest_success"></div>
Same goes for button test connection dest
next button click should be enabled only once the both become successful
$(document).ready(function () {
$("#test_btn_src").on("click", function(){
var inpsrc = document.getElementById('inp_src').value;
//alert(inpsrc);
if(inpsrc.trim() == null || inpsrc.trim() == "") {
document.getElementById('inp_src1').innerHTML = 'IP src should be filled out';
}
else {
$("inp_src").keypress(function(key){
if (key){
$("inp_src1").hide();
}
});
}
});
$("#test_btn_dest").on("click", function(){
var inpdest = document.getElementById('inp_dest').value;
//alert(inpsrc);
if(inpdest.trim() == null || inpdest.trim() == "") {
document.getElementById('inp_dest1').innerHTML = 'IP src should be filled out';
}
else {
$("inp_dest").keypress(function(key){
if (key){
$("inp_dest1").hide();
}
});
}
});
document.getElementById("mybtn").onclick = function () {
location.href = "www.google.com";
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<body>
<div id = "inp_src_success"></div>
<div>
<label>Enter Source Server IP Here</label>
<input id = "inp_src" name="txtbox_ip_src" minlength="7" maxlength="15" class="form-control" type="text"
placeholder="Source Server Ip:"
pattern="(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
required onkeypress="myFunction()" />
<div id = "inp_src1"></div>
<button id = "test_btn_src" class="btn btn-primary success" type="button" style=" font-size: 10px; margin-top:7px;">Test Connection Src</button>
</div>
<div id = "inp_dest_success"></div>
<div>
<label>Enter Destination Server IP Here</label>
<input id = "inp_dest" name="txtbox_ip_src" minlength="7" maxlength="15" class="form-control" type="text"
placeholder="Destination Server Ip:"
pattern="(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
required onkeypress="myFunction1()" />
<div id = "inp_dest1"></div>
<button id = "test_btn_dest" class="btn btn-primary success" type="button" style=" font-size: 10px; margin-top:7px;">Test Connection Dest</button>
</div>
<button id = "mybtn" class="btn btn-primary nextBtn pull-right" type="button">Next</button>
There's a lot of changes that I would suggest you make in your JavaScript. It can do with a lot of improvement. Since you will be using these elements in a few places I suggest adding global variables for these, so that it's easier to work with.
See the snippet below. I will add comments. I won't be using jQuery, but vanilla JavaScript.
I added type="submit" to the buttons to use the browser's built in validator.
So in the example snippet, you will see a few ways you can validate.
I wrapped your form in form tags, since this is a form, and you're doing validation. I assume you will be submitting the form as well.
$(document).ready(function() {
//Global vars, to be reused.
var sourceValid = false;
var destinationValid = false;
var btnTestSrc = document.getElementById("test_btn_src");
var btnTestDest = document.getElementById("test_btn_dest");
var btnSubmit = document.getElementById("mybtn");
btnSubmit.disabled = true;
var txtInpSrc = document.getElementById("inp_src");
var txtInpDest = document.getElementById("inp_dest");
var inpSrc1 = document.getElementById('inp_src1');
inpSrc1.style.display = "none";
var inpDest1 = document.getElementById('inp_dest1');
inpDest1.style.display = "none";
//
//Add an event listener to the button. Same as the jQuery alternative that you used.
btnTestSrc.addEventListener("click", function() {
sourceValid = InputHasValue(txtInpSrc);
inpSrc1.style.display = sourceValid ? "none" : "block";
if (sourceValid && destinationValid)
btnSubmit.removeAttribute("disabled");
else
btnSubmit.setAttribute("disabled", true);
});
//This event listener will do validation before you click the button
txtInpSrc.addEventListener("keyup", function() {
inpSrc1.style.display = InputHasValue(this) ? "none" : "block";
});
btnTestDest.addEventListener("click", function() {
destinationValid = InputHasValue(txtInpDest);
inpDest1.style.display = destinationValid ? "none" : "block";
if (sourceValid && destinationValid)
btnSubmit.removeAttribute("disabled");
else
btnSubmit.setAttribute("disabled", true);
});
txtInpDest.addEventListener("keyup", function() {
inpDest1.style.display = InputHasValue(this) ? "none" : "block";
});
btnSubmit.addEventListener("click", function() {
alert("submit");
});
//Repeat on Dest
});
function InputHasValue(input) {
var val = input.value.trim();
return val ? true : false;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<form>
<div id="inp_src_success"></div>
<div>
<label>Enter Source Server IP Here</label>
<input id="inp_src" name="txtbox_ip_src" minlength="7" maxlength="15" class="form-control" type="text" placeholder="Source Server Ip:" pattern="(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
required />
<br />
<div id="inp_src1">IP src should be filled out</div>
<button id="test_btn_src" type="submit" class="btn btn-primary success" type="button" style=" font-size: 10px; margin-top:7px;">Test Connection Src</button>
</div>
<div id="inp_dest_success"></div>
<div>
<label>Enter Destination Server IP Here</label>
<input id="inp_dest" name="txtbox_ip_src" minlength="7" maxlength="15" class="form-control" type="text" placeholder="Destination Server Ip:" pattern="(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
required />
<br />
<div id="inp_dest1">IP dest should be filled out</div>
<button id="test_btn_dest" type="submit" class="btn btn-primary success" type="button" style=" font-size: 10px; margin-top:7px;">Test Connection Dest</button>
</div>
<button id="mybtn" type="submit" class="btn btn-primary nextBtn pull-right" type="button">Next</button>
</form>
</body>
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<body>
<div id = "inp_src_success"></div>
<div>
<label>Enter Source Server IP Here</label>
<input id = "inp_src" name="txtbox_ip_src" minlength="7" maxlength="15" class="form-control" type="text"
placeholder="Source Server Ip:"
pattern="(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
required onkeypress="myFunction()" />
<div id="inp_src1"></div>
<br>
<button id = "test_btn_src" class="btn btn-primary success" type="button" style=" font-size: 10px; margin-top:7px;">Test Connection Src</button>
</div>
<div id = "inp_dest_success"></div>
<div>
<label>Enter Destination Server IP Here</label>
<input id = "inp_dest" name="txtbox_ip_src" minlength="7" maxlength="15" class="form-control" type="text"
placeholder="Destination Server Ip:"
pattern="(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
required onkeypress="myFunction1()" />
<div id = "inp_dest1"></div>
<br>
<button id = "test_btn_dest" class="btn btn-primary success" type="button" style=" font-size: 10px; margin-top:7px;">Test Connection Dest</button>
</div>
<button id = "mybtn" class="btn btn-primary nextBtn pull-right" type="button">Next</button>
JS:
$(document).ready(function () {
$("#test_btn_src").on("click", function(){
var inpsrc = document.getElementById('inp_src').value;
//alert(inpsrc);
if(inpsrc.trim() == null || inpsrc.trim() == "") {
document.getElementById('inp_src1').innerHTML = 'IP src should be filled out1';
}
else {
$("#inp_src1").hide();
}
});
$("#test_btn_dest").on("click", function(){
var inpdest = document.getElementById('inp_dest').value;
//alert(inpsrc);
if(inpdest.trim() == null || inpdest.trim() == "") {
document.getElementById('inp_dest1').innerHTML = 'IP src should be filled out';
}
else {
$("#inp_dest1").hide();
}
});
document.getElementById("mybtn").onclick = function () {
location.href = "www.google.com";
};
});
Related
const btn = document.getElementById("btn");
const inputfield = document.getElementById("username");
inputfield.addEventListener("keyup", function(e) {
const val = e.target.value;
if (val === "") {
btn.disabled = true;
btn.style.backgroundColor = "grey";
} else {
btn.disabled = false;
btn.style.backgroundColor = "orange";
}
})
<div class="container">
<input id="username" placeholder="Username" class="input" />
<button disabled id="btn" type="button" class="button">Submit</button>
</div>
Now the issue is that it only works for one input and the associated button field
it does not work for another pair of input field and button , so what changes should i make in the above javascript code in which it runs for as many as input field and button i want?
Please can anyone help me in this. Thank you
If you have full jquery code it's also accepted.
My approach was to put the input and button in a div with a custom class.
And just loop over every div, get the child inputs and buttons and just use your existing code for every div.
const btns = document.getElementsByClassName('inputButton');
for (let i = 0; i < btns.length; i++) {
let input = btns[i].querySelector('input');
let button = btns[i].querySelector('button');
input.addEventListener("keyup", function(e) {
const val = e.target.value;
if (val === "") {
button.disabled = true;
button.style.backgroundColor = "grey";
} else {
button.disabled = false;
button.style.backgroundColor = "orange";
}
});
}
<div class="container">
<div class="inputButton">
<input id="username" placeholder="Username" class="input" />
<button disabled id="btn" type="button" class="button">Submit</button>
</div>
<div class="inputButton">
<input id="username" placeholder="Username" class="input" />
<button disabled id="btn" type="button" class="button">Submit</button>
</div>
<div class="inputButton">
<input id="username" placeholder="Username" class="input" />
<button disabled id="btn" type="button" class="button">Submit</button>
</div>
</div>
Just wrap it into a additional div element and iterate trough. For each "input-group" you can add an event listener to the input child and edit the style of the button child.
document.querySelectorAll('.input-group').forEach((group) => {
let input = group.querySelector('input');
let button = group.querySelector('button');
input.addEventListener('keyup', () => {
if(input.value !== "") {
button.disabled = false;
} else {
button.disabled = true;
}
});
});
#btn[disabled] {
background: red;
}
#btn {
background: green;
}
<div class="container">
<div class="input-group">
<input id="username" placeholder="Username" class="input" />
<button disabled id="btn" type="button" class="button">Submit</button>
</div>
<div class="input-group">
<input id="username" placeholder="Username" class="input" />
<button disabled id="btn" type="button" class="button">Submit</button>
</div>
<div class="input-group">
<input id="username" placeholder="Username" class="input" />
<button disabled id="btn" type="button" class="button">Submit</button>
</div>
</div>
You can make a loop with a class to add an event listener to every input you want.
You can use data-whateverYouWant to link the button to the input
Also, should make your style in css.
let inputs = document.getElementsByClassName("an-input");
for (let i = 0; i < inputs.length; i++) {
inputs[i].addEventListener("keyup", function(e) {
let btn = document.querySelectorAll("[data-placeholder="+this.placeholder+"]")[0];
if (this.value === "") {
btn.disabled = true;
} else {
btn.disabled = false;
}
})
}
button{
background-color:orange;
}
button:disabled,
button[disabled]{
background-color:grey;
}
<input class="an-input" placeholder="Username" class="input" />
<button disabled data-placeholder="Username" type="button" class="button">Submit</button>
<input class="an-input" placeholder="email" class="input" />
<button disabled data-placeholder="email" type="button" class="button">Submit</button>
So I'm still new to JS and jQuery, but I'm trying to learn how to get all the elements and the values inside a div when I click a button inside it.
I was able to get it working for a form when I used FormData to do it. I can't figure out how to do it with a div instead of a form. (I would just use a form, but can't for this unfortunately.)
Here is what I got so far, but I know I'm doing something wrong.
$('button.browsePageImages').on('click', (function(e) {
e.preventDefault();
console.log("Attempting Image Browsing: ");
var myArea = $(this).closest("div");
console.log(myArea);
var myAreaData = new FormData(myArea[0]);
console.log(myAreaData);
var myFormID = $(this).closest("div").attr("id");
console.log(myFormID);
var dataHref = $(this).attr('data-href');
console.log(dataHref);
}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-12" id="browseImagesDiv">
<h4>Image (Optional) <span></h4>
<input type="text" class="form-control" name="description" value="This is the image description." />
<input type="text" class="form-control" id="areaSection-15" name="image_url" value="" placeholder="Image URL Here"/>
<button type="button" class="btn btn-white btn-xs browsePageImages" data-href="15">Save Image Info</button></span>
</div>
You can use serializeArray for each input.
var myArea = $(this).closest("div").find(':input');
var myAreaData = myArea.serializeArray();
$('button.browsePageImages').on('click', (function(e) {
e.preventDefault();
console.log("Attempting Image Browsing: ");
var myArea = $(this).closest("div").find(':input');
//console.log(myArea);
var myAreaData = myArea.serializeArray();
console.log(myAreaData);
var myFormID = $(this).closest("div").attr("id");
console.log(myFormID);
var dataHref = $(this).attr('data-href');
console.log(dataHref);
}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-12" id="browseImagesDiv">
<h4>Image (Optional) <span></h4>
<input type="text" class="form-control" name="description" value="This is the image description." />
<input type="text" class="form-control" id="areaSection-15" name="image_url" value="" placeholder="Image URL Here"/>
<button type="button" class="btn btn-white btn-xs browsePageImages" data-href="15">Save Image Info</button></span>
</div>
I make custom Wizard with validate but when I click Next button to First step check validation and when click next step click on next button it's not check validate and skip the step.
HTML is as given below:
<form>
<div class="form-main">
<div class="form-input">
<input type="text" id="fname" placeholder="First Name">
<p id="error"></p>
</div>
<div class="form-input">
<input type="text" id="lname" placeholder="Last Name">
<p id="error"></p>
</div>
<div class="form-input">
<input type="email" id="email" placeholder="Email">
<p id="error"></p>
</div>
<div class="form-input">
<input type="password" id="password" placeholder="Password">
<p id="error"></p>
</div>
<div class="form-btn">
<button type="button" id="prev" onClick="prevBtn(this);">prev</button>
<button type="button" id="next" onClick="nextBtn(this);">next</button>
<button type="submit" id="submit">submit</button>
</div>
</div>
</form>
Script Below:
separated function used update status means find index and update ,validation,next button and previous button.
$(window).on('load',function(){
$('.form-main > .form-input:nth-child(1)').addClass('open');
$('.form-main > .form-input:not(".open")').addClass('close').hide();
});
var $div = $('.form-input');
var submits = $('#submit').css('display','none');
index = 0;
function updateStatus(a){
$div.eq(index).removeClass('current').addClass('close').hide();
index += a;
$div.eq(index).addClass('current').removeClass('close').show();
$('#next').toggle((index !==$div.length-1));
$('#prev').toggle(index !== 0);
if(index == ($div.length - 1)){
submits.toggle(index !== 0);
}else{
submits.hide();
}
}
var input = document.getElementsByTagName('input');
var error = document.getElementById('error');
function validation(){
var inputValue = $(input).val();
var inputType = $(input).attr('type');
if(inputValue !== ''){
updateStatus(+1);
}else{
error.innerHTML = "please enter the value";
}
}
function nextBtn(){
validation();
}
function prevBtn(){
updateStatus(-1);
}
So I have made few changes and got it to work.
Changed
var inputValue = $(input).val();
to below, as you need to check for current visible element
var inputValue = $('input:visible').val();
Secondly, you cannot have error as same ID for multiple elements, so I have removed that. IDs are unique.
$(window).on('load', function() {
$('.form-main > .form-input:nth-child(1)').addClass('open');
$('.form-main > .form-input:not(".open")').addClass('close').hide();
});
var $div = $('.form-input');
var submits = $('#submit').css('display', 'none');
index = 0;
function updateStatus(a) {
$div.eq(index).removeClass('current').addClass('close').hide();
index += a;
$div.eq(index).addClass('current').removeClass('close').show();
$('#next').toggle((index !== $div.length - 1));
$('#prev').toggle(index !== 0);
if (index == ($div.length - 1)) {
submits.toggle(index !== 0);
} else {
submits.hide();
}
}
var input = document.getElementsByTagName('input');
function validation() {
var inputValue = $('input:visible').val();
var inputType = $(input).attr('type');
if (inputValue !== '') {
updateStatus(+1);
} else {
$('input:visible').next().html("please enter the value");
}
}
function nextBtn() {
validation();
}
function prevBtn() {
updateStatus(-1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="form-main">
<div class="form-input">
<input type="text" id="fname" placeholder="First Name">
<p></p>
</div>
<div class="form-input">
<input type="text" id="lname" placeholder="Last Name">
<p></p>
</div>
<div class="form-input">
<input type="email" id="email" placeholder="Email">
<p></p>
</div>
<div class="form-input">
<input type="password" id="password" placeholder="Password">
<p></p>
</div>
<div class="form-btn">
<button type="button" id="prev" onClick="prevBtn(this);">prev</button>
<button type="button" id="next" onClick="nextBtn(this);">next</button>
<button type="submit" id="submit">submit</button>
</div>
</div>
</form>
I've tried many different methods, and even tried searching on SO. No answer was what I was looking for.
What I want is to have two input buttons that do some things in pure javascript.
Button one: Have it say "Add" when the page loads. When clicked, the value changes to "Cancel." Also, when it's clicked, have it display a form with three fields. When it's clicked again, have the form disappear. One named 'name', the second named 'location', the third named 'type'. I want the user to be able to submit these three things and have them be stored in the code.
Button two: Take the user input from the form and each time the user clicks, it displays all three information values, but have the button act as random generator. Let's say the code has 5 separate entries, I want them to be randomly selected and displayed when the button is clicked.
Like I said, I tried to make this work, but couldn't quite get over the top of where I wanted to go with it. If you want to see my original code, just ask, but I doubt it will be of any assistance.
Thanks in advance.
EDIT: Added the code.
function GetValue() {
var myarray = [];
var random = myarray[Math.floor(Math.random() * myarray.length)];
document.getElementById("message").innerHTML = random;
}
var testObject = {
'name': BWW,
'location': "Sesame Street",
'type': Bar
};
localStorage.setItem('testObject', JSON.stringify(testObject));
var retrievedObject = localStorage.getItem('testObject');
function change() {
var elem = document.getElementById("btnAdd1");
if (elem.value == "Add Spot") {
elem.value = "Cancel";
} else elem.value = "Add Spot";
}
window.onload = function() {
var button = document.getElementById('btnAdd1');
button.onclick = function show() {
var div = document.getElementById('order');
if (div.style.display !== 'none') {
div.style.display = 'none';
} else {
div.style.display = 'block';
}
};
};
<section>
<input type="button" id="btnChoose" value="Random Spot" onclick="GetValue();" />
<p id="message"></p>
<input type="button" id="btnAdd1" value="Add Spot" onclick="change();" />
<div class="form"></div>
<form id="order" style="display:none;">
<input type="text" name="name" placeholder="Name of Resturant" required="required" autocomplete="on" />
<input type="text" name="type" placeholder="Type of Food" required="required" autocomplete="off" />
<input type="text" name="location" placeholder="Location" required="required" autocomplete="off" />
<input type="submit" value="Add Spot" />
</form>
</div>
</section>
The randomizer works, and so does the appear/hide form. Only thing is storing the input and switching the input value.
Here's one way to do this. Each form submission is stored as an object in an array. The random button randomly selects an item from the array and displays it below.
HTML:
<section>
<input type="button" id="btnChoose" value="Random Spot" />
<p id="message"></p>
<input type="button" id="btnAdd1" value="Add Spot" />
<div class="form">
<form id="order" style="display:none;">
<input id="orderName" type="text" name="name" placeholder="Name of Resturant" required="required" autocomplete="on" />
<input id="orderType" type="text" name="type" placeholder="Type of Food" required="required" autocomplete="off" />
<input id="orderLocation" type="text" name="location" placeholder="Location" required="required" autocomplete="off" />
<input type="submit" value="Add Spot" />
</form>
</div>
</section>
<div id="randomName"></div>
<div id="randomLocation"></div>
<div id="randomType"></div>
JS:
var formData = [];
var formSubmission = function(name, location, type) {
this.name = name;
this.location = location;
this.type = type;
}
var spotName = document.getElementById("orderName"),
spotLocation = document.getElementById("orderLocation"),
spotType = document.getElementById("orderType");
var addClick = function() {
if (this.value === 'Add Spot') {
this.value = "Cancel";
document.getElementById('order').style.display = 'block';
}
else {
this.value = 'Add Spot';
document.getElementById('order').style.display = 'none';
}
}
document.getElementById("btnAdd1").onclick = addClick;
document.getElementById('order').onsubmit = function(e) {
e.preventDefault();
var submission = new formSubmission(spotName.value, spotLocation.value, spotType.value);
formData.push(submission);
submission = '';
document.getElementById('btnAdd1').value = 'Add Spot';
document.getElementById('order').style.display = 'none';
this.reset();
}
var randomValue;
document.getElementById('btnChoose').onclick = function() {
randomValue = formData[Math.floor(Math.random()*formData.length)];
document.getElementById('randomName').innerHTML = randomValue.name;
document.getElementById('randomLocation').innerHTML = randomValue.location;
document.getElementById('randomType').innerHTML = randomValue.type;
}
I was working on something since you first posted, and here is my take on it:
HTML:
<section>
<p id="message">
<div id="name"></div>
<div id="location"></div>
<div id="type"></div>
</p>
<input type="button" id="btnAdd" value="Add" onclick="doAdd(this);" />
<input type="button" id="btnShow" value="Show" onclick="doShow(this);" />
<div class="form">
<script id="myRowTemplate" type="text/template">
<input type="text" name="name" placeholder="Name of Resturant" required="required" autocomplete="on" onchange="onChanged(this, {{i}})" />
<input type="text" name="type" placeholder="Type of Food" required="required" autocomplete="off" onchange="onChanged(this, {{i}})" />
<input type="text" name="location" placeholder="Location" required="required" autocomplete="off" onchange="onChanged(this, {{i}})" />
</script>
<form id="order" style="display:none;">
<div id="formItems">
</div>
<input type="button" value="Add Spot" onclick="addSpot()" />
</form>
</div>
</section>
JS:
function GetValue() {
if (enteredItems.length) {
var entry = enteredItems[Math.floor(Math.random() * enteredItems.length)];
document.getElementById("name").innerHTML = entry.name;
document.getElementById("location").innerHTML = entry.location;
document.getElementById("type").innerHTML = entry.type;
}
}
function doAdd(elem) {
switch (elem.value) {
case "Add":
document.getElementById('order').style.display = "";
elem.value = "Cancel";
break;
case "Cancel":
document.getElementById('order').style.display = "none";
elem.value = "Add";
break;
}
}
function doShow(elem) {
GetValue();
}
function addSpot(index) { // (note: here, index is only for loading for the first time)
if (index == undefined) index = enteredItems.length;
var newRowDiv = document.createElement("div");
newRowDiv.innerHTML = document.getElementById("myRowTemplate").innerHTML.replace(/{{i}}/g, index); // (this updates the template with the entry in the array it belongs)
if (enteredItems[index] == undefined)
enteredItems[index] = { name: "", location: "", type: "" }; // (create new entry)
else {debugger;
newRowDiv.children[0].value = enteredItems[index].name;
newRowDiv.children[1].value = enteredItems[index].location;
newRowDiv.children[2].value = enteredItems[index].type;
}
document.getElementById("formItems").appendChild(newRowDiv);
}
function onChanged(elem, index) {
enteredItems[index][elem.name] = elem.value;
localStorage.setItem('enteredItems', JSON.stringify(enteredItems)); // (save each time
}
// update the UI with any saved items
var enteredItems = [];
window.addEventListener("load", function() {
var retrievedObject = localStorage.getItem('enteredItems');
if (retrievedObject)
enteredItems = retrievedObject = JSON.parse(retrievedObject);
for (var i = 0; i < enteredItems.length; ++i)
addSpot(i);
});
https://jsfiddle.net/k1vp8dqn/
It took me a bit longer because I noticed you were trying to save the items, so I whipped up something that you can play with to suit your needs.
So I made a simple javascript form validator which creates a box with the error message using DOM. But I can't figure out a way how to reset all these changes when i reset the form using
<button type="reset">
I would like to know how it's done please.
Thanks.
The Code
<html>
<head>
<script type="text/javascript">
function validate(){
var fname = document.getElementById("fname");
var surname = document.getElementById("surname");
if(fname.value === "" || fname.value === null){
document.getElementById("sbody").style.display = "block";
document.getElementById("fname").style.display = "block";
return false;
}
//Verify Last Name
if(surname.value === "" || surname.value === null){
document.getElementById("sbody").style.display = "block";
document.getElementById("surname").style.display = "block";
return false;
}
}//End Validate Function
</script>
<style type="text/css">
#sbody{
width: 100px;
height: 100px;
background-color: #f3f3f3;
display:none;
}
.vis{
display: none;
font-size: 12px;
}
</style>
</head>
<body>
<section id="sbody">
<span id="fner" class="vis">First Name is missing.</span>
<span id="lner" class="vis">Surame is missing.</span>
</section>
<form id="registerForm" method="POST" action="register.php" onsubmit="return validate()">
<label for="fname" class="labelStyle">First Name: </label>
<input id="fname" name="fname" type="text" value="">
<label for="surname" class="labelStyle">Surname: </label>
<input id="surname" name="surname" type="text" value="">
<button type="submit">Sign Up</button>
<button type="reset">Reset</button>
</form>
</body>
</html>
The browser cannot magically figure out what has to be done to reset the custom changes.
However you can listen to the reset event of the form using element.addEventListener.
DEMO
HTML
<form id="test">
<div id="errors-ct">The form has errors</div>
<button type="reset">Reset</button>
</form>
JS
//wait for the DOM to be ready
document.addEventListener('DOMContentLoaded', function () {
//store a reference to the errors container div
var errorsCt = document.getElementById('errors-ct');
//listen to the reset event of the form
document.getElementById('test').addEventListener('reset', function (e) {
var form = e.target; //this is how you could access the form
//hide the errors container
errorsCt.style.display = 'none';
});
});
If you want to reset the form, as if user hadn't made any selections or added any input, then just set all form element values to their default value, or empty.
jsFiddle
<div>
<form action="/echo/html" method="get">
<input type="text" placeholder="username" />
<br/>
<input type="password" placeholder="password" />
<br/>
<input type="checkbox" value="test" data-default="checked" checked="checked"/>
<br/>
<button type="reset" value="reset" onclick="resetForm()">reset</button>
<br/>
</form>
<div id="err">Some error message</div>
</div>
window.resetForm = function () {
var fields = $('input'),
uname, pass, check;
uname = $(fields.get(0));
pass = $(fields.get(1));
check = $(fields.get(2));
$("#err").text("");
uname.val('');
pass.val('');
if (check.attr("data-default") == "checked") {
check.attr("checked", "checked");
} else {
check.removeAttr("checked");
}
}