0

I need to pass two different values back as the result from one checkbox. I tried an object, but the result was undefined (the code works with one value).

 ' <input type="checkbox" id="cat" value="'+{value1: data.blue, value2: data.red} +'"/>'

result.value1 is always undefined, whereas result works for just a string.

What is the best way to do this using javascript/jquery.

0

4 Answers 4

3

You can use attr for add more values, for example:

<input type="checkbox" id="cat" data-value1="blue" data-value2="red" value=""/>

Get values using jQuery, use:

$("#cat").data("value1");//return 'blue'
$("#cat").data("value2");//return 'red'

Result: https://jsfiddle.net/cmedina/a0ya5bwp/

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

Comments

0

Why not create a string with a separator Something like value1 \t value2

And you just have to search for this separator and cut the string to get your 2 differents values?

1 Comment

Thanks, this was my original plan, but I thought I got my test object to work. An object would be the easiest route (if it works).
0

You can stringify the object and put that value on the input as a data attribute, in the input change handler, parse the string to JSON.

HTML

<input type="checkbox" id="cat" name="cat">
<label for="cat">Cat</label>

Javascript

var input = document.getElementById('cat');
var testValue = {value1: 'blue', value2: 'red'};

input.setAttribute('data-value',JSON.stringify(testValue));

input.addEventListener('change', function(event) {
  var inputValue = JSON.parse(event.target.getAttribute('data-value'));
  console.log(inputValue);
});

Demo : JSFiddle

Comments

-1

it looks like you have a spelling mistake : vaule1 should be value1

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.