Reputation: 19
So I have select on my page and based on user choice I want to show that amount of input fields to him and then do something with it in php script.
It looks like this:
https://i.sstatic.net/78Qyr.png
And if user chooses 3 then 3 input fields should appear if 2 then 2 etc. without reloading page. What should be used here any js or something?
Upvotes: 0
Views: 631
Reputation: 1480
Here's a snippet, you can run and check it. It also preserves inputs values in case of number of inputs reduce.
var inputNumber = document.getElementById('input-number');
inputNumber.addEventListener('change', changeNumberOfInputs);
function changeNumberOfInputs(event) {
var desiredInputs = parseInt(event.target.value);
var inputsForm = document.getElementById('inputs-form');
var actualInputs = inputsForm.getElementsByTagName('input').length;
if(actualInputs < desiredInputs) {
for(var i=0; i<(desiredInputs - actualInputs); i++) {
inputsForm.appendChild(document.createElement('input'));
}
}
else if(actualInputs > desiredInputs) {
for(var i=0; i<(actualInputs - desiredInputs); i++) {
var lastInput = inputsForm.getElementsByTagName('input');
lastInput = lastInput[lastInput.length - 1];
inputsForm.removeChild(lastInput);
}
}
}
<select id="input-number">
<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>
<form id="inputs-form">
<input />
</form>
Upvotes: 1
Reputation: 41
Assuming you have an already existing form f, you could create the input elements dynamically by looping x times where x is the selected number of inputs required, so something like
for ( var i=0;i<x;i++){
var inputText = document.createElement("input"); //input element, text
inputText.setAttribute('type',"text");
inputText.setAttribute('name',"mark" + i);
f.append(inputText);
}
Upvotes: 1
Reputation: 2615
What you want to do, is to create all 6 of the Input fields. Then hide them all as standard, and do document.getElementById(id).style
to get the style. Then call a function when the Select changes, and use the selected value to uncover the hidden inputs!
As @Arthur Cantarela stated, this is a bad practice in JS. Alternatively, you could put them in a div, and change the div's innerHTML according to how many you need!
Upvotes: 0
Reputation: 21
You could use ng-repeat in angularjs and bind the number select to the repeat expression.
Upvotes: -1