Creating Text Boxes based on the value of a text box - javascript

Basically wht I'm trying to do is have a single textbox on a page. When the user enters a number, it should auto generate X amount of additional text boxes below it.
I've been able to get it to work based off of a dropdown box but a dropdown box will not work for this application.
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script>
<script>
$(document).ready(function(){
$("#ppl").change(function(){
// The easiest way is of course to delete all textboxes before adding new ones
//$("#holder").html("");
var count = $("#holder input").size();
var requested = parseInt($("#ppl").val(),10);
if (requested > count) {
for(i=count; i<requested; i++) {
var $ctrl = $('<input/>').attr({ type: 'text', name:'text', value:'text'});
$("#holder").append($ctrl);
}
}
else if (requested < count) {
var x = requested - 1;
$("#holder input:gt(" + x + ")").remove();
}
});
});
</script>
</head>
<body>
<SELECT id="ppl">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</SELECT>
<div id="holder"></div>
</body>
</html>
Also is there an alternative way to do something like this using ajax rather then jquery?
Demo: Fiddle

I have updated your fiddle again, as your fiddle had everything sitting in the HTML part. jsFiddle.
To give them all unique names, all you need to do is concatenate the index (i) to the end of the name field like this:
for (i = count; i < requested; i++) {
var $ctrl = $('<input/>').attr({
type: 'text',
name: 'text' + i,
value: 'text'
});
$("#holder").append($ctrl);
}
This will give you unique names: ("text1", "text2", .. and so on). I have already changed it for you in the updated fiddle.
I'm agreeing with #Barmar when it comes to your AJAX question, there's no point to do an additional server request unless you need to get data which only the server can provide. It just adds another factor into the equation which might slow things down. If JavaScript can do exactly the same for you but then on the client side instead of on the server side, it is definitely a much faster option.

Here's a similar solution. If you get the desired box count from Ajax then you'll just need to call the 'generateTextBoxes' function.
<html>
<head>
<script type="text/javascript" src="jquery-1.9.js"></script>
<script>
var generateTextBoxes = function( qty, container ) {
if (container) {
for (var i = 1; i <= qty; i++ ) {
$('<label for="box-'+i+'">Box '+i+'</label> <input id="box-'+i+'" name="box-'+i+'" type="text" /><br>').appendTo( container );
}
}
}
var init = function() {
$('#btnGenBoxes').on('click', function() {
generateTextBoxes( $('#box-0').val(), $('#putThemHere') );
});
}
window.onload = init;
</script>
</head>
<body>
<label for="box-0" />How many?</label>
<input type="text" id="box-0" name="box-0" />
<br>
<input type="button" id="btnGenBoxes" value="Generate text boxes" />
<br><br>
<div id="putThemHere"></div>
</body>
</html>

Related

Javascript create input field using a select element

I am trying to create a simple website that calculates a card game score. The website will prompt a user to enter the number of players and return that number of fields for name inputs.
However, as my code stands currently, when a user enters the number of players, the website only shows one field for maybe a second and disappears. I was hoping that someone could help me (a novice programmer) on how to create input text fields dynamically with Javascript. Thanks!
//*****script.js*****
let response = parseInt(document.getElementById("players").value);
const playerNames = () => {
let player;
for (let i = 0; i < response; i++) {
player = document.createElement('input');
player.type = 'text';
document.body.appendChild(player);
};
}
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>
<body>
<form class="start" action="index.html" method="post">
<p>How many players?</p>
<select id="players" class="" name="">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<input type="submit" value="Submit" onclick="playerNames()"/>
</form>
<script src="script.js"></script>
</body>
</html>
You need not wrap your fields in a <form>. If you do this, since your button is type of submit: by default your browser will attempt to submit the form to another page & redirect. You can simply use <div> as a wrapper. Once you do this, you can remove the HTML attributes action & method since these attributes are no longer essential to your code base as you are no longer submitting a form.
As for the script, simply move the gathering of the input inside of the function not outside. So onclick event, that is the time you get the input from the <select>
<body>
<div class="start">
<p>How many players?</p>
<select id="players" class="" name="">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<button onclick="playerNames()">Submit</button>
</div>
<script>
//*****script.js*****
const playerNames = () => {
let response = parseInt(document.getElementById("players").value);
let player;
for (let i = 0; i < response; i++) {
player = document.createElement('input');
player.type = 'text';
document.body.appendChild(player);
};
}
</script>
</body>
When you submit the action takes hold and index.html is loaded. Use event.preventDefault() to stop this load. place response inside the function so each time submit is pressed it captures the value of the select box
//*****script.js*****
const playerNames = () => {
event.preventDefault();
let response = parseInt(document.getElementById("players").value);
let player;
for (let i = 0; i < response; i++) {
player = document.createElement('input');
player.type = 'text';
document.body.appendChild(player);
};
}
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>
<body>
<form class="start" action="index.html" method="post">
<p>How many players?</p>
<select id="players" class="" name="">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<input type="submit" value="Submit" onclick="playerNames()"/>
</form>
<script src="script.js"></script>
</body>
</html>

js html select dropdown value depends on input value

I wanna create select drop down list where selected value will be depends on input value. Example:
If i write 0 in <input type='text' name='answer' id="ans" oninput="myFunction();"> than will be selected dynamically value NO.
<select id="abcd">
<option value="1">OK</option>
<option value="0">NO</option>
</select>
My attempts
function myFunction() {
var x = document.getElementById('ocena7');
if (x == 0)
{
document.getElementById("abcd").selectedIndex = 2;
}}
Greetings
The problem is that with var x = document.getElementById('ans'); you get the DOM element not the value of it.
You need to replace that with: var x = document.getElementById('ans').value;
Just look at this answer: https://stackoverflow.com/a/1085810/826211
And for your code:
You want to use
var x = document.getElementById('ocena7').value;
if you want the value of the element. Now you're just getting a reference to the element with
var x = document.getElementById('ocena7');
This may help
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
var x = document.getElementById('ans').value;
if (x == 0)
{
document.getElementById("abcd").options[1].selected = 'selected'
}
}
</script>
</head>
<body>
<select id="abcd">
<option value="1" >OK</option>
<option value="0" >NO</option>
</select>
<input type='text' name='answer' id="ans" oninput="myFunction();">
</body>
</html>

Textbox value to check multiselect parameter based on values JS

Trying to assign ticks to a checkbox and have options selected if the value matches the values in the textbox. This a multi-select parameter.
E.g. if the textbox contains 1,2 when the page refreshes I want to ensure Cheese and Tomatoes is selected. If the textbox contains 1,5,6 then I want to ensure Cheese, Pepperoni and Onions are selected. If the textbox contains 1,2,3,4,5,6 then I want to ensure all checkboxes are selected.
Trying to write some javascript to do this. I tried to use local storage but can't get it working. See code example: https://www.codeply.com/go/rupzwTzBMY
ASPX:
<input type="text" runat="server" id="txt1" visible="true" value="" />
<div class="container">
<select id="basic" multiple="multiple">
<option value="1">Cheese</option>
<option value="2">Tomatoes</option>
<option value="3">Mozzarella</option>
<option value="4">Mushrooms</option>
<option value="5">Pepperoni</option>
<option value="6">Onions</option>
</select>
</div>
Currently when the page refreshes, even if the textbox has values assigned - the checkboxes clear and nothing is selected.
I am trying to ensure when users select items from the multi-parameter when the page refreshes those values are not gone and still remain on the page.
Javascript functionality that works so far. This puts values in a textbox when you select items from the drop-down. However, when the page refreshes the text box keeps these selected values but the multi-select parameter doesn't:
$('#basic').multiselect({
onChange: function () {
var selectedOptions = $('#basic').val();
document.getElementById("txt1").value = selectedOptions;
},
});
Firstly, you must reload the select once after populating default values as below
$('#basic').multiselect('refresh')
Secondly, try to use onInitialized method as described here
Finally, You're trying to assign back values from TextBox to Dropdown as below, where you're trying to assign the value as such with a comma 1,2 which actually doesn't exist as a value in dropdown.
External Fiddle
$('#basic').children("option[value=" +
document.getElementById("txt1").value + "]").prop("selected", true);
Split the values as 1 and 2 and then assign and it works.
$(document).ready(function () {
document.getElementById("txt1").value = "1,2,3"
$('#basic').multiselect({
includeSelectAllOption: true,
numberDisplayed: 5,
onInitialized: function(select, container) {
console.log("Init");
selectListValues();
}
});
$("#basic").multiselect('refresh');
});
function selectListValues()
{
var txtValue = document.getElementById("txt1").value;
var selectedValues = txtValue.split(",");
for(var i = 0; i < selectedValues.length; i++)
{
var val = selectedValues[i];
if (val == null || val == "") continue;
$('#basic').children("option[value=" + val + "]").prop("selected", "selected");
}
}
<html>
<head>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.15/css/bootstrap-multiselect.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
</head>
<body>
<input type="text" runat="server" id="txt1" visible="true" value="" onchange="selectListValues()" />
<div class="container">
<select id="basic" multiple="multiple">
<option value="1">Cheese</option>
<option value="2">Tomatoes</option>
<option value="3">Mozzarella</option>
<option value="4">Mushrooms</option>
<option value="5">Pepperoni</option>
<option value="6">Onions</option>
</select>
</div>
</body>
</html>
You can get and populate the value using local storage and split the item.
Note
I had to comment out the local storage so the demo code will work as local storage won't work cross domain. You will need to test this locally.
$(function() {
//$("#txt1").val(localStorage.getItem('topping'));
var str = $("#txt1").val().split(",");
$('#basic').val(str);
$('#basic').on('change', function(){
var list = $("#txt1").val($(this).val());
//localStorage.setItem('topping', list);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" runat="server" id="txt1" visible="true" value="1,2,4" />
<select id="basic" multiple="multiple">
<option value="1">Cheese</option>
<option value="2">Tomatoes</option>
<option value="3">Mozzarella</option>
<option value="4">Mushrooms</option>
<option value="5">Pepperoni</option>
<option value="6">Onions</option>
</select>
you can store input value in local storage, then get inputvalue from local storage then iterate on option set and set selected attribute to true of option if value is present in localstorage.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
<input type="text" runat="server" id="txt1" visible="true" value="" />
<div class="container">
<select id="basic" multiple>
<option value="1">Cheese</option>
<option value="2">Tomatoes</option>
<option value="3">Mozzarella</option>
<option value="4">Mushrooms</option>
<option value="5">Pepperoni</option>
<option value="6">Onions</option>
</select>
</div>
<script>
$(document).ready(function () {
$('#basic').multiselect({
onChange: function () {
var selectedOptions = $('#basic').val();
console.log(selectedOptions);
setInputAndLocatStorage();
}
});
function onLoad() {
if(!localStorage.getItem('selectedItems')) return false;
var selItems = localStorage.getItem('selectedItems').split(',');
document.getElementById('txt1').value = selItems.join(',');
$('#basic').multiselect('select',selItems);
}
function setInputAndLocatStorage() {
var selItems = $('#basic').val();
var val = selItems == null ? '': selItems.join(',');
document.getElementById('txt1').value = val;
localStorage.setItem('selectedItems', val);
}
onLoad();
});
</script>

Local Storage With JavaScript

I want to store a string locally so when the user reloads the page it saves what was last there.
I looked at this and tried to implement it.
I had this code which basicllay has a button and a dropdown list of colors to change the background.
When I close and reopen the doc I want it to be the color that I saved.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="">
<label>
<select id="color">
<option value="#FFFFFF">White</option>
<option value="#FF0000">Red</option>
<option value="#FFCC00">Orange</option>
<option value="#FFFF00">Yellow</option>
<option value="#00FF00">Green</option>
<option value="#0000FF">Blue</option>
<option value="#663366">Indigo</option>
<option value="#FF00FF">Violet</option>
</select>
</label>
<input type="button" onClick="inputForm()" value="change color"/>
<form>
<script language="JavaScript">
<!--
function inputForm(){
var color = document.getElementById("color");
var outputContents=color.value;
document.body.style.backgroundColor = outputContents;
}
//-->
</script>
</body>
</html>
I made this code to do that but it didn't work
<!DOCTYPE html>
<html>
<head>
</head>
<body onload="storeColor()">
<form action="">
<label>
<select id="color">
<option value="#FFFFFF">White</option>
<option value="#FF0000">Red</option>
<option value="#FFCC00">Orange</option>
<option value="#FFFF00">Yellow</option>
<option value="#00FF00">Green</option>
<option value="#0000FF">Blue</option>
<option value="#663366">Indigo</option>
<option value="#FF00FF">Violet</option>
</select>
</label>
<input type="button" onClick="inputForm()" value="change color"/>
<input type="button" onClick="storeColor()" value="save color"/>
<script>
var outputContents;
function inputForm(){
var color = document.getElementById("color");
outputContents=color.value;
document.body.style.backgroundColor = outputContents;
}
function storeColor(){
// Store
localStorage.color = outputContents;
// Retrieve
document.body.style.backgroundColor = outputContents;
}
</script>
<form>
</body>
</html>
Local storage in JavaScript is uses (key, value) pairs of strings so if you wanted to save the value This is my test value. you would need to give it a key that you can get it from later, for example myTestValue.
So in code this would be
// set the value in window.localStorage
window.localStorage.setItem('myTestValue', 'This is my test value.')
// get the value from window.localStorage
window.localStorage.getItem('myTestValue')
Here is some more information: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage
You code is almost complete. You only need to apply background color on window load. I added one more function applyColor:
function applyColor(color) {
color = color || localStorage.color;
document.body.style.backgroundColor = color;
// Select corresponding option in selectbox
var select = document.getElementById("color");
for (var i = 0; i < select.options.length; i++) {
if (select.options[i].value == color) {
select.options[i].selected = true;
return;
}
}
}
applyColor();
Also note that when page is loaded we should also select the option from selectbox corresponding to currently saved color.
Demo: http://jsfiddle.net/sd2Cx/

Using jQuery, how can I store the selected values of a select into an array?

Thanks for reading this.
I would have thought it would be as simple as using the .split function on the select .val(), but I get a js error. This is the code I am using. I will use .each() to loop through the selected items...but would like to understand what I am doing wrong...
If I set opts with a literal..the split works (commented code)
Thanks
<html><head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script type="text/JavaScript">
$(function(){
$("#multOpts").bind("click", function() {
// var opts = "OPT1,OPT2,OPT3" ;
var opts = $("#select1").val() ;
$("#text1").val(opts);
});
$("#oneOpt").bind("click", function() {
// var opts = "OPT1,OPT2,OPT3" ;
var opts = $("#select1").val() ;
var optsArray = opts.split(",") ;
$("#text2").val("1st opt: " + optsArray[0]);
});
}); // End eventlistener
</script>
</head><body>
<select id="select1" multiple size="5">
<option value="OPT1">Option 1</option>
<option value="OPT2">Option 2</option>
<option value="OPT3">Option 3</option>
<option value="OPT4">Option 4</option>
<option value="OPT5">Option 5</option>
</select>
<div>
<input id="multOpts" type="button" value="Show Options"/>
<input id="text1" type="text"/>
</div>
<input id="oneOpt" type="button" value="One Option"/>
<input id="text2" type="text"/>
</body></html>
The val() function when there are more than one option selected returns you already an array, you don't need to do the split.
$("#oneOpt").bind("click", function() {
var opts = $("#select1").val();
$("#text2").val("1st opt: " + opts[0]);
});
Since jQuery 1.2, .val() returns array of values is return on multiple select.
var opts = $("#select1").val() || [];
$("#text2").val("values is: " +opts.join(", "));

Categories

Resources