Creating efficient function instead of repetitive functions - javascript

I have a function which onclick displays the form.
Was wondering if there is any efficient way to code instead of creating 4 different functions for 4 different forms? Below example is for 4 forms but I am working with multiple forms.
<div class="navbar">
<div class="dropdown">
<button class="dropbtn" onclick="myFunction1()">Category 1
<i class="fa fa-caret-down"></i>
</button>
</div>
//Same for other 3 categories
<div id="form1" style = "display:none">
<form action="#" method="post" id="demoForm1" class="demoForm1" >
<fieldset>
<legend>Use CTRL to select multiple options</legend>
<p>
<select name="demoSel[]" id="demoSel" size="4" multiple>
<option value="ABC">ABC</option>
</select>
<input type="submit" value="Submit" />
<textarea name="display" id="display" placeholder="view select list value(s) onchange" cols="20" rows="4" readonly></textarea>
</p>
</fieldset>
</form>
</div>
//Same for other 3 forms
<script>
function myFunction1() {
document.getElementById("form1").style.display = '';
}
function myFunction2() {
document.getElementById("form2").style.display = '';
}
function myFunction3() {
document.getElementById("form3").style.display = '';
}
function myFunction4() {
document.getElementById("form4").style.display = '';
}
</script>

It's generally not a good idea to use inline event handlers.
Next, add a data-* attribute to each button and remove the onclick attribute like:
<button class="dropbtn" data-target="form1">...</button>
<button class="dropbtn" data-target="form2">...</button>
<button class="dropbtn" data-target="form3">...</button>
<button class="dropbtn" data-target="form4">...</button>
Then, you can use .addEventListener() on these buttons with class dropbtn and update respective form element display property like:
const btns = document.querySelectorAll(".dropbtn");
btns.forEach(function(btn) {
btn.addEventListener("click", function(cbox) {
document.getElementById(this.dataset.target).style.display = '';
});
});
Demo:
const btns = document.querySelectorAll(".dropbtn");
btns.forEach(function(btn) {
btn.addEventListener("click", function(cbox) {
document.getElementById(this.dataset.target).style.display = '';
});
});
<button class="dropbtn" data-target="form1">Form 1</button>
<button class="dropbtn" data-target="form2">Form 2</button>
<br><br>
<form id="form1" style="display:none">Form 1 Content Here</form>
<form id="form2" style="display:none">Form 2 Content Here</form>

Don't use on-event attributes:
<button onclick='eventHandler()'></button>
Use event listeners or on-event properties:
const btn = document.querySelector('button');
btn.addEventListener('click', eventHandler);
// OR
btn.onclick = eventHandler;
If you have multiple targets to click -- register the click event to a parent tag that all target tags share.
document.querySelector('main').onclick = toggleForm;
Instead of using .style on each <form> toggle classes
// CSS
.off { display: none }
// JavaScript
forms[idx].classList.toggle('off');
Demo
Note: Details are commented in demo
/*
- Reference the parent tag (<main>)
- Register <main> to the click event
- Event handler function toggleForm() is called on click
*/
document.querySelector('main').onclick = toggleForm;
// Event handler always passes Event Object (event)
function toggleForm(event) {
// Collect all <form>s into a HTML Collection
const forms = document.forms;
// Collect all <button> into a NodeList
const buttons = document.querySelectorAll('button');
// Reference the tag the user clicked (<button>)
const clicked = event.target;
// if a <button> was clicked...
if (clicked.matches('button')) {
// ...toggle the <button>'s .on and .off classes
clicked.classList.toggle('off');
clicked.classList.toggle('on');
/*
- Convert buttons NodeList into a rel Array
- Iterate through the buttons array and return
the index of the clicked <button>
*/
let idx = [...buttons].flatMap((button, index) => clicked === button ? [index] : []);
/*
- Toggle the .off class on the <form> located at the
index that was obtained from the previous statement
*/
forms[idx].classList.toggle('off');
}
}
button {
display: inline-block;
width: 11ch
}
button.off::before {
content: 'Show '
}
button.on::before {
content: 'Hide '
}
form.off {
display: none
}
<main>
<button class='off' type='button'>A</button>
<button class='off' type='button'>B</button>
<button class='off' type='button'>C</button>
<button class='off' type='button'>D</button>
<hr>
<form id='A' class='off'>
<fieldset>
<legend>Form A</legend>
</fieldset>
</form>
<form id='B' class='off'>
<fieldset>
<legend>Form B</legend>
</fieldset>
</form>
<form id='C' class='off'>
<fieldset>
<legend>Form C</legend>
</fieldset>
</form>
<form id='D' class='off'>
<fieldset>
<legend>Form D</legend>
</fieldset>
</form>
</main>

Related

Detect innerHTML of clicked button

I am trying to make the innerHTML of a single button (amongst various buttons) the value of an input.
I have an empty div inside a form and six buttons (each with the same class).
<form>
<div id='wrapper'></div>
<button type='submit'>Submit</button>
</form>
<div class="col-lg-6 Div1">
<button class="form-button" onclick="addForm()">Button 1</button>
<button class="form-button" onclick="addForm()">Button 2</button>
<button class="form-button" onclick="addForm()">Button 3</button>
</div>
<div class="col-lg-6 Div2">
<button class="form-button" onclick="addForm()">Button 4</button>
<button class="form-button" onclick="addForm()">Button 5</button>
<button class="form-button" onclick="addForm()">Button 6</button>
</div>
And then I have a dynamically added inputs, a button and a div. The inputs and buttons gets added into the div (.innerDiv) which get's added inside the #wrapper div (in the html code). The reason is so that the remove button can remove everything from it's parent element without removing all the dynamically added tags.
i = 1;
addForm() {
if(i < Infinity) {
var innerDiv = document.createElement('div');
innerDiv.classList = 'innerDiv' + i;
$('.wrapper').append(innerDiv);
//This adds a fixed input
var dynamicInput = document.createElement('input');
dynamicInput.type = 'text';
dynamicInput.name = 'dynamicInputName' +i;
dynamicInput.disabled = true;
dynamicInput.classList = 'dynamicInputClass';
$(".form-button").click(function() { dynamicInput.value = this.innerHTML; }); //Gives the innerHTML of the button that was clicked as the value of the input
$('.innerDiv' + i).append(dynamicInput);
var anotherInput = document.createElement('input');
anotherInput.type = 'text';
anotherInput.name = 'anotherInput' +i;
anotherInput.classList = 'anotherInputClass';
anotherInput.placeholder = 'Write name here';
$('.innerDiv' + i).append(anotherInput);
var removeButton = document.createElement('button'); //This removes one element inside a parent div.
removeButton.type = 'button';
removeButton.classList = 'remove';
removeButton.innerHTML = '-';
removeButton.onclick = function () {
this.parentElement.remove();
}
$('.innerDiv').append(removeButton);
i++;
}
}
I've fixed the function for the dynamicInput to what was suggested to me by s.Bergmann. So whenever a button with the class of .form-button is clicked, all the above stiff will be added and the dynamicInput will have a fixed value of the button that was clicked. If I click Button 5 and then Button 2, in code, it will look a little something like this:
<form>
<div id='wrapper'>
<div class='innerDiv1'>
<input type='text' name='dynamicInputName1' class='dynamicInputClass' value='Button 2' disabled>
<input type='text' name='anotherInput1' class='anotherInputClass' placeholder='Write name here'>
<button type='button' class='remove'>-</button>
</div>
<div class='innerDiv2'>
<input type='text' name='dynamicInputName2' class='dynamicInputClass' value='Button 2' disabled>
<input type='text' name='anotherInput2' class='anotherInputClass' placeholder='Write name here'>
<button type='button' class='remove'>-</button>
</div>
</div>
<button type='submit'>Submit</button>
</form>
As you can see, each button added one div, with the two inputs and the button. However, both inputs that were created from the dynamicInput have the same value (Button 2.). The idea is, if I press Button 5 first the first dynamicInput should have a value = 'Button 5' and if I then press Button 2, the second dynamicInput should have a value = 'Button 2' (These inputs are the first input of each div).
I'm not sure this is what you're going for,
but it might nudge you in the right direction.
It seems that onclick on a .form-button two things should happen:
it should create a dynamic input element
addForm() should be called // or perhaps addForm is what creates the input element?
If i were you, i'd reconsider the need for that "dynamic element". why not just use the actual button clicked?
anyway...
$(".form-button").click(function () { // replaces all the onlick=
addForm(this);
var dynamicInput = document.createElement('input');
dynamicInput.type = 'text';
dynamicInput.name = 'dynamicInputName';
dynamicInput.disabled = true;
dynamicInput.classList = 'dynamicInputClass';
dynamicInput.value = this.innerText;
console.log("Dynamic input", dynamicInput.value);
});
function addForm (formButton) { // dummy function? unclear what it's used for.
console.log("Form Button:", formButton)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg-6 Div1">
<button class="form-button"> Button 1</button>
<button class="form-button">Button 2</button>
<button class="form-button">Button 3</button>
</div>
<div class="col-lg-6 Div2">
<button class="form-button">Button 4</button>
<button class="form-button">Button 5</button>
<button class="form-button">Button 6</button>
</div>

Possible to embed html in an if statement?

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.

how to display the array of values for the single field using jquery?

Here I need to get all the values entered in the input field. But it echoes only the first value.
ie. When I press the + and give some values, I need to get that value too.
$(document).ready(function() {
$(document).on("click", ".add", function() {
var clone = '<div class="add1"><input type="text" name="selprice" /><input type = "submit" value = "+" class = "add" ><input type = "submit" value = "-" class = "remove" ></div>';
$(this).closest('.add1').after(clone);
});
$(document).on("click", ".remove", function() {
$(this).parent(".add1").remove();
});
});
$('#package').change(function() {
var arr = [];
$("input.packageclass").each(function() {
arr.push($(this).val());
alert(arr);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div class="add1">
<h6>Sales Package </h6>
<div>
<input type="text" name="package" placeholder="Ex:34" id="package" class="packageclass">
<input type="submit" value="+" class="add"></div>
</div>
$('.package').change(function() {
You are using an ID in your input type="text". IDs are only used once. If you want to add the listener to all of your textfields use classes.
In addition to that the .change(function() is only once called, when the dom is ready. That will be a problem too. So the change listener is not added to the generated textfields. Maybe you use something like...
$('.package').on('change', 'input', function() {
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div class="add1">
<h6>Sales Package </h6>
<div>
<input type="text" name="package" placeholder="Ex:34" id="package" class="packageclass">
<input type="submit" value="+" class="add">
</div>
</div>
<script type="text/javascript">
var addInput = function(e) {
var arr = [];
$("input.packageclass").each(function() {
arr.push($(this).val());
});
alert(arr);
};
$(document).ready(function() {
$(document).on("click", ".add", function() {
var clone = '<div class="add1"><input class="packageclass" type="text" name="selprice" /><input type = "submit" value = "+" class = "add" ><input type = "submit" value = "-" class = "remove" ></div>';
$(this).closest('.add1').after(clone);
$('.packageclass').unbind().bind('change', addInput);
});
$(document).on("click", ".remove", function() {
$(this).parent(".add1").remove();
});
});
$('.packageclass').unbind().bind('change', addInput);
</script>
Just using loop you can get the particular value from loop.
for (var i = arr.length - 1; i >= 0; i--) {
arr[i];
//work with arr[]
}
I have used event delegation to capture the events and take appropriate action.
In this, you can add a event listener to your parent element i.e., click to the .body in my case. When I click on the .add button, the event propagates and .body click handler gets invoked. By checking for event.target we can find out the origin of event and add or remove the divs.
Similary we can listen for the change event of the input boxes and take appropriate actions.
$('#body').click(function(e) {
if(e.target.className === 'add') {
$('#body').append(`
<div class="add1">
<input type="text" name="package" placeholder="Ex:34" id="package" class="packageclass">
<button class="add">+</button>
<button class="remove">-</button>
</div>
`);
}
if(e.target.className === 'remove') {
$(e.target).parent().empty();
}
});
$('#body').change(function(e) {
console.log(e.target.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div id="body">
<h6>Sales Package </h6>
<div class="add1">
<input type="text" name="package" placeholder="Ex:34" id="package" class="packageclass">
<button class="add">+</button>
</div>
</div>
Just add class="packageclass" to the input when creating your clone variable.
https://jsfiddle.net/289xvmu7/
var clone = '<div class="add1"><input type="text" name="selprice" class="packageclass"/> <input type = "submit" value = "+" class = "add" ><input type = "submit" value = "-" class = "remove" ></div>';

How to display user input with a Javascript function

I'm trying to display the user input through the submit button. The user will input tool types and then the first five inputs will be displayed in the li's. Then as the limit of 5 tools is reached, another function prints 'Thanks for your suggestions'. However, I can't get the function to print out any of the user input for suggested tools. Could someone help me understand why they aren't printing out?
<script src="modernizr.custom.05819.js">
var i = 1;
var listItem = "";
function processInput() {
if (i <= 5) {
listItem[0] += 1;
listItem = toolBox;
var toolBox = "";
alert("This is running");
if (i == 5) {
var resultsExpl = "Thanks for your suggestions";
}
}
var backSubmit = document.getElementById("button");
if (backSubmit.addEventListener) {
backSubmit.addEventListener("click", calcTotal, false);
} else if (backsubmit.attachEvent) {
backSubmit.attachEvent("onclick", calcTotal);
}
}
</script>
<div id="results">
<ul>
<li id="item1"></li>
<li id="item2"></li>
<li id="item3"></li>
<li id="item4"></li>
<li id="item5"></li>
</ul>
<p id="resultsExpl"></p>
</div>
<form>
<fieldset>
<label for="toolBox" id="placeLabel">
Type the name of a tool, then click Submit:
</label>
<input type="text" id="toolBox"/>
</fieldset>
<fieldset>
<button type="submit" id="button" onclick="processInput()">Submit</button>
<button type="button" id ="reset" onclick="resetForm()"/>Reset</button>
</fieldset>
</form>
Here's the working DEMO to your problem.
I have removed the button type as submit because in some browsers instead of calling the function processInput it will submit the form.
Here is my JavaScript that I changed,
var count=1;
function processInput(){
var tool = document.getElementById("toolBox").value;
document.getElementById("toolBox").value = "";
if(count==5){
document.getElementById("resultsExpl").innerHTML = "Thanks for your suggestions";
document.getElementById("item"+count).innerHTML = tool;
}else{
document.getElementById("item"+count).innerHTML = tool;
count++;
}
}
function resetForm(){
document.getElementById("results").innerHTML = '<ul><li id="item1"></li><li id="item2"></li><li id="item3"></li><li id="item4"></li><li id="item5"></li><p id="resultsExpl"></p></ul>';
}
The only change I made to your HTML code was to add formId as the id for your form.
<div id="results">
<ul>
<li id="item1"></li>
<li id="item2"></li>
<li id="item3"></li>
<li id="item4"></li>
<li id="item5"></li>
</ul>
<p id="resultsExpl"></p>
</div>
<form id="formId">
<fieldset>
<label for="toolBox" id="placeLabel">
Type the name of a tool, then click Submit:
</label>
<input type="text" id="toolBox"/>
</fieldset>
<fieldset>
<button type="button" id="button" onclick="processInput()">Submit</button>
<button type="button" id ="reset" onclick="resetForm()"/>Reset</button>
</fieldset>
</form>
For me not much of this was working so I modified your code a bit to this working example. Each input fills in the <li> fields in order. On the 5th entry, you get alerted, and on the reset button the <li>'s are blanked out. Was not sure if this is what you were going for specifically but it sounded like it
var i = 1;
function processInput() {
if (i <= 5) {
document.getElementById('item' + i).innerHTML = document.getElementById('toolBox').value;
document.getElementById('toolBox').value = '';
if (i == 5) {
alert('Thank you for your suggestions');
} else {
i++;
}
}
}
function resetForm() {
while (i >= 1) {
document.getElementById('item' + i).innerHTML = '';
i--;
}
i = 1;
}
<div id="results">
<ul>
<li id="item1"></li>
<li id="item2"></li>
<li id="item3"></li>
<li id="item4"></li>
<li id="item5"></li>
</ul>
<p id="resultsExpl"></p>
</div>
<form>
<fieldset>
<label for="toolBox" id="placeLabel">
Type the name of a tool, then click Submit:
</label>
<input type="text" id="toolBox"/>
</fieldset>
<fieldset>
<button type="button" id="button" onclick="processInput()">Submit</button>
<button type="button" id ="reset" onclick="resetForm()"/>Reset</button>
</fieldset>
</form>
I'll try to list some of the problems you have into your code:
Defining a script tag with the src attribute, and writing code inline, this will never work
Defining some global variables, and although this isn't a bug, it's a really bad design
Declaring a variable listItem as an empty string, and then using its 1st character to increment a Number, I don't realize exactly what you're trying to do here.
Then, you set an undefined/undeclared toolBox variable to the listItem string
And, afterall, you add a click event handler to the submit button, but to an undefined callback
Well, since your code doesn't make much sense for me, but I think I got what you're trying to achieve, I've made an example of your code updated, and you can check the full commented code below:
/* we encapsulate your hole code into an IIFE (Immediately-Invoked Function Expression)
the goal here is to not polute the global scope, so the variable declarations reside inside it */
(function(d) {
/* that's the counter you already had, I renamed it from i to item */
var item = 1;
/* we cache all the elements we're going to use here, by getting them by id */
var txt = d.getElementById('toolBox'),
btn = d.getElementById('button'),
reset = d.getElementById('reset'),
results = d.getElementById('results'),
resultsExpl = d.getElementById('resultsExpl');
/* we add the 'click' event handlers to our buttons
it's better than puting directly inside the HTML, because it's a better design
this approach is known as Unobstrusive Javascript */
btn.addEventListener('click', processInput);
reset.addEventListener('click', resetForm);
/* your processInput function, with the same logic you had, but fixed */
function processInput() {
if (item <= 5) {
/* here, we get the li tag by its id, concatenating the string 'item' to our variable item */
var li = d.getElementById('item' + item);
/* we must use the property textContent to change the text of the li
and we get the user's input by getting its property value */
li.textContent = txt.value;
/* then, we increment our counter. the code below is the same as item += 1 */
item++;
}
/* if the last item was inserted, we show our message */
if (item > 5) {
resultsExpl.textContent = 'Thanks for your suggestions';
}
}
function resetForm() {
/* to reset our form, firstly I loop through all the lis inside the div results */
[].forEach.call(results.querySelectorAll('li'), function(el, i) {
/* and I change each li textContent property to an empty string */
el.textContent = '';
});
/* then, we set our input's value to empty, and we also reset our item variable to 1 */
txt.value = '';
item = 1;
}
})(document); /* I'm passing the document as a parameter, so I can use inside the IIFE as the variable d */
<div id="results">
<ul>
<li id="item1"></li>
<li id="item2"></li>
<li id="item3"></li>
<li id="item4"></li>
<li id="item5"></li>
</ul>
<p id="resultsExpl"></p>
</div>
<form>
<fieldset>
<label for="toolBox" id="placeLabel">
Type the name of a tool, then click Submit:
</label>
<input type="text" id="toolBox" />
</fieldset>
<fieldset>
<button type="submit" id="button">Submit</button>
<button type="button" id="reset">Reset</button>
</fieldset>
</form>
A little tidied up version of Saumil Soni's post:
var count=1;
var done;
function processInput(){
var tool = document.getElementById("toolBox").value;
if (done!=1) {
document.getElementById("toolBox").value = "";
}
if(count==5){
if (done!=1) {
document.getElementById("resultsExpl").innerHTML = "Thanks for your suggestions";
document.getElementById("item"+count).innerHTML = tool;
done = 1;
}
}else{
if (done!=1) {
document.getElementById("item"+count).innerHTML = tool;
count++;
}
}
}
function resetForm() {
location.reload();
}
<div id="results">
<ul>
<li id="item1"></li>
<li id="item2"></li>
<li id="item3"></li>
<li id="item4"></li>
<li id="item5"></li>
</ul>
<p id="resultsExpl"></p>
</div>
<form id="formId" onSubmit="processInput(); return false;">
<fieldset>
<label for="toolBox" id="placeLabel">
Type the name of a tool, then click Submit:
</label>
<input type="text" id="toolBox"/>
</fieldset>
<fieldset>
<button type="button" id="button" onclick="processInput()">Submit</button>
<button type="button" id ="reset" onclick="resetForm()"/>Reset</button>
</fieldset>
</form>

Polymer update datalist

I'm making a polymer element with some requirements. I've a list (ul) and two input fields. I need that one of the inputs update my list (there's no problem here). The other input should be able to define some default values for the first input, here I'm using a datalist.
I wrapped all in a polymer element. That's when I started having problems. I'm trying to update the datalist inside the polymer element, the datalist is updated but the input doesn't show the new hints.
Also, I've noticed that if I have more than one of these elements all the input binds with the datalist of the first element. I don't understand this behaviour. Each element must bind to the list inside her scope.
One more thing that I need to figure out is how can I delete some of default values added.
Here is my code:
<dom-module id="test-input" attributes="edit list type">
<template>
<!-- Here I have the first input that creates a list and I need to be binded with a datalist-->
<div id="container">
<div id="display" on-click="_openEdit">
<div id="textDescription" class="textDescription">{{description}}</div>
<ul id="list" class="list"></ul>
<form id="addContainer" class="addContainer" action="#" method="post">
<label for="newitem">{{label}}</label>
<!--<input type="text" name="newitem" id="newitem" placeholder="{{placeholder}}" required>-->
<input list="defaultValues" name="newitem" id="newitem" placeholder="{{placeholder}}" required>
<!-- I've added this options so we can see that it's working but when the datalist is updated it doesn't show-->
<datalist id="defaultValues">
<option value="option added on html"></option>
<option value="option added on html 2"></option>
</datalist>
<input type="submit" id="addToList" value={{buttonText}}>
</form>
</div>
<!-- Here I have the second input that updates the datalist default values-->
<div id="edit">
<div id="extendedList">
<div>Enter the default values</div>
<form id="extendedAddContainer" class="addContainer" action="#" method="post">
<label for="extendedNewitem">{{label}}</label>
<input type="text" name="extendedNewitem" id="extendedNewitem"
placeholder="enter default values" required>
<input type="submit" id="extendedAddToList" value={{buttonText}}>
</form>
</div>
</div>
</div>
</template>
<script>
defaultValueCounter = 0;
function isEmpty(str) {
return !str.replace(/^\s+/g, '').length; // boolean (`true` if field is empty)
}
Polymer({
is: "test-input",
properties: {
buttonText: {
type: String,
value: "Add"
}
},
ready: function () {
/* Start: add input to list */
var list = this.$.list,
field = this.$.newitem,
form = this.$.addContainer;
form.addEventListener('submit', function (ev) {
if (field.validity.valid && !isEmpty(field.value)) {
list.innerHTML += '<li class="style-scope list-input">' + field.value + '</li>';
field.value = '';
field.focus();
ev.preventDefault();
}
}, false);
list.addEventListener('click', function (ev) {
var t = ev.target;
if (t.tagName === 'LI') {
t.parentNode.removeChild(t);
}
ev.preventDefault();
}, false);
/* End: add input to list */
/* Start: Add default values */
var extendedList = this.$.defaultValues,
extendedField = this.$.extendedNewitem,
extendedForm = this.$.extendedAddContainer,
container = this.$.extendedList,
defaultList = this.$.defaultList;
extendedForm.addEventListener('submit', function (ev) {
ev.preventDefault();
/* Here I add things to the datalist */
if (extendedField.validity.valid && !isEmpty(extendedField.value)) {
aux = document.createElement("option");
aux.value = extendedField.value;
extendedList.appendChild(aux);
extendedField.value = '';
extendedField.focus();
}
}, false);
}
/* End: Add default values */
});
</script>
</dom-module>
Thanks in advance!

Categories