HTML submit multiple values through one check box?

2020-07-17 15:00发布

Hello I have a form that allows the user to check as many options as they like and then hit submit. Is there any way to have the input type 'checkbox' submit more than one value?

For example right now I have:

<input type="checkbox" value="testuser">

But I want something like:

<input type="checkbox" value="testuser" valuetwo="1">

Is there any way to achieve this second option? Thanks!

Since there is no way to submit to values, is there a way to submit them both in value one? For example:

<input type="checkbox" value="testuser,1">

And if so how would I separate the value into two?

标签: html forms
3条回答
小情绪 Triste *
2楼-- · 2020-07-17 15:42

From your comments, it sounds like you have some JavaScript that handles the data before it's submitted. If that's the case, you can add a data attribute to the checkbox. To use your example, you could call it data-valuetwo.

<input type="checkbox" value="testuser" data-valuetwo="1">

Then, your JavaScript can use getAttribute to retrieve the value in your data-valuetwo attribute and handle it appropriately. It could look something like this:

var valuetwo = checkbox.getAttribute("data-valuetwo");
查看更多
一纸荒年 Trace。
3楼-- · 2020-07-17 16:01

I found a way to do this without JavaScript or Libraries using a hidden form-field instead:

<input name="selectedValue" type="hidden" value="defaultValue">
<input name="selectedValue" type="checkbox" value="secondValue">

Now, if the checkbox is not selected, the hidden value is sent, if it is selected, the hidden value is overridden.

查看更多
够拽才男人
4楼-- · 2020-07-17 16:02

You might try alternative using select2, see: https://select2.github.io/examples.html (Tagging support, use two options limit). Again, there is no enough information supplied to fully satisfy Your question.

Another approach with select box and JSON is Can an Option in a Select tag carry multiple values? (can be rewritten for checkbox)

查看更多
登录 后发表回答