0

I'm using rangeslider.js on a page and want to display the value in a hidden form field to be submitted. The hidden field can only accept a value in a range format, such as 50-205, where 50 is the minimum of the range and 205 is the dynamic number that is selected from moving the slider around.

Currently, it seems that the value is being subtracted from the 50- I have in the code. What do I need to do to make it so that the value is 50-xxx where xxx is the dynamic value?

<input type="range" value="" min="50" max="800" aria-required="true" aria-invalid="false" data-rangeslider name='input_5' id='input_1_5' oninput="document.getElementById('testfield').value = 50-this.value)">

<input type="hidden" id="testfield" name="testfield" value="" />
1
  • well it is subtraction so if you want it to be the string, than use a string and do concatenation. Commented Jul 11, 2019 at 20:25

1 Answer 1

2

You just need some quotation marks, by the looks of it.

Using template strings:

oninput="document.getElementById('testfield').value = `50-${this.value}`"

Using .toString()

oninput="document.getElementById('testfield').value = '50-'+(this.value.toString())"

As pointed out by @Andreas, HTMLInputElement#value will always return a String, so you actually don't need the .toString() call here. If you want to use a Number data type at any point in the future, though, you would need to dive into JavaScript type coercion.

oninput="document.getElementById('testfield').value = '50-'+this.value"

Sign up to request clarification or add additional context in comments.

5 Comments

The .toString() version is unnecessary complicated (this.value is already a string, and even if it wasn't a string, because '50' is also a string it would be automatically converted on concatenation) and doesn't yield the requested output.
As for the incorrect output, whoops-- forgot the hyphen. I've just fixed that. As for it being unnecessarily complicated, yes and no. I get that JS would implicitly take care of this, but because of the simplicity of the question and the likely low experience level the author has, I wanted to spell out the conversion instead of forcing them down the deep, dark hole of type coercion.
The .value property of an HTMLInputElement will always return a string, hence the .toString() call is unnecessary: html.spec.whatwg.org/multipage/input.html#htmlinputelement
Thank you both very much @IronFlare and Andreas, really appreciate the help and the information. That did the trick!
Good catch @Andreas. I've edited my answer to include your information.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.