I would like to know how could I create many <input type=text /> tags with a loop in JS.
I need that loop to be linked to a first input (type=number), which tell to the loops how many input text to create.
function getP () {
var nbP = Number(document.getElementById("nombreP").value);
for (var i = 0; i < nbP; i++) {
var newForm = document.createElement("input[type=text]");
newForm.id = "form"+i
document.body.appendChild(newForm);
}
}
<form method="get">
<input type="number" name="nombrePlat" id="nombreP">
<input type="submit" value="Envoyer" id="ok" onclick="getP()">
</form>
Direct answer to your question:
<script type="text/javascript">
function getP() {
var nbP = +document.getElementById("nombreP").value;
var inputContainer = document.getElementById("inutContainer");
for (var i = 0; i < nbP; i++) {
var newForm = document.createElement("input");
newForm.setAttribute("type", "text");
newForm.setAttribute("id", "form"+i);
inputContainer.appendChild(newForm);
inputContainer.appendChild(document.createElement("br"));
}
}
</script>
<form>
<input type="number" name="nombrePlat" id="nombreP">
<input type="button" value="Envoyer" id="ok" onclick="getP()">
<div id="inutContainer">
</div>
</form>
BUT: this is good question to learn about Javascript and HTML, but bad to create powerfull UI. To implement modern UI in JS/HTML i am strongly recommend to learn more abou next technologies:
https://reactjs.org/ or https://angular.io/ or https://vuejs.org/
I hope it helps:
document.querySelector('#ok').addEventListener('click', getP)
function getP(event) {
let inputsQtt = document.querySelector('input[type=number]').value
for (let i = 0; i < inputsQtt; i++) {
let input = document.createElement("input");
document.body.appendChild(input);
}
}
<form method="get">
<input type="number" name="nombrePlat" id="nombreP">
<input type="button" value="Envoyer" id="ok">
</form>
There are few problems with your code
First: syntax error, you are missing 1 curly bracket } to close function.
And second and more important as you click on button it causes to submit form and refreshes the page.To solve this you just need to change type of button from submit to button.
And also you can not use "input[type=text]" to create element.You can just create an element with following code
function getP () {
var nbP = Number(document.getElementById("nombreP").value);
for (var i = 0; i < nbP; i++) {
var newForm = document.createElement("input");
newForm.id = "form"+i;
newForm.setAttribute("type","text");
document.body.appendChild(newForm);
}
}
Here's a slightly different approach, that involves adding a wrapper container within your form.
function updateForm() {
var parent = document.getElementById('inputs'),
count = document.getElementById('inputCount').value || 0;
parent.innerHTML = '';
for (let i = 0; i < count; i++) {
parent.innerHTML += `<input placeholder="text input ${i+1}" name="form${i+1}" id="form${i+1}" /><br>`;
}
}
<form method="get" name="inputForm">
<input min="0" type="number" name="inputCount" id="inputCount">
<div id="inputs">
<!-- container for dynamic inputs -->
</div>
</form>
<!-- Notice inputs can also be associated to form with `form` attribute -->
<input form="inputForm" type="submit" value="Make" id="ok" onclick="updateForm()">
I have two input, textarea (name + comment) and Submit button. Onclick should post text from input and textarea. I use appendchild(), but need to call textarea.
1. How should I do it?
2. Button "Delete" remove all post, but I need delete just the last one. So how it is possible?
Thank you for any tips.
There is the code:
<script type="text/javascript">
function append(form) {
if (form.input.value) {
var newItem = document.createElement("div");
newItem.appendChild(document.createTextNode(form.input.value));
document.getElementById("myDiv").appendChild(newItem);
}
}
function restore() {
var oneChild;
var mainObj = document.getElementById("myDiv");
while (mainObj.childNodes.length > 0) {
oneChild = mainObj.lastChild;
mainObj.removeChild(oneChild);
}
}
</script>
<form>Name:
<br>
<input type="text" name="input" />
<br />Comment:
<br>
<textarea type="text" name="textarea"></textarea>
<br />
<input type="button" value="Submit" onclick="append(this.form)" />
<input type="button" value="Delete" onclick="restore()" />
</form>
<div id="myDiv"></div>
Problem is because you are saying while there are posts delete last one.
Put just this code in restore. It will remove last child once.
function restore() {
var oneChild;
var mainObj = document.getElementById("myDiv");
oneChild = mainObj.lastChild;
mainObj.removeChild(oneChild);
}
To solve your append issue:
function append(form) {
if (form.input.value) {
var newItem = document.createElement("div");
newItem.appendChild(document.createTextNode(form.input.value));
//add a line break and the text from textarea
newItem.appendChild(document.createElement("br"));
newItem.appendChild(document.createTextNode(form.textarea.value));
document.getElementById("myDiv").appendChild(newItem);
}
}
If you want to delete the last item only, you have to convert the while loop to an if condition:
function restore() {
var oneChild;
var mainObj = document.getElementById("myDiv");
if (mainObj.childNodes.length > 0) {
oneChild = mainObj.lastChild;
mainObj.removeChild(oneChild);
}
}
I want to have a button which when you click on it adds 1 to a number, which is displayed on the screen. This is how far I got.
<button onclick="addOne();">Click Me</button>
<input type="text" id="inc" value="0"></input>
<script>
function addOne()
{
i++;
document.getElementById('inc').value = i;
}
</script>
How can I make it so that the number is saved into a cookie so whenever I come back the number is not changed back into 0?
The variable i has no starting value. You could do the following:
updated, see http://jsfiddle.net/sUHy2/4/
<button onclick="addOne();">Click Me</button>
<input type="text" id="inc" value="0"></input>
<button onclick="resetCookie()">Reset Cookie</button>
<script>
function resetCookie()
{
document.cookie = 0;
writeValue();
}
function addOne()
{
document.cookie++;
writeValue();
}
function writeValue()
{
document.getElementById('inc').value = document.cookie;
}
window.onload = function(){
if(!document.cookie)
{
document.cookie = 0;
}
writeValue();
}
</script>
The crux of this problem is that assigning a variable to an html element is not working within a constructor function.
There must be a way around this right?
The most effective way I have found is to create a method within the constructor function that returns the element.
The problematic variable is "box".
I commented out the section at the start where I tried to make box a global variable, but the constructor couldn't find the box variable. That is the weirdest part to me.
Below is my sample code:
window.onload = function()
{
document.getElementById("sub_button").onclick = adder;
document.getElementById("scrap_it").onclick = remover;
}
//var box = document.getElementById("contact_list");
//refers to the select tag containing contact names as options
var Contacts = function()
{
this.box = function (){ return document.getElementById("contact_list");}
this.list = [];
this.contact_info = document.getElementById("contact_info");
this.find = function(personName){
var found = "missing";
for(var i = 0; i < this.list.length; i++)
{
if(this.list[i].personName == personName)
{
found = i;
}
}
return found;
}
this.addPerson = function(personName, phone)
{
if (this.find(personName) == "missing")
{
personName = personName;
contact =
{
personName: personName,
phone: phone
}
this.list.push(contact);
this.update();
}
else
{
alert("Sorry, this contact name is already in use. Please choose another.");
}
}
this.update = function()
{
this.box().innerHTML = "";
for (var i = 0; i <this.list.length; i++)
{
option_element = document.createElement("OPTION");
option_node = document.createTextNode(this.list[i].personName);
option_element.appendChild(option_node);
this.box().appendChild(option_element);
}
}
this.remove = function(name_to_delete)
{
var index_to_remove = name_to_delete;
this.list.splice(index_to_remove, 1);
this.update();
}
this.postInfo = function(contact_to_display)
{
var index_to_display = contact_to_display;
alert(this.list[index_to_display].personName);
alert(this.list[index_to_display].phone);
}
}
var myList = new Contacts();
function adder()
{
myList.addPerson(document.getElementById("contact_name").value, document.getElementById("contact_phone").value);
}
function remover()
{
myList.remove(myList.box().selectedIndex);
}
function showInfo()
{
myList.postInfo(myList.box().selectedIndex);
}
And the HTML:
<html>
<head>
<title>Address Book</title>
<script type="text/javascript" src="beta3.js"></script>
</head>
<body>
<form id="contact_form">
<label for="contact_name">Name: </label>
<input type="text" id="contact_name" /><br />
<label for="contact_phone">Phone: </label>
<input type="text" id="contact_phone" /><br />
<input type="button" name="submit" value="submit" id="sub_button" />
</form>
<br />
<div>
Delete
</div>
<br />
<div>
<select name="contact_list" id="contact_list" size="10" multiple="multiple" style="width: 450px">
</select>
</div>
<div>
<textarea id="contact_info">
</textarea>
</div>
</body>
</html>
try something like this
var box;
window.onload = function()
{
document.getElementById("sub_button").onclick = adder;
document.getElementById("scrap_it").onclick = remover;
//refers to the select tag containing contact names as options
box = document.getElementById("contact_list");
}
Your code is not working because your script is executed before our element is render in dom so your box variable get nothing.
i'm developing a meta search engine website, Soogle and i've used JS to populate select menu..
Now, after the page is loaded none of engines is loaded by default, user needs to select it on his own or [TAB] to it..
Is there a possibility to preselect one value from the menu via JS after the page loads?
This is the code:
Javascript:
// SEARCH FORM INIT
function addOptions(){
var sel=document.searchForm.whichEngine;
for(var i=0,l=arr.length;i<l;i++){
sel.options[i]=new Option(arr[i][0], i);
}
}
function startSearch(){
var searchString=document.searchForm.searchText.value;
if(searchString.replace(/\s+/g,"").length > 0){
var searchEngine=document.searchForm.whichEngine.selectedIndex,
finalSearchString=arr[searchEngine][1]+searchString;
window.location=finalSearchString;
}
return false;
}
function checkKey(e){
var key = e.which ? e.which : event.keyCode;
if(key === 13){
return startSearch();
}
}
// SEARCH ENGINES INIT
var arr = [
["Web", "http://www.google.com/search?q="],
["Images", "http://images.google.com/images?q="],
["Knowledge","http://en.wikipedia.org/wiki/Special:Search?search="],
["Videos","http://www.youtube.com/results?search_query="],
["Movies", "http://www.imdb.com/find?q="],
["Torrents", "http://thepiratebay.org/search/"]
];
HTML:
<body onload="addOptions();document.forms.searchForm.searchText.focus()">
<div id="wrapper">
<div id="logo"></div>
<form name="searchForm" method="POST" action="javascript:void(0)">
<input name="searchText" type="text" onkeypress="checkKey(event);"/>
<span id="color"></span>
<select tabindex="1" name="whichEngine" selected="Web"></select>
<br />
<input tabindex="2" type="button" onClick="return startSearch()" value="Search"/>
</form>
</div>
</body>
I appreciate that your question asks for a solution that utilises JavaScript, but having looked at the webpage in question I feel confident in making this point:
Your problem is that you are trying to use JavaScript for something that HTML itself was designed to solve:
<select name="whichEngine">
<option value="http://www.google.com/search?q=" selected="selected">Web</option>
<option value="http://images.google.com/images?q=">Images</option>
<option value="http://en.wikipedia.org/wiki/Special:Search?search=">Knowledge</option>
<option value="http://www.youtube.com/results?search_query=">Videos</option>
<option value="http://www.imdb.com/find?q=">Movies</option>
<option value="http://thepiratebay.org/search/">Torrents</option>
</select>
Fear not, though! You can still access all of the options from JavaScript in the same way that you did before.
function alertSelectedEngine() {
var e = document.getElementsByName("whichEngine")[0];
alert("The user has selected: "+e.options[e.selectedIndex].text+" ("+e.options[e.selectedIndex].value+")");
}
Please, forgive and listen to me.
I have modified the code to use jQuery. It is working fine in IE8, IE8 (Compatibility mode) and in FireFox.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Index</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
// SEARCH ENGINES INIT
var arr = new Array();
arr[arr.length] = new Array("Web", "http://www.google.com/search?q=");
arr[arr.length] = new Array("Images", "http://images.google.com/images?q=");
arr[arr.length] = new Array("Knoweledge", "http://en.wikipedia.org/wiki/Special:Search?search=");
arr[arr.length] = new Array("Videos", "http://www.youtube.com/results?search_query=");
arr[arr.length] = new Array("Movies", "http://www.imdb.com/find?q=");
arr[arr.length] = new Array("Torrents", "http://thepiratebay.org/search/");
// SEARCH FORM INIT
function addOptions() {
// Add the options to the select dropdown.
var nOptions = arr.length;
var optionText = '';
for (var i = 0; i < nOptions; i++) {
optionText += '<option value="' + i + '">' + arr[i][0] + '</option>'
}
//alert('optionText = ' + optionText);
// Add the options to the select drop down.
$('select#whichEngine').html(optionText);
// set the second option as default. This can be changed, if required.
$('select#whichEngine option:eq(1)').attr('selected', true);
}
function startSearch() {
var searchEngineIndex = $('select#whichEngine option:selected').attr('value');
searchEngineIndex = parseInt(searchEngineIndex, 10);
var searchString = $('input#searchText').val();
if (searchEngineIndex >= 0 && searchString) {
var searchURL = arr[searchEngineIndex][1] + searchString;
//alert('location = ' + searchURL);
window.location.href = searchURL;
}
return false;
}
function checkKey(e) {
var character = (e.which) ? e.which : event.keyCode;
if (character == '13') {
return startSearch();
}
}
$(function() {
// Add the options to the select drop down.
addOptions();
// Add focus to the search text box.
$('input#searchText').focus();
// Hook the click event handler to the search button.
$('input[type=button]').click(startSearch);
$('input#searchText').keyup(checkKey);
});
</script>
</head>
<body>
<div id="wrapper">
<div id="logo"></div>
<form name="searchForm" method="POST" action="javascript:void(0)">
<input id="searchText" name="searchText" type="text"/>
<span id="color"></span>
<select tabindex="1" id="whichEngine" name="whichEngine"></select>
<br />
<input tabindex="2" type="button"value="Search"/>
</form>
</div>
</body>
</html>
You had some errors in how you handle the <select> values and options. I would reorganize your JavaScript like this:
// SEARCH ENGINES
var arr = [["Web", "http://www.google.com/search?q="],
["Images", "http://images.google.com/images?q="],
["Knowledge", "http://en.wikipedia.org/wiki/Special:Search?search="],
["Videos", "http://www.youtube.com/results?search_query="],
["Movies", "http://www.imdb.com/find?q="],
["Torrents", "http://thepiratebay.org/search/"]];
// SEARCH FORM INIT
function addOptions(){
var sel=document.searchForm.whichEngine;
for(var i=0;i<arr.length;i++) {
sel.options[i]=new Option(arr[i][0],arr[i][1]);
}
}
function startSearch(){
var searchString = document.searchForm.searchText.value;
if(searchString!==''){
var mySel = document.searchForm.whichEngine;
var finalLocation = mySel.options[mySel.selectedIndex].value;
finalLocation += encodeURIComponent(searchString);
location.href = finalLocation;
}
return false;
}
function checkKey(e){
var character=(e.which) ? e.which : event.keyCode;
return (character=='13') ? startSearch() : null;
}
I would also move your onload handler into the main body of your JavaScript:
window.onload = function() {
addOptions();
document.searchForm.searchText.focus();
};
I also made some changes to your HTML:
<body>
<div id="wrapper">
<div id="logo"></div>
<form name="searchForm" method="POST" action="." onsubmit="return false;">
<input name="searchText" type="text" onkeypress="checkKey(event);" />
<span id="color"></span>
<select tabindex="1" name="whichEngine" selected="Web"></select><br />
<input tabindex="2" type="button" value="Search"
onclick="startSearch();" />
</form>
</div>
</body>
You could specify which egine you would like preselected in the engines array like this:
// SEARCH ENGINES INIT
// I've used array literals for brevity
var arr = [
["Web", "http://www.google.com/search?q="],
["Images", "http://images.google.com/images?q="],
["Knoweledge", "http://en.wikipedia.org/wiki/Special:Search?search="],
/*
* notice that this next line has an extra element which is set to true
* this is my default
*/
["Videos", "http://www.youtube.com/results?search_query=", true],
["Movies", "http://www.imdb.com/find?q="],
["Torrents", "http://thepiratebay.org/search/"]
];
Then in your setup function:
// SEARCH FORM INIT
function addOptions() {
var sel = document.searchForm.whichEngine;
for (var i = 0; i < arr.length; i++) {
// notice the extra third argument to the Option constructor
sel.options[i] = new Option( arr[i][0], i, arr[i][2] );
}
}
if your only concern is preselecting an engine onload, don't "over-engineer" it.
var Web = "http://www.google.com/search?q=";
var Images = "http://images.google.com/images?q=";
var Knowledge = "http://en.wikipedia.org/wiki/Special:Search?search=";
var Videos = "http://www.youtube.com/results?search_query=";
var Movies = "http://www.imdb.com/find?q=";
var Torrents = "http://thepiratebay.org/search/";
function addOptions(source){
var sel=document.searchForm.whichEngine;
for(var i=0,l=arr.length;i<l;i++){
sel.options[i]=new Option(arr[i][0], i);
}
}
then insert your argument made onto your body tag to a pre-defined variable. If you want something random, create a new function with your equation for selecting a random variable then load your addOptions(function) within your new function. Then remove addOptions from your body tag.
<body onload="addOptions(Web);document.forms.searchForm.searchText.focus()">