-1

I have a form that looks something like this:

<form name="theForm">

    <input name="Name" type="text" placeholder="Name" />

    <select name="Options">
        <option value=1>Option 1</option>
        <option value=2>Option 2</option>
        <option value=3>Other</option>
    </select>

    <button type="submit">Submit</button>

</form>

Behind the scenes, I have some javascript which, if the user is to select the third option (other), a text input is created where the user can type an input that does not appear in the list.

I've looked into posts like this and this, where the accepted answer changes the value of an existing input in the form before submission, but these do not suit my situation as I cannot simply change the value of the <select> to a string.

So, I would like to ask if it is possible to alter the form data upon submission, so that if the third option is selected, the form submits the contents of the custom text box rather than the value 3.

Thank you.

Caspar B
  • 499
  • 1
  • 6
  • 19

2 Answers2

1

I think it could be easier to insert your input text in the form and hide it (CSS, or JavaScript). The user won't be able to see it and so your form is gonna send an empty string is the option 1 or 2 are selected. When the user select the third option, you just show the text input with some JavaScript, allowing the user to complete his answer. Your form will send the option 3 and also the input text, which will be filled by the user in this case.

<form name="theForm">

    <input name="Name" type="text" placeholder="Name" />

    <select name="Options">
        <option value=1>Option 1</option>
        <option value=2>Option 2</option>
        <option value=3>Other</option>
    </select>
    <input name="other" type="text" placeholder="My option 3 is..." hidden/>

    <button type="submit">Submit</button>

</form>
BNilsou
  • 886
  • 8
  • 22
  • 1
    I see what you mean. I thought of this, but I'd ultimately like the form to submit one value for simplicity purposes. Not a value for the select dropdown and a value for the input box, because I'm only going to need the info from one or the other. Thank you for your answer. Not sure why the downvote. – Caspar B Apr 17 '18 at 08:07
0

If you can restrict usage of your solution to HTML5 compliant browsers and exclude Safari for the moment, you can use datalist: https://www.w3schools.com/tags/tag_datalist.asp

It will simplify your HTML code and avoid any need of javascript custom code.

Yannick Vincent
  • 441
  • 2
  • 5
  • 15