I have a dynamic section in my html form. When clicking on a button, user can add a tag name and tag type. At a point, imagine that there are 3 set of tag names and tag types, the data should be submitted in the following format.
Array[0][name] = tag1 name, Array[0][type] = tag1 type
Array[1][name] = tag2 name, Array[1][type] = tag2 type
Array[2][name] = tag3 name, Array[2][type] = tag3 type
Can someone help me on this ?
I think you are looking to have a multidimensional array that can store an array within each position of the array. Assuming you have already a form, html should look something like this:
<form class="" action="index.html" method="post">
<div class="inputs">
<input type="text" name="tagName" value="">
<input type="text" name="tagType" value="">
</div>
Add new tag name and type
<button type="submit" name="button">Submit form data</button>
</form>
For the functionality, you could have something like this to store the information and then submit the form:
//Initialization of array
var javascriptArray = [];
//Function to replicate fields in the form
function replicateFields(){
var elementToReplicate = $('.inputs').first(), //Only clone first group of inputs
clonedElement = elementToReplicate.clone();//Cloned the element
clonedElement.find('input').val(''); //Clear cloned elements value on each new addition
clonedElement.insertBefore($('form a'));
}
//Calling function on click
$('.addRow').click(function(){
replicateFields();
});
//Go through inputs filling up the array of arrays.
$('form').submit(function(){
$('.inputs').each(function(){
javascriptArray.push([$(this).find('input[name="tagName"]').val(), $(this).find('input[name="tagType"]').val()]);
});
console.log(javascriptArray);
return false; // remove this to submit the form.
});
You can check in the console in the developer tools for the information you are about to submit.
Let me know if this helps,
Leo.
//Initialization of array
var javascriptArray = [];
//Function to replicate fields in the form
function replicateFields(){
var elementToReplicate = $('.inputs').first(), //Only clone first group of inputs
clonedElement = elementToReplicate.clone();//Cloned the element
clonedElement.find('input').val(''); //Clear cloned elements value on each new addition
clonedElement.insertBefore($('form a'));
}
//Calling function on click
$('.addRow').click(function(){
replicateFields();
});
//Go through inputs filling up the array of arrays.
$('form').submit(function(){
$('.inputs').each(function(){
javascriptArray.push([$(this).find('input[name="tagName"]').val(), $(this).find('input[name="tagType"]').val()]);
});
console.log(javascriptArray);
return false; // remove this to submit the form.
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="" action="index.html" method="post">
<div class="inputs">
<input type="text" name="tagName" value="">
<input type="text" name="tagType" value="">
</div>
Add new tag name and type
<button type="submit" name="button">Submit form data</button>
</form>
here is another possibility for how to make this work. a simple form with a div to contain the tags and a small input field to add a new tag.
var tagid = 1;
function addTag() {
var div = document.getElementById("tags");
var name = document.getElementById("tname").value;
var type = document.getElementById("ttype").value;
div.innerHTML += "tag" + tagid + "<br><input type='text' name='tag[" + tagid + "][name]' value='" + name + "'><br><input type='text' name='tag[" + tagid + "][type]' value='" + type + "'><hr>";
tagid++;
}
<html>
<body>
<form id="form">
tags:<br>
<div id="tags">
</div>
<input type="submit" value="Submit">
</form>
<hr> tag name: <input id="tname" type="text" name="tname"><br> tag type: <input id="ttype" type="text" name="ttype"><br>
<button onclick="addTag()">add tag</button>
</body>
</html>
I need some help with this HTML code I'm trying to improve.
I don't have much HTML knowledge so the most basic solution would be nice.
Currently, the code works fine but I want once the page has loaded for the drop-down option to be that of the selected option that I click Submit with. Same with the slider, if I select 2, I want 2 to be displayed on the new page once loaded.
Is there a way to do this with variables or how?
<div id="input_header">
<div id="logo_div">
<img id="logo" src="static/steering-wheel.svg">
<p id="logo_name">TITLE</p>
</div>
<form id="driver_form" action="compare_driver" method="get">
<p class="label">Vendor:</p>
<select class="driver_input_box" name="driver_vendor">
<option value="Vendor A">AAA</option>
<option value="Vendor B">BBB</option>
<option value="Vendor C">CCC</option>
</select>
<p class="label"># to show: </p>
<div id="count_slider">
<input id="driver_count_id" name="driver_count" type="range" min="1" max="10" step="1" value="5" oninput="driver_count_out_id.value = driver_count_id.value"/>
<output id="driver_count_out_id" name="driver_count_output" >5</output>
</div>
<input id="compare_driver" type="submit" value="Compare">
</form>
</div>
First you need to include some JavaScript there. The easiest (but probably worse) way is to add an script tag to the HTML.
To get the selected option with Javascript, you can check these answers: Get selected value in dropdown list using JavaScript? . The code will be easier to write if you give an id to your <select>, like: <select id="mySelect" class="driver_inpu....
<script>
//check if there's an old selection by the user:
if (sessionStorage.getItem("selectedOption")) {
//to set the selected value:
document.getElementById("mySelect").value = sessionStorage.getItem("selectedOption");
}
//this will set the value to sessionStorage only when user clicks submit
document.getElementById("driver_form").addEventListener("submit", () => {
//to get the selected value:
var selectedOption = document.getElementById("mySelect").value;
sessionStorage.setItem("selectedOption", selectedOption);
});
/*
//use this only if you want to store a new value
//every time the user clicks on another option
document.getElementById("mySelect").addEventListener("change", () => {
//to get the selected value:
var selectedOption = document.getElementById("mySelect").value;
sessionStorage.setItem("selectedOption", selectedOption);
});
*/
</script>
You can put it in window.onload if you want to. This answer should put you in the right track. I'm very tired and I haven't tested it, but it should work.
I am trying to make a spreadsheet sidebar that allows a user to input data to create records, as well as edit them. So far I understand how to create the sidebar and display it. I've got a working form that can submit values.
What I am struggling with is how to pre-populate the forms. Form instance some records are associated with others, and I'd like to have a hidden field to store and eventually submit the associated id. Eventually users should also be able to edit records and I'd like to use the same form and just populate the fields and reuse the same submission flow.
I've tried a few different things found on here and other places, but nothing seems to work.
Here is the HTML for the sidebar template
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<!-- The CSS package above applies Google styling to buttons and other elements. -->
<style>
</style>
<script>
// Prevent forms from submitting.
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
$('#accountId').val(<? data.accountId ?>);
function handleFormSubmit(formObject) {
google.script.run.withSuccessHandler(alertSuccess).createContact(formObject);
}
function alertSuccess(message) {
var div = document.getElementById('alert');
div.innerHTML = "<p>" + message + "</p>";
google.script.host.close();
}
</script>
</head>
<body>
<p>Enter Contact Info</p>
<form id="contact" onsubmit="handleFormSubmit(this)">
Account Id: <br>
<input type="number" name="accountId" value="0" id="accountId" /><br>
Name:<br>
<input type="text" name="name"/><br>
Phone Number:<br>
<input type="text" name="phone"/><br>
Email:<br>
<input type="email" name="email"/><br>
Contact Type:<br>
<input type="radio" name="type" value="emergency" checked> Emergency<br>
<input type="radio" name="type" value="guardian" checked> Guardian<br>
<input type="radio" name="type" value="other" checked> Other<br>
<input type="submit" value="Submit" />
</form>
<div id="alert"></div>
</body>
</html>
And the accompanying .gs file:
var AlternativeContact = ObjectModel("AlternativeContacts");
function newContact() {
var htmlOutput = HtmlService.createTemplateFromFile("new_contact");
var id = ACCOUNT_MANAGER.getRange("M4").getValue();
htmlOutput.data = {accountId: id};
UI.showSidebar(htmlOutput.evaluate());
}
function createContact(contactJSON) {
var newContact = new AlternativeContact(contactJSON);
newContact.save();
return "Success!";
}
The first line that uses ObjectModel is creating and ORM around the data sheet.
Thanks for the help!
Couple changes and it seems to be working in a basic way.
First, in the scriptlet, i needed to us the printing tag. so use in stead of . This was causing the value to not be used in the rendered template.
Second, I changed my jQuery to:
$(document).ready(function () {
$("input#accountId").val(<?= data.accountId ?>);
});
If anyone is able to answer, I'd be curious why using the $(document).ready is needed. Doesn't everything in the get run? is it an order of operation thing?
I am trying to figure out how to make one of the options in my select drop down a link that redirects to that page. So far from researching this I have only found a way to make all the options links that are redirected to (Load page on selection from dropdown form) but I only want one of the options to be a link. Also I need the link to work without hitting the submit button.
EDITED USING #VLADIMIR'S SUGGESTION:
<form method="get" id="searchform" name="searchform" action="<?php echo home_url(); ?>/">
<select name="posttype" id="selection">
<option name="Product" value="Product">Legal Documents</option>
<option name="videos" value="videos">Legal Advice - Videos</option>
<option value="http://www.testing.com">An Attorney</option>
</select>
<input name="s" id="s" class="s" type="text" onfocus="if(this.value=='<?php _e('');?>') this.value='';" onblur="if(this.value=='') this.value='<?php _e('');?>';" value="<?php _e('');?>" />
<button tabindex="2" type="submit" class="search_btn">
</button>
<?php wp_dropdown_categories( 'taxonomy=videoscategory&show_option_all=All Practice Areas' ); ?>
<?php wp_dropdown_categories( 'taxonomy=states&show_option_all=All U.S States' ); ?>
</form>
<script type="text/javascript">
$(document).ready(function() {
$("#selection").change(function() {
var curVal = $("#selection option:selected").val();
if (curVal.indexOf('http://') === 0) {
location = $("#selection option:selected").val();
}
});
});
</script>
Also is there a way to have one option with multiple values?
You can adapt solution from the Load page on selection from dropdown form
Replace JS code with
$(document).ready(function() {
$("#selection").change(function() {
var curVal = $("#selection option:selected").val();
if (curVal.indexOf('http://') === 0) {
location = $("#selection option:selected").val();
}
});
});
The idea is that you check the option value and if it begins with 'http://', then you set new location.
For example I have a form like this:
<form method='post' action='someaction.php' name='myform'>
<input type='text' name='text1'>
<input type='text' name='text2'>
<input type='checkbox' name="check1">Check Me
<textarea rows="2" cols="20" name='textarea1'></textarea>
<select name='select1'>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<input type='reset' value='Reset' name='reset'>
<input type='submit' value='Submit' name='submit'>
</form>
When I press Reset it empties all fields. But if I populate some fields using URL params and then press Reset, it only empties fields which I enter after form reload.
How can I empty all fields whether some fields are already populated at the time of form load.
As others pointed out, I think you should reconsider the need to blank the form.
But, if you really need that functionality, this is one way to do it:
Plain Javascript:
function resetForm(form) {
// clearing inputs
var inputs = form.getElementsByTagName('input');
for (var i = 0; i<inputs.length; i++) {
switch (inputs[i].type) {
// case 'hidden':
case 'text':
inputs[i].value = '';
break;
case 'radio':
case 'checkbox':
inputs[i].checked = false;
}
}
// clearing selects
var selects = form.getElementsByTagName('select');
for (var i = 0; i<selects.length; i++)
selects[i].selectedIndex = 0;
// clearing textarea
var text= form.getElementsByTagName('textarea');
for (var i = 0; i<text.length; i++)
text[i].innerHTML= '';
return false;
}
Note that I commented out the case in which I clear the hidden inputs. Most of the time, this is not necessary.
For this to work, you need to call the function from the onclick handler of a button (or some other way), e.g. like this:
<input type='reset' value='Reset' name='reset' onclick="return resetForm(this.form);">
You can test it all here on jsFiddle.
If you use jQuery in your project, you can do this with much less code (and no need to change the HTML):
jQuery(function($) { // onDomReady
// reset handler that clears the form
$('form[name="myform"] input:reset').click(function () {
$('form[name="myform"]')
.find(':radio, :checkbox').removeAttr('checked').end()
.find('textarea, :text, select').val('')
return false;
});
});
Also, note that I do not clear the values of hidden inputs, check-boxes and radio buttons.
Play with this here.
In jquery simply you can use,
$("#yourFormId").trigger('reset');
You will have to clear them all through javascript (or clear it out server side).
The reset button will only reset form elements to their initial value - if this was a specific value, that's what it will be reset to.
If you're using jQuery, the code is much simpler:
$('#my-form').not(':button, :submit, :reset, :hidden').val('').removeAttr('checked').removeAttr('selected');
You can also remove the :hidden from the .not selector if you want to clear hidden fields as well.
The easiest way to clear a form is by using the HTML tag
<input type="reset" value="Reset">
Example:
<form>
<table>
<tr>
<td>Name</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Reset</td>
<td><input type="reset" value="Reset"></td>
</tr>
</table>
</form>
A simple way to do it with JS:
<form id="myForm">
<!-- inputs -->
</form>
const { myForm } = document.forms;
myForm.reset();
I've summarized some of the suggestions using jQuery to give a more complete solution to the question:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Demo Forms</title>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
</head>
<body>
<form method='post' action='someaction.php' name='myform'>
<input type='text' name='text1'>
<input type='text' name='text2' value='preset value'>
<input type='checkbox' name="check1">Check Me
<textarea rows="2" cols="20" name='textarea1'></textarea>
<select name='select1'>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<input type='button' value='Reset' name='reset' onclick="return clearForm(this.form);">
<input type='submit' value='Submit' name='submit'>
<script>
function clearForm(form) {
var $f = $(form);
var $f = $f.find(':input').not(':button, :submit, :reset, :hidden');
$f.val('').attr('value','').removeAttr('checked').removeAttr('selected');
}
</script>
</form>
</body>
</html>
Note that I've added the inclusion of the jquery lib in the head section and added an onclick handler to the Reset button. Lastly, I've added the javascript code based on the feedback from some other answers here.
I have also added a preset value to one text field. The val('') function would not clear such a field, that's why I've also added attr('value','') to the last script line to clear such default values as well.
You can do something similar to this in JS and call it from onclick within your button:
function submit() {
$('#fieldIdOne').val('');
$('#fieldIdTwo').val('');
}
And then in your HTML file:
<button id="submit" onclick="submit(); return false">SIGN UP</button>
If you happen to use this solution with Firebase, it actually won't send anything to the database unless you add return false right after the call.
Another way to do that with HTMLFormControlsCollection:
for (let el of form.elements) el.value = null
I just came across this question and have used an <a> to facilitate clearing a form by reloading the page. It is easy to style an <a> element to appear as a button.
e.g.
Clear
By using ? for the href attribute, the <a> will reload the page from the server without submitting it.
I prefer solutions which do not depend on JavaScript so hopefully this is of some use to someone.
Using JavaScript give the form an ID of 'myform':
document.getElementById('myform').reset();