Create inputs N times in JavaScript - javascript

I am working on a form that initially asks for an amount of people:
<select name="amount" onClick="update()" id="amount">
<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>
</select>
This then triggers the update function when any option is clicked which toggles the visibility of the next part of the form which is contained in a div called step2:
function update(){
document.getElementById('step2').style.visibility='visible';
};
What I then want to do is create N inputs (N being how many people they selected)
So if they select 4 then 4 name inputs appear.
I have tried using this function:
function addinput(){
var wrapper = $("#step2"); //Fields wrapper
var x = document.getElementById(amount).value;
for(var i = 0; i < x; i++) {
$(wrapper).append('<div><input type="name" name="mytext[' + i + ']"/></div>');
}
};
And then placing addinput() at the end of the update function.
However this does not work.
Is there any other way that will, or even, what am I doing wrong in my code?

Related

Show Div based on multiple drop down selections

<select name="main">
<option value="1">1</option>
<option value="1">2</option>
<option value="1">3</option>
<option value="1">4</option>
<option value="1">5</option>
</select>
<select name="sub">
<option value="1">1</option>
<option value="1">2</option>
<option value="1">3</option>
</select>
I have 2 seperate drop downs as seen here. I want to make it so that if they select main it will show a div for main with a text box equal to they number they select(ie. 4 will show 4 main textboxes for them to fill out) which I know how to do. The problem comes with sub I want them to show a text box equal to the sub for each main select(ie if main is 3 and sub is 3 then each of the 3 main text box will be followed by 3 sub text boxes) I can make it show 3 or all but I can not figure out how to make it go based of the selection of both main and sub to ive me the exact fields I am looking for. Do I just need to set in the function for the java script that if main == x then show xyz on the function for sub?
You can use onchange in the sub select:
<select name="sub" onchange="createSubInput(this)">
function createSubInput (selected) {
let mainSelectedValue = document.getElementById('main').value;
for(let i=0; i< mainSelectedValue; i++) {
for(let j=0; j< selected.value; j++) {
// todo: create sub input by each main input
}
}
}
In order to accomplish this you'll have to:
Use the change event on each select
Take advantage of the value attribute on each option
Demo:
const mainSelect = document.querySelector('select[name="main"]');
const subSelect = document.querySelector('select[name="sub"]');
const resultsDiv = document.getElementById("results");
mainSelect.addEventListener("change", event => {
handleChange(event);
});
subSelect.addEventListener("change", event => {
handleChange(event);
});
function handleChange(event) {
let textboxes = "";
let mainCount = Number(mainSelect.value);
let subCount = Number(subSelect.value);
for (let i = 0; i < mainCount; i++) {
let t = "<input type='text' placeholder='main' /><br/>";
for (let s = 0; s < subCount; s++) {
t += "<input placeholder='sub' style='margin-left: 10px;' /><br/>"
}
textboxes += t;
}
resultsDiv.innerHTML = `<h4>Please fill these out</h4>${textboxes}`;
}
<select name="main">
<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>
</select>
<br />
<select name="sub">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<div id="results"></div>

Filter two select fields based upon two options and total availability

I have two select options for adults and children in my form:
<select name="BKG_Adult">
<option value="1" data-price="1000">1</option>
<option value="2" data-price="2000">2</option>
<option value="3" data-price="3000">3</option>
<option value="4" data-price="4000">4</option>
</select>
<select name="BKG_Child">
<option value="0" data-price="0">0</option>
<option value="1" data-price="500">1</option>
<option value="2" data-price="1000">2</option>
<option value="3" data-price="1500">3</option>
</select>
<input type="hidden" id="dynamic_availability" name="dynamic_availability" value="4">
The hidden field dynamic availability is populated by an external web service on page load to give the total amount of seats available on a tour. The options are also populated on page load.
The main rule of the form is that at least one adult must travel on the tour. The remaining seats can then be made up of a combination of children and adults.
If 2 adults are selected, I need to reduce the amount of options in the child select to ensure that the user cannot select over 4 people in total. Equally, if 2 children are selected in the child select I must restrict the values in the adult select but still ensure that at least one adult is selected.
Essentially this will use the onchange event of the child and adult select fields but the complexity is filtering the options based upon the rules defined above. Of course, if the user were to reduce the number of options selected in one field, the number of options should increase in the other field so that the user can still select a maximum of 4.
Does anyone know of an example of such functionality or how this can be implemented in vanilla javascript or jquery?
$(function() {
var max = $("#dynamic_availability").val(),
$adult = $("#adult"),
$child = $("#child");
fillCmb($adult, 1, max);
fillCmb($child, 0, max - 1);
$adult.on("change", function() {
var cant = $(this).val();
fillCmb($child, 0, max - cant);
});
$child.on("change", function() {
var cant = $(this).val();
fillCmb($adult, 1, max - cant);
});
function fillCmb($cmb, min, max) {
var val = $cmb.val();
$cmb.empty();
for (var i = min; i <= max; i++)
$cmb.append("<option value=\"" + i + "\">" + i + "</option>");
if (val)
$cmb.val(val);
}
});
http://jsfiddle.net/paska/9ac1ta7u/2/
function changeSelect(element, otherSelectValue){
var options = element.find(option);
for(x=0; options.length; x++){
if((options[x].value() + value) > 4){
options[x].remove();
}
}
}
$('#adult', '#child').on('change', function(){
if(this.attr('id') === 'adult'){
changeSelect($('#child'), this.val());
}else{
changeSelect($('#adult'), this.val());
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="adult" name="BKG_Adult">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select id="child" name="BKG_Child">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>

Setting value to a form field with JavaScript

I have a web form with several fields. Three of them are ano_evento, mes_evento and dia_evento (year, month and day). I want to get the values from these fields, convert it to a date format and show the formatted date in another field called fecha_evento. The user sets a value for ano_evento (e.g. 2014), a value for mes_evento (e.g. 11) and a value for dia_evento (e.g. 25). The value for fecha_evento should then be 2014-11-25.
All three fields have an onchange method in it:
For ano_evento:
<select name="ano_evento" id ="ano_evento" onchange="cambiar_fecha()">
For mes_evento:
<select name="mes_evento" id ="mes_evento" onchange="cambiar_fecha()">
For dia_evento:
<select name="dia_evento" id="dia_evento" onchange ="cambiar_fecha()">
The field for fecha_evento:
<input type="text" name="fecha_evento" id="fecha_evento" value="0" size="32" />
And this is the script:
<script>
function cambiar_fecha(){
alert (document.getElementById("fecha_evento").value);
var ano = document.getElementById("ano_evento").value;
var mes = document.getElementById("mes_evento").value; //
var dia = document.getElementById("dia_evento").value;
document.getElementById("fecha_evento").value = ano+"-"+mes+"-"+dia;
}
</script>
When the user changes any of the three fields values, the alert inside the script is shown, but the value from the field fecha_evento doesn't change.
Any help is welcome
how are you?
Try this code:
<select name="ano_evento" id="ano_evento">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="mes_evento" id="mes_evento">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="dia_evento" id="dia_evento">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="text" name="fecha_evento" id="fecha_evento">
<script>
var ano = document.getElementById("ano_evento");
var mes = document.getElementById("mes_evento");
var dia = document.getElementById("dia_evento");
var fecha = document.getElementById("fecha_evento");
function cambiar_fecha() {
alert(fecha.value);
fecha.value = ano.value + "-" + mes.value + "-" + dia.value;
alert(fecha.value);
}
ano.onchange = cambiar_fecha;
mes.onchange = cambiar_fecha;
dia.onchange = cambiar_fecha;
</script>
Recommendations:
- Save the elements in variables to optimize execution avoiding constantly DOM access.
- Set events handler from JS.
- Use browser console to see if there are JS errors.
Regards.
Instead of the inline javascript, I would just go with a querySelectorAll
DEMO
HTML:
<select name="ano_evento" id ="ano_evento" >
<option value="1">1</option>
<option value="2">2</option>
</select>
<select name="mes_evento" id ="mes_evento" >
<option value="1">1</option>
<option value="2">2</option>
</select>
<select name="dia_evento" id="dia_evento" >
<option value="1">1</option>
<option value="2">2</option>
</select>
<input type="text" name="fecha_evento" id="fecha_evento" value="0" size="32" />
Javascript:
var a = document.querySelectorAll('select');
console.log(a);
for(var i = 0; i<a.length;i++) {
a[i].addEventListener('change',cambiar_fecha);
}
function cambiar_fecha(){
alert (document.getElementById("fecha_evento").value);
var ano = document.getElementById("ano_evento").value;
var mes = document.getElementById("mes_evento").value; //
var dia = document.getElementById("dia_evento").value;
document.getElementById("fecha_evento").value = ano+"-"+mes+"-"+dia;
}

querySelectAll Not Selecting Proper Elements

I have a dropdown menu with a really long ID, but part of it is _Country. I have a text box with a really long ID, but part of it is _State.
I'm trying to take the value from the dropdown Country and put it into the textbox State anytime someone selects an option in the Country dropdown.
Here is the JavaScript I have now. It worked fine before I tried using the wildcard, but now it does not work.
<script type="text/javascript">
document.querySelectorAll('[id*="_Country"]').onchange = replicate;
function replicate() {
var tb1 = document.querySelectorAll('[id*="_Country"]');
var tb2 = document.querySelectorAll('[id*="_State"]');
tb2.value = tb1.value;
}
</script>
querySelectorAll() returns a NodeList. Use querySelector() to get just one node.
Here's a sample (fiddle):
<select id="test_Country">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select id="test_State">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<script>
(function() {
var country = document.querySelector('[id*="_Country"]');
var state = document.querySelector('[id*="_State"]');
country.addEventListener("change", function(e) {
state.value = country.value;
});
})();
</script>

Multiple identical <select> tags where each option can be selected once

I am creating a website where their are 4 identical dropdown menu's, each dropdown menu has got 10 options. But each of those options can only be selected in one of the dropdown menu's.
So for example:
When I select option 1 in this dropdown menu.
<select name="select1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">2</option>
<option value="4">4</option>
</select>
I can't select it in this one. So it should say disabled in option one.
<select name="select2">
<option value="1" //disabled >1</option>
<option value="2">2</option>
<option value="3">2</option>
<option value="4">4</option>
</select>
I don't know how to do it myself so I would be very glad if someone could help me.
To provide a better user experience, you should disable the items using JavaScript when the user selects something in a drop down. Are you using jQuery by any chance?
You should also enforce it on the server because as a general rule, clients are not to be trusted.
If I understand you correctly, what you are trying to achieve is better done via checkboxes.
Instead of <select> do this:
<input type="checkbox" name="1" value="1">option1<br>
<input type="checkbox" name="2" value="2">option2 <br> ...
The code below does what you are asking. I also made a jsfiddle
It will correctly disable and enable options as options from ANY of the select inputs are changed.
The javascript
<script type="text/javascript">
// *** EDIT THIS ***
var selectIds = new Array('select1', 'select2', 'select3', 'select4'); // all of the select input id values to apply the only one option value anywhere rule against
function process_selection(theObj){
var allSelectedValues = new Array(); // used to store all currently selected values
// == get all of the currently selected values for all the select inputs
for (var x=0; x<selectIds.length; x++){
var v = document.getElementById(selectIds[x]).value; // the value of the selected option for the select input currently being looked at in the loop (selectIds[x])
// if the selected option value is not an empty string ..
if(v!==""){
// store the value of the selected option and it's associated select input id value
allSelectedValues[v] = selectIds[x];
}
}
// == now work on each option within each select input
for (var x=0; x<selectIds.length; x++){
// loop thru all the options of this select input
var optionObj = document.getElementById(selectIds[x]).getElementsByTagName("option");
for (var i = 0; i < optionObj.length; i++) {
var v = optionObj[i].value; // the value of the current option in the iteration
// only worry about option values that are not an empty string ("")
if(v!==""){
if(allSelectedValues[v]){
if(allSelectedValues[v] && allSelectedValues[v] != selectIds[x]){
// disable this option because it is already selected
// and this select input is NOT the one that it is selected in
optionObj[i].disabled = true;
}
}else{
// enable this option because it is not already selected
// in any of the other select inputs
optionObj[i].disabled = false;
}
}
} // end for (option loop)
} // end for (select loop)
} // end func
</script>
The HTML that works with the above
But really the code above will work with any select inputs on your page by editing the one line indicated in the js code above
<select name="select1" id="select1" onchange="process_selection(this)">
<option value="">-- choose one --</option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select name="select2" id="select2" onchange="process_selection(this)">
<option value="">-- choose one --</option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select name="select3" id="select3" onchange="process_selection(this)">
<option value="">-- choose one --</option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select name="select4" id="select4" onchange="process_selection(this)">
<option value="">-- choose one --</option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
As others have mentioned, it is a cleaner way to do it in checkboxes. However, just to improve my JavaScript skills, I came up with something that should answer what you asked for:
var boxes, i, disableOthers;
boxes = document.getElementsByTagName('select');
disableOthers = function () {
'use strict';
var i, j, k, selectedValues = [],
options;
for (i = 0; i < boxes.length; i += 1) {
selectedValues.push(boxes[i].value);
for (j = 0; j < boxes.length; j += 1) {
if (boxes[j] !== boxes[i]) {
options = boxes[j].querySelectorAll('option');
for (k = 0; k < options.length; k += 1) {
options[k].disabled = (selectedValues.indexOf(options[k].value) > -1);
}
}
}
}
};
for (i = 0; i < boxes.length; i += 1) {
boxes[i].addEventListener('change', disableOthers, false);
}
See jsFiddle

Categories

Resources