Mikhail Mikhail -3 years ago 100
Javascript Question

Add input number/text to range

I have string with input range

<input form="send" type="range" min="40" max="300" name="width[]" value="40">

it means width of one part.
If user needs some parts he clicks add button and get new string with new input range.
So I get array with different values (size of parts).

Now I need to add input number/text which would repeat range value and vice versa. User can type a number and range input will be changed also. Or he changes input range and input number also get this value.

I know how to do it but without width array.

<input type="range" name="width" min="40" max="200" value="40"
oninput="this.form.widthPlus.value=this.value" /> <input
type="number" name="widthPlus" min="40" max="200" value="40"
oninput="this.form.width.value=this.value" />

Can somebody tell how I can do that to input number reapeat value and also was cloned if user add new string with add button.
I think I can do it with JS/jQuery only.

Answer Source

The easiest way is to just use a new value attribute everytime. Nothing like width[] (which does not work), but instead width0, width1, width2, ..

So somewhere in your code, you have a function which creates a new input element:

var counter = 0;
function addElement() {
    var html = '<input type="range"  name="width' +     counter + '" min="40" max="200" value="40" oninput="this.form.widthPlus' + counter + '.value=this.value" />' +
               '<input type="number" name="widthPlus' + counter + '" min="40" max="200" value="40" oninput="this.form.width'     + counter + '.value=this.value" />'; 

And everytime the user clicks a button, you can call this function to add a new element.

There are also alternative ways that do not require the name-attribute to count upwards. You could just call a JS-function if the user enters something, and then use jQuery to determine which element was edited (n'th child). But this is a bit more complicated and requires more code.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download