Is it possible to embed html within javascript? I am trying to pass two different forms based on the input to a radio button. My question is this possible?
<script>
if(document.getElementById('hello').checked) {
<p> form 1 </p>
}else if(document.getElementById('goodbye').checked) {
<p> form 2</p>
}
</script>
<button onclick="">one or the other</button>
You could create an Object with templates forms.
Depending on the checked radio element, you simply reference the template by the checked radio element value:
const form_templates = {
contact: `<form action="/form_contact.php">
<label><span>First name:</span><input type="text" name="fname"></label>
<label><span>Last name:</span><input type="text" name="lname"></label>
<input type="submit" value="Submit">
</form>`,
newsletter: `<form action="/newsletter.php">
<label><span>Email:</span><input type="text" name="email"></label>
<input type="submit" value="Submit">
</form>`
};
const ELS_picker = document.querySelectorAll("[name=form-picker]");
const EL_picked = document.querySelector("#picked");
const pickForm = () => {
const ckd = [...ELS_picker].filter(el => el.checked)[0];
EL_picked.innerHTML = form_templates[ckd.value];
};
// On radio change
ELS_picker.forEach(el => el.addEventListener("change", pickForm));
// Init!
pickForm();
<h3>Select a form:</h3>
<label>Contact: <input type="radio" value="contact" name="form-picker" checked></label>
<label>Newsletter: <input type="radio" value="newsletter" name="form-picker"></label>
<div id="picked"></div>
Example with two forms already defined in the document and by using classList.toggle()
const ELS_picker = document.querySelectorAll("[name=form-picker]");
const pickForm = () => {
const ckd = ELS_picker.forEach(el => {
document.querySelector(`[id="form--${el.value}"]`).classList.toggle("u-none", !el.checked);
});
};
// On radio change
ELS_picker.forEach(el => el.addEventListener("change", pickForm));
// Init!
pickForm();
/* Utility classes */
.u-none {
display: none;
}
<h3>Select a form:</h3>
<label>Contact: <input type="radio" value="contact" name="form-picker" checked></label>
<label>Newsletter: <input type="radio" value="newsletter" name="form-picker"></label>
<form id="form--contact" class="u-none" action="/form_contact.php">
<label><span>First name:</span><input type="text" name="fname"></label>
<label><span>Last name:</span><input type="text" name="lname"></label>
<input type="submit" value="Submit">
</form>
<form id="form--newsletter" class="u-none" action="/newsletter.php">
<label><span>Email:</span><input type="text" name="email"></label>
<input type="submit" value="Submit">
</form>
You can do it, but you may have to inject like this:
<div id="form"></div>
<button onclick="">one or the other</button>
<script>
var formEl = document.getElementById('form');
if(document.getElementById('hello').checked) {
formEl.innerHTML = '<p> form 1 </p>';
}else if(document.getElementById('goodbye').checked) {
formEl.innerHTML = '<p> form 2</p>';
}
</script>
If you want to update the HTML on your JS code, you should use functions like document.createElement.
Check the section Creating and placing new nodes at this Mozilla's doc.
Related
I'm trying to create a form with a list. The button is responsible for adding a new element to the list in the form. HTML:
<form id="newBrand">
<fieldset>
<ul id="formCars">
<li>
<legend>Car 1</legend>
<label>Name
<input type="text" name="carName1" />
</label>
</li>
</ul>
</fieldset>
<button type="button" id="addCar">+</button>
</form>
And there is my JS code:
const form = document.getElementById('newBrand');
const formCars = document.getElementById('formCars');
const addCarBtn = document.getElementById('addCar');
addCarBtn.addEventListener('click', () => formCars.appendChild(createBrandCar));
function createBrandCar() {
const result = document.createElement('li');
let size = formCars.getElementsByTagName('li').length;
result.innerHTML = `
<legend>Car ${size}</legend>
<label>Name
<input type="text" name="carName${size}" />
</label>`;
return result
}
My application renders fine, but when I click the button then I get this error:
Uncaught TypeError: Node.appendChild: Argument 1 does not implement interface Node.
This error points to a line that contains this code:
addCarBtn.addEventListener('click', () => formCars.appendChild(createBrandCar));
What can i do to prevent this error from occurring ?
You should invoke the function by specifying the parenthesis after the function name:
addCarBtn.addEventListener('click', () => formCars.appendChild(createBrandCar()));
Also, since you have already one list item on page load you should increment the size by 1:
let size = ++formCars.getElementsByTagName('li').length;
Demo:
const form = document.getElementById('newBrand');
const formCars = document.getElementById('formCars');
const addCarBtn = document.getElementById('addCar');
addCarBtn.addEventListener('click', () => formCars.appendChild(createBrandCar()));
function createBrandCar() {
const result = document.createElement('li');
let size = ++formCars.getElementsByTagName('li').length;
result.innerHTML = `
<legend>Car ${size}</legend>
<label>Name
<input type="text" name="carName${size}" />
</label>`;
return result
}
<form id="newBrand">
<fieldset>
<ul id="formCars">
<li>
<legend>Car 1</legend>
<label>Name
<input type="text" name="carName1" />
</label>
</li>
</ul>
</fieldset>
<button type="button" id="addCar">+</button>
</form>
I have been learning JavaScript and i am attempting to launch a new window on click after a user has placed info into a form fields and then placing that info into form fields in the newly launched window. I have read many posts and methods in Stackoverflow however i cant seem to get it to work properly.
Starting page HTML:
<form id="memCat" methed="get" class="member_catalogue">
<button type="submit" class="prodBtn" id="catOrder" onclick="openMemberOrder()"><img class="prodImg" src="../../../Images/bcpot002_thumb.jpg" name="Red Bowl"></button>
<div class="cat_block">
<label class="cat_label" for="cat_name">Product Name:</label>
<input class="cat_input" type="text" id="catID" value="bepot002" readonly>
</div>
<div class="cat_block">
<label class="cat_label" for="cat_description">Product Description:</label>
<input class="cat_input" type="text" id="catDesc" value="Ocre Red Pot" readonly>
</div>
<div class="cat_block">
<label class="cat_label" for="cat_price">Per unit price:$</label>
<input class="cat_input" type="number" id="catVal" value="10" readonly>
</div>
</form>
New page HTML:
<form id="memOrder" method="post">
<div>
<label for="pname">Product Name:</label>
<input type="text" id="orderID" readonly>
</div>
<div>
<label for="pdescription">Product Description:</label>
<input type="text" id="orderDesc" readonly>
</div>
<div>
<label for="quantity">Quantity ordered:</label>
<input type="number" class="quantOrder" id="orderOrder" value="1" min="1" max="10">
</div>
<div>
<label for="ind_price">Per unit price: $</label>
<input type="number" class="quantCount" id="orderVal" readonly>
</div>
<div>
<label for="tot_price">Total Price: $</label>
<input type="number" class="quantCount" id="orderTotal" readonly>
</div>
<div>
<button type="reset">Clear Order</button>
<button type="submit" id="orderCalc">Calculate Total</button>
<button type="submit" id="orderPlace">Place Order</button>
</div>
</form>
Script i have to date:
function openMemberOrder() {
document.getElementById("orderID").value = document.getElementById("catID").document.getElementsByTagName("value");
document.getElementById("orderDesc").value = document.getElementById("catDesc").document.getElementsByTagName("value");
document.getElementById("orderVal").value = document.getElementById("catVal").document.getElementsByTagName("value");
memberOrderWindow = window.open('Member_Orders/members_order.html','_blank','width=1000,height=1000');
};
script and other meta tags in head are correct as other code is working correctly.
So after much trial and error i have had success with this:
On the submission page:
1. I created a button on the page that will capture the input form data
2. i created the localstorage function in JS
3. I then placed the script tag at the bottom of the page before the closing body tag
HTML
<button type="submit" class="prodBtn" id="catOrder" onclick="openMemberOrder()"><img class="prodImg" src="../../../Images/bcpot002/bcpot002_thumb.jpg" name="Red Bowl"></button>
Javascript
var catID = document.getElementById("catID").value;
var catDesc = document.getElementById("catDesc").value;
var catVal = document.getElementById("catVal").value;
function openMemberOrder() {
var memberOrderWindow;
localStorage.setItem("catID", document.getElementById("catID").value);
localStorage.setItem("catDesc", document.getElementById("catDesc").value);
localStorage.setItem("catVal", document.getElementById("catVal").value);
memberOrderWindow = window.open('Member_Orders/members_order.html', '_blank', 'width=1240px,height=1050px,toolbar=no,scrollbars=no,resizable=no');
} ;
Script Tag
<script type="text/javascript" src="../../../JS/catOrder.js"></script>
I then created the new page with the following javascript in the header loading both an image grid as well as input element values:
var urlArray = [];
var urlStart = '<img src=\'../../../../Images/';
var urlMid = '_r';
var urlEnd = '.jpg\'>';
var ID = localStorage.getItem('catID');
for (var rowN=1; rowN<5; rowN++) {
for (var colN = 1; colN < 6; colN++){
urlArray.push(urlStart + ID + '/' + ID + urlMid + rowN + '_c' + colN + urlEnd)
}
}
window.onload = function urlLoad(){
document.getElementById('gridContainer').innerHTML = urlArray;
document.getElementById('orderID').setAttribute('value', localStorage.getItem('catID'));
document.getElementById('orderDesc').setAttribute('value', localStorage.getItem('catDesc'));
document.getElementById('orderVal').setAttribute('value', localStorage.getItem('catVal'));
};
I then created 2 buttons to calculate a total based on inputs and clearing values separately, the script for this was placed at the bottom of the page.
function total() {
var Quantity = document.getElementById('orderQuant').value;
var Value = document.getElementById('orderVal').value;
var Total = Quantity * Value;
document.getElementById('orderTotal').value = Total;
}
function clearForm() {
var i = 0;
var j = 0;
document.getElementById('orderQuant').value = i;
document.getElementById('orderTotal').value = j;
}
I have this task that has to been done soon, I have been trying to figure it out for the past couple of days but unfortunately, I have failed every time. I need to create a filter, where the user can click on a radio button to get those specific courses, after that or even before, he can click on checkboxes to filter even further.
I have managed to go through the "first" part of the filtering with radio buttons, the biggest issue is that I can't filter with checkboxes because for example -> you can't choose 2 options from the checkboxes.
Here is HTML
By subject:<br>
<form action="">
<input type="radio" name="name" value="Computing & IT">Computing & IT</input><br>
<input type="radio" name="name" value="Psychology & Sociology">Psychology & Sociology</input><br>
<input type="radio" name="name" value="Business & Management">Business & Management</input><br>
<input type="radio" name="name" value="Law & Criminology">Law & Criminology</input><br>
<input type="radio" name="name" value="Data Analytics">Data Analytics</input><br>
<input type="radio" name="name" value="Finance">Finance</input><br>
<input type="radio" name="name" value="Human Resource Management">Human Resource Management</input><br>
<!-- <input type="submit" value="Submit"> -->
</form>
<hr>
<h4> By Award:</h4>
<form action="">
<input type="checkbox" value="Postgraduate">Postgraduate</input><br>
<input type="checkbox" value="Undergraduate">Undergraduate</input><br>
<input type="checkbox" value="Top-Up">Top-Up</input><br>
</form>
and here is JS
fetch("https://api.myjson.com/bins/1axsrs")
.then(response => response.json())
.then(data => {
let api_array = data.name;
let radio = document.querySelectorAll('input[type=radio]');
let checkboxes = document.querySelectorAll('input[type=checkbox]')
api_array.map(item => {
document.getElementById('app').innerHTML +=
`<div class="card">
<h6>${item.vertical}</h6>
<h4>${item.program}</h4>
<p>${item.level}</p>
<button class="myButton">Enquire Now</button>
`
})
for(let select of radio) {
select.addEventListener('click',() => {
document.getElementById('app').innerHTML = "";
let api_array = data.name.filter(e => e.vertical === select.value)
api_array.map(item => {
document.getElementById('app').innerHTML +=
`<div class="card">
<h6>${item.vertical}</h6>
<h4>${item.program}</h4>
<p>${item.level}</p>
<button class="myButton">Enquire Now</button>
`
})
for(let check of checkboxes) {
check.addEventListener('change',() => {
document.getElementById('app').innerHTML = "";
if(check.checked) {
let chosen = api_array.filter(c => c.level === check.value)
chosen.map(item => {
document.getElementById('app').innerHTML +=
`<div class="card">
<h6>${item.vertical}</h6>
<h4>${item.program}</h4>
<p>${item.level}</p>
<button class="myButton">Enquire Now</button>
`
})
} else {
}
})
}
})
}
})
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");
}
}
I have used this jquery validation plugin for the following form.
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#commentForm").validate();
});
function addInput() {
var obj = document.getElementById("list").cloneNode(true);
document.getElementById('parent').appendChild(obj);
}
</script>
<form id="commentForm" method="get" action="">
<p id="parent">
<input id="list" class="required" />
</p>
<input class="submit" type="submit" value="Submit"/>
<input type="button" value="add" onClick="addInput()" />
</form>
When the add button is clicked a new input is dynamically added. However when the form is submitted only the first input field is validated. How can i validate dynamically added inputs?
Thank you...
You should have 'name' attribute for your inputs. You need to add the rules dynamically, one option is to add them when the form submits.
And here is my solution that I've tested and it works:
<script type="text/javascript">
$(document).ready(function() {
var numberIncr = 1; // used to increment the name for the inputs
function addInput() {
$('#inputs').append($('<input class="comment" name="name'+numberIncr+'" />'));
numberIncr++;
}
$('form.commentForm').on('submit', function(event) {
// adding rules for inputs with class 'comment'
$('input.comment').each(function() {
$(this).rules("add",
{
required: true
})
});
// prevent default submit action
event.preventDefault();
// test if form is valid
if($('form.commentForm').validate().form()) {
console.log("validates");
} else {
console.log("does not validate");
}
})
// set handler for addInput button click
$("#addInput").on('click', addInput);
// initialize the validator
$('form.commentForm').validate();
});
</script>
And the html form part:
<form class="commentForm" method="get" action="">
<div>
<p id="inputs">
<input class="comment" name="name0" />
</p>
<input class="submit" type="submit" value="Submit" />
<input type="button" value="add" id="addInput" />
</div>
</form>
Good luck! Please approve answer if it suits you!
Reset form validation after adding new fields.
function resetFormValidator(formId) {
$(formId).removeData('validator');
$(formId).removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse(formId);
}
You need to re-parse the form after adding dynamic content in order to validate the content
$('form').data('validator', null);
$.validator.unobtrusive.parse($('form'));
The one mahesh posted is not working because the attribute name is missing:
So instead of
<input id="list" class="required" />
You can use:
<input id="list" name="list" class="required" />
Modified version
jquery validation plugin version work fine v1.15.0 but v1.17.0 not work for me.
$(document).find('#add_patient_form').validate({
ignore: [],
rules:{
'email[]':
{
required:true,
},
},
messages:{
'email[]':
{
'required':'Required'
},
},
});
In regards to #RitchieD response, here is a jQuery plugin version to make things easier if you are using jQuery.
(function ($) {
$.fn.initValidation = function () {
$(this).removeData("validator");
$(this).removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse(this);
return this;
};
}(jQuery));
This can be used like this:
$("#SomeForm").initValidation();
In case you have a form you can add a class name as such:
<form id="my-form">
<input class="js-input" type="text" name="samplename" />
<input class="js-input" type="text" name="samplename" />
<input class="submit" type="submit" value="Submit" />
</form>
you can then use the addClassRules method of validator to add your rules like this and this will apply to all the dynamically added inputs:
$(document).ready(function() {
$.validator.addClassRules('js-input', {
required: true,
});
//validate the form
$('#my-form').validate();
});
$('#form-btn').click(function () {
//set global rules & messages array to use in validator
var rules = {};
var messages = {};
//get input, select, textarea of form
$('#formId').find('input, select, textarea').each(function () {
var name = $(this).attr('name');
rules[name] = {};
messages[name] = {};
rules[name] = {required: true}; // set required true against every name
//apply more rules, you can also apply custom rules & messages
if (name === "email") {
rules[name].email = true;
//messages[name].email = "Please provide valid email";
}
else if(name==='url'){
rules[name].required = false; // url filed is not required
//add other rules & messages
}
});
//submit form and use above created global rules & messages array
$('#formId').submit(function (e) {
e.preventDefault();
}).validate({
rules: rules,
messages: messages,
submitHandler: function (form) {
console.log("validation success");
}
});
});
Try using input arrays:
<form action="try.php" method="post">
<div id="events_wrapper">
<div id="sub_events">
<input type="text" name="firstname[]" />
</div>
</div>
<input type="button" id="add_another_event" name="add_another_event" value="Add Another" />
<input type="submit" name="submit" value="submit" />
</form>
and add this script and jQuery, using foreach() to retrieve the data being $_POST'ed:
<script>
$(document).ready(function(){
$("#add_another_event").click(function(){
var $address = $('#sub_events');
var num = $('.clonedAddress').length; // there are 5 children inside each address so the prevCloned address * 5 + original
var newNum = num + 1;
var newElem = $address.clone().attr('id', 'address' + newNum).addClass('clonedAddress');
//set all div id's and the input id's
newElem.children('div').each (function (i) {
this.id = 'input' + (newNum*5 + i);
});
newElem.find('input').each (function () {
this.id = this.id + newNum;
this.name = this.name + newNum;
});
if (num > 0) {
$('.clonedAddress:last').after(newElem);
} else {
$address.after(newElem);
}
$('#btnDel').removeAttr('disabled');
});
$("#remove").click(function(){
});
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/jquery-validation#1.17.0/dist/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#commentForm").validate();
});
function addInput() {
var indexVal = $("#index").val();
var index = parseInt(indexVal) + 1
var obj = '<input id="list'+index+'" name=list['+index+'] class="required" />'
$("#parent").append(obj);
$("#list"+index).rules("add", "required");
$("#index").val(index)
}
</script>
<form id="commentForm" method="get" action="">
<input type="hidden" name="index" name="list[1]" id="index" value="1">
<p id="parent">
<input id="list1" class="required" />
</p>
<input class="submit" type="submit" value="Submit"/>
<input type="button" value="add" onClick="addInput()" />
</form>