I have a 'users page'. I would like to give a textbox for entering the no. of users. On click of submit 'n' no of user forms need to be presented to user.
User1
first name -
last name -
User2
first name -
last name -
.
.
.
UserN
first name -
last name -
I don't know the value of 'N' upfront. So it won't be a good idea to write multiple 'divs' in my html.
Requirement:Rather I want to have a user template div. And copy the template 'n' times depending on the value of 'n' in the textbox. But I would also want all the 'divs' to have different ids like 'user1', 'user2' etc.
I cannot figure out a way to do this apart from populating my html with too many 'divs'. Would need help achiving the Requirement specified.
Looking for a template like:-
<div id="user-template" class="hidden">
<label class="lbl"><b>Handle:</b></label><input type="text" id="first_name" value=""/>
</div>
And wanted to have id="user-template" change for all new divs.
You can try something like this:
You can make a template and append it to the DOM for the number entered in the input field.
$(document).ready(function() {
$("#createForms").click(function() {
var numOfForms = $("#numOfForms").val();
var template = $('#hidden-template').html();
for (var i = 0; i < numOfForms; i++) {
$('#targetDiv').append("<p>User" + (i + 1) + ":</p>");
$('#targetDiv').append(template);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="numOfForms"></input>
<input type="button" id="createForms" value="Get Fields"></input>
<div id="targetDiv"></div>
<script id="hidden-template" type="text/x-custom-template">
<div id="user-template" class="hidden">
<p>First Name:
<input type="text" name="firstName"></input>
</p>
<p>Last Name:
<input type="text" name="lastName"></input>
</p>
<br>
</div>
</script>
A simple way is to write a function that takes the n value and returns the actual dom that you can append to some parent element on your page. A simple example below:
function createNDivs(n) {
if(!n) return;
var fragment =document.createDocumentFragment();
for(var i=0;i<n;i++) {
var div = document.createElement('div');
fragment.appendChild(div);
}
return fragment;
}
Related
I have a program that is supposed to group links together. Like minecraft saved toolbars, you can save a collection of links, then enter in the name of a group and it will open all of them.
But my program is having trouble with getting the list from localStorage when the name is entered into the text box meant to get the link. But when I just use the value of the text box meant to name the group, it works fine.
My code is here:
var groupName = document.getElementById('name');
var link = document.getElementById('newLink');
var linkCounter = 0
var getByName = document.getElementById('getByName').value
function startGroup() {
localStorage.setItem(groupName.value, groupName.value);
console.log(localStorage.getItem(groupName.value))
}
function addLink() {
linkCounter++;
localStorage.setItem(groupName.value + '_link' + linkCounter, link.value);
console.log(localStorage.getItem(groupName.value + '_link' + linkCounter))
}
function saveGroup() {
localStorage.setItem(groupName.value + '_length', linkCounter);
console.log(localStorage.getItem(groupName.value + '_length'))
alert(groupName.value);
}
function getGroup() {
// if I replace getByName with groupName.value, it works fine.
var len = localStorage.getItem(getByName + '_length')
console.log(len)
for (var x = 1; x <= len; x++) {
window.open(localStorage.getItem(getByName + '_link' + x));
}
}
<!DOCTYPE html>
<html>
<a href='readit.html'>READ THIS BEFORE USING</a>
<p>WHEN ADDING A LINK YOU NEED TO PASTE IT OR ADD HTTPS:// TO THE BEGINNING OF THE LINK.</p>
<div id='toolbars'>
<p>Open a group!</p>
</div>
<div id='create'>
<p>Create some bookmark groups!</p>
<input type='text' placeholder='name your group' id='name'>
<button onclick='startGroup()'>Let's add some links!</button>
<br>
<input type='text' placeholder='add a link' id='newLink'>
<button onclick='addLink()'>Submit</button>
<br>
<button onclick='saveGroup()'>SAVE</button>
</div>
<div id='preview'>
<br><br>
<button onclick='getGroup()'>Open this group</button>
<input type="text" id="getByName">
</div>
</html>
<script src="script.js"></script>
You are reading the value of the getByName input element at page load. Instead you should read the value at the time of need. So define getByName as the DOM element (not as its value):
var getByName = document.getElementById('getByName');
And where you currently reference getByName, suffix the .value property accessor. For instance:
var len = localStorage.getItem(getByName.value + '_length');
Side note: I find it easier to use a memory data structure for all your data, and when something is added to it, to write that complete data structure to one single local storage key, JSON formatted. You may want to look into that.
I'm trying to make a sort of questionnaire/quiz in javascript for my website. The questionnaire is spread on 5 pages, each page has a question. I want to use the GET method so the URL of each page looks something like that:
(I must keep the GET method because I want to use for something else).
First question: http://website.com/quiz/first?q=1
Second question: http://website.com/quiz/second?q=133
Third question: http://website.com/quiz/third?q=133
Fourth question: http://website.com/quiz/fourth?q=1332
Fifth question: http://website.com/quiz/fifth?q=13324
The user lands on the first page --> get a radio input form --> checks one --> gets redirected to the second page --> etc...
The ?q= is a variable containing the answers, for example ?q=133 means the user picked the following answers:
In the first question, he checked the radio input of the value 1
In the second question, he checked the radio input of the value 3
In the third question, he checked the radio input of the value 3
(so 133 means the user check the 1 for the first question, 3 for the second, 3 for the third.)
I managed to make the variables work:
answPre: gets the previous answer from the form GET (?q=1).
answCurrent: gets the radio input checked from the current page.
urlVal: an combination of the two (answPre+answCurrent)
so I'd like urlVal to be the value that gets transferred from a page to the other.
But I don't want to have both urlVal and the "q" value (name of checked radio) in the url.
What's the right thing to do?
can I hide the "q" value from the URL?
or can I "overwrite" the q value and put instead urlVal?
I'm lost and would appreciate any help, thanks for your help and your time!
function displayRadioValue() {
// var pageURL = window.location.href;
var fakeURL="website.com/quiz/first?q=1"
var answPre = fakeURL.substr(fakeURL.lastIndexOf('=') + 1); //get the previous page's answer.
//get the current page's answer
var ele = document.getElementsByName('q');
for(j = 0; j < ele.length; j++) {
if(ele[j].checked)
var answCurrent= document.getElementById("demo2").innerHTML = ele[j].value;
}
var array = [answPre,answCurrent]; //combine answPre + answNew
var urlVal = "";
var i;
for (i = 0; i < array.length; i++) {
urlVal += array[i];
}
document.getElementById("demo1").innerHTML = answPre;
document.getElementById("demo3").innerHTML = urlVal;
//document.getElementById("fquiz").submit();// Form submission
}
<html>
<body>
<h2>second.html</h2>
<b>answPre: </b><span id="demo1"></span><br>
<b>answCurrent: </b><span id="demo2"></span><br>
<b>urlVal: </b><span id="demo3"></span><br>
<!-- <b>final answNew: </b><span id="demo4"></span><br> -->
<hr>
<form id="fquiz" method="GET" action="third.html">
<p>Who are you going with?</p>
<input type="radio" name="q" value="1" id="yes"
onClick="javascript: displayRadioValue()">Solo<br>
<input type="radio" name="q" value="2" id="no"
onClick="javascript: displayRadioValue()">Couple<br>
<input type="radio" name="q" value="3" id="no"
onClick="javascript: displayRadioValue()">Family with kids<br>
<input type="radio" name="q" value="4" id="no"
onClick="javascript: displayRadioValue()">Group of friends<br>
<p>(then it takes you to third.html with hopefully this url: ../third.html?q=XX where XX is urlVal)
</form>
</body>
</html>
I've made a few changes to your code to modernize it a bit.
I moved the binding of the event handlers to the JavaScript from the HTML. Generally speaking I like to keep my HTML about the structure and the JavaScript about the behavior.
I added code to grab the step from the URL in addition to the previous answers.
I used querySelector to retrieve the selected radio button, using the :checked pseudo-selector.
I used join('') on the array of answers to make it easier to read.
In the HTML, I used <p> elements for everything that needed to be in one line, rather than tacking a <br> at the end of each line. That's just a personal preference.
I wrapped the radio buttons and their text in <label> elements. This helps in accessibility and to give a larger target for people to click on (clicking on the entire label checks the radio, rather than just the radio itself).
I also changed the name of the URL parameter to urlVal rather than q, but I'm not sure I understood that part of your question. I'm not using the form submission process at all with this code, relying instead on changing the location directly...
Do note that running the code here on Stack Overflow won't redirect correctly, since of course there's nothing at example.com/quiz/second listening, and Stack Snippets are sandboxed anyway. You'll need to adjust the code for your specific use in any case.
// Use JavaScript to attach event handlers to HTML elements.
document.querySelectorAll('input[name="q"]').forEach(el => el.addEventListener('click', displayRadioValue));
function displayRadioValue() {
// var pageURL = window.location.href;
var fakeURL = "example.com/quiz/first?q=1"
var step = fakeURL.substring(fakeURL.lastIndexOf('/') + 1, fakeURL.indexOf('?'));
var answPre = fakeURL.substr(fakeURL.lastIndexOf('=') + 1); //get the previous page's answer.
//get the current page's answer
// The :checked pseudo-class makes it easier to find the checked radio button
var el = document.querySelector('input[name="q"]:checked');
var answCurrent = document.getElementById("demo2").innerHTML = el.value;
var array = [answPre, answCurrent]; //combine answPre + answNew
// The join method is easier to use than looping.
var urlVal = array.join('');
document.getElementById("demo1").innerHTML = answPre;
document.getElementById("demo3").innerHTML = urlVal;
switch (step) {
case 'first': step = 'second'; break;
case 'second': step = 'third'; break;
case 'third': step = 'final'; break;
default: return;
}
location.href = `example.com/quix/${step}?urlVal=${urlVal}`;
}
.form-group { margin: 0; }
<h2>second.html</h2>
<!-- <br> is a presentational element; better just to split up lines with paragraphs -->
<p class="form-group"><b>answPre: </b><span id="demo1"></span></p>
<p class="form-group"><b>answCurrent: </b><span id="demo2"></span></p>
<p class="form-group"><b>urlVal: </b><span id="demo3"></span></p>
<!-- <p class="form-group"><b>final answNew: </b><span id="demo4"></span></p> -->
<hr>
<form id="fquiz" method="GET" action="third.html">
<p>Who are you going with?</p>
<!-- <br> is a presentational element; better just to split up lines with paragraphs -->
<!-- Always use <label> elements to label form fields -->
<!-- IDs must be unique to a document. They did not appear relevant here. -->
<p class="form-group"><label><input type="radio" name="q" value="1">Solo</label></p>
<p class="form-group"><label><input type="radio" name="q" value="2">Couple</label></p>
<p class="form-group"><label><input type="radio" name="q" value="3">Family with kids</label></p>
<p class="form-group"><label><input type="radio" name="q" value="4">Group of friends</label></p>
<p>(then it takes you to third.html with hopefully this url: ../third.html?q=XX where XX is urlVal)</p>
</form>
I am attempting to preview my name and step element in my form, so the user can see if they have made a mistake. I am able to preview the step however the name just won't work. Can anyone see why?
http://jsfiddle.net/pocockn/rw54b/
$(document).ready(function() {
var commentNode = $('#lp-step'),
nameNode = $('#lp-name'),
name = $('#name');
$('#live-preview-form input, #live-preview-form textarea').bind('blur keyup',function() {
commentNode.text($('#step_1').val());
commentNode.html($('#lp-step').html().replace(/\n/g,'<br />'));
if($('#name').val()) {
nameNode.text(name.val() + ' says:');
}
else {
return false;
}
});
});
You can't have two elements with the same ID, if you do it will only select the first element it finds. (in this case its the div which is always empty and never runs your if statement). You have your div with id=name and your input. So I changed your div id to nameDiv instead.
Id's should be unique to avoid confusion.
<div id="nameDiv">
<label for="name">Enter recipe name:</label>
<input type="text" id="name" name="name">
<br />
</div>
http://jsfiddle.net/trevordowdle/rw54b/1/
is there a way to write the same thing clientside using javascript to multiple divs or multiple spots on a page?
I have a php script outputting rows from a database. To edit the contents, I would like to insert a checkbox before each row as with the iphone edit contacts and to do it quickly, I'm trying to use javascript to populate a div with a checkbox before each row using getElemenByID.
One problem is you cannot have more than one div of the same name on a page so I can't write once and have it populate multiple divs of the same name. If I give divs different names than I have to write multiple times which is not appealing especially as the number of rows may vary.
As a related question would checkboxes inserted using javascript even work?
Here is non working code:
js
function edit() }
var box = '<input type="checkbox name=num[]>';
var target = "checkbox";
document.getElementById(target).innerHTML = box;
return;
}//end function
html (generated by PHP from dbase)
<form action="edit.php" method="post">
<a href="javascript:void" onclick="edit()";>edit</a>
<div id="checkbox"></div>Row1 contents<br>
<div id="checkbox"></div>Row2 contents<br>
<form type = "submit" value="Edit">
</form>
Does anyone know a way to do this ie make boxes appear that can then be selected for submission?
Many thanks for any suggestions.
Should be generated using PHP instead, but...
HTML
I'm guessing that you want to use a span element (not a div) for your checkbox placeholder, otherwise you'd have a checkbox on one line, and then "Row1 contents" below the checkbox, versus having the checkbox next to the text.
[X]
Row 1 Contents
versus (span)
[X] Row 1 Contents
<form action="edit.php" method="post" name="frmRows" id="frmRows">
edit
<span class="checkbox"></span>Row1 contents<br>
<span class="checkbox"></span>Row2 contents<br>
<input type = "submit" value="Edit">
</form>
JavaScript
It's not recommended to use .innerHTML in JavaScript unless absolutely necessary (not supported in all browsers, and there are better ways to accomplish the same task.)
function edit() {
var newCb;
var i;
var checkboxList = document.getElementsByClassName( 'checkbox' );
for ( i = 0; i < checkboxList.length; i++ ) {
newCb = document.createElement( 'input' ); // Create a new input element
newCb.setAttribute( 'type', 'checkbox' ); // Set attributes for new element
newCb.setAttribute( 'value', 'SomeValueHere' );
newCb.setAttribute( 'name', 'checkboxName' );
newCb.setAttribute( 'id', 'checkbox-' + i );
checkboxList[i].appendChild( newCB ); // Add checkbox to span.checkbox
}
}
The ID attribute must be unique on each page. You could use the class attribute like this:
<div class="checkbox"></div>Row1 contents<br>
<div class="checkbox"></div>Row2 contents<br>
and then you can use
var check = getElementsByClassName('checkbox');
for (var i=0; i< check.length; i++) {
check[i].innerHTML = box;
}
But... this will not work in IE < 9. If you are using a framework like jQuery they already implemented a workaround for this but with pure JS you have to implement this yourself.
jQuery example
HTML
<div class="checkbox"></div>Row1 contents<br>
<div class="checkbox"></div>Row2 contents<br>
JS
var box = '<input type="checkbox" name="num[]" />';
$(".checkbox").html(box);
The HTML
The first thing to do is to update the generated HTML. In HTML element id attributes should be unique just like field names inside a form. To classify multiple elements as similar you should use the class attribute.
Here is an example of how you could structure the HTML.
<form action="edit.php" method="post">
edit
<div id="row1Identifier" class="editCheckbox"></div>Row1 contents</br>
<div id="row2Identifier" class="editCheckbox"><?div>Row2 contents</br>
<input type="submit" value="Submit">
</form>
The javascript
Using document.getElementsByClassName will return a list of elements with the matching class.
function edit () {
// set up the variables used in this function
var checkboxDivs = document.getElementsByClassName('editCheckbox'),
i,
loopDiv;
// make the change to each div
for (i = 0; i < checkboxDivs.length; i += 1) {
loopDiv = checkboxDivs[i];
loopDiv.innerHTML = '<input type="checkbox" name="' + loopDiv.id + '">';
}
}
Even if you could do it with a single line (using jQuery, for exemplo), you would actually be running a loop through all the divs (that's the only way to change something in various elements: change it in each one).
So you can do this with pure JavaScript using a loop to run the modifications in all the divs, getting them by id (the faster way):
for(var i = 0; i < numberOfDivs; i++){
document.getElementById("myElement" + i).innerHTML = box; //concatenating i to a base id
}
You could also use another slower techniques to get elements by tag name or class, or even use a lib such as jQuery.
If you use jquery:
function edit() {
// box = '<input type="checkbox name=num[]>';
var target = "checkbox";
$(".cb").html(box);
return;
}//end function
<form action="edit.php" method="post">
edit
<div class="cb" id="checkbox">aa</div>Row1 contents<br>
<div class="cb" id="checkbox">bb</div>Row2 contents<br>
</form>
I have a simple HTML form that asks a user to input their name, SKU, quantity, and comments. This is for a simple inventory request system.
<html>
<body>
<form id="myForm" method="post">
<input type="submit">
<br>Name: <input type="text" name="form[name]">
<br>SKU: <input type="text" name="form[SKU1]">
<br>Quantity: <input type="text" name="form[quantity1]">
<br>Comment: <input type="text" name="form[comment1]">
</form>
Add item
<script>
var num = 2; //The first option to be added is number 2
function addOption() {
var theForm = document.getElementById("myForm");
var newOption = document.createElement("input");
newOption.name = "form[SKU"+num+"]"; // form[varX]
newOption.type = "text";
theForm.appendChild(newOption); //How can I add a newline here?
optionNumber++;
}
</script>
</body>
</html>
Currently I can only get it working where it will add a single form value. I would like to recreate the entire myForm except for the name field with a single click.
Your post is very old, so presumably you've found an answer by now. However, there are some things amiss with your code.
In the JavaScript code you have
var num = 2;
This is the number that is incremented to keep track of how many "line-items" you will have on the form. In the function addOption(), though, instead of incrementing num you have
optionNumber++;
You never use optionNumber anywhere else. Your code works once, when you add the first item, but since you increment the wrong variable, you are effectively always adding option 2.
Oh, and adding the newline: you need to append a <br> element.