I have a HTML table from which the user will check the row if they want to perform a particular action on that row.
Rather than creating logic which picks out the key data from the row I wish to store the key values in the value attribute of the input checkbox.
My question is, is this legitimate:
<input type="checkbox" value="{'id': 100, 'postcode': 'WA8 6QF'}" />
This way I can use jQuery selectors to pick out the checked boxes and loop through them, performing the action using the items in the value JSON object.
The value attribute on the checkbox is used when the form is interacting with a server. So when you set the value as lettuce, that means when the form is submitted and that box is checked, the value it sends back to the server is topping=lettuce .
Return Value: It returns a string value which represent the value of the value attribute of a input checkbox field.
name. Sets or returns the value of the name attribute of a checkbox. required. Sets or returns whether the checkbox must be checked before submitting a form. type.
You can use HTML5 data-*
attribute:
<input type="checkbox" data-value='{"id": 100, "postcode": "WA8 6QF"}' />
var val = $('input:checkbox').data('value')
Instead of that, you may use .data() of jQuery
:
$(':checkbox').data({'id': 100, 'postcode': 'WA8 6QF'});
markup equivalent is this:
<input type="checkbox" data-id="100" data-postcode="'WA8 6QF'" />
and then retrieve like this:
$(':checkbox').data('id') //100
$(':checkbox').data('postcode') //'WA8 6QF'
the value
of an input:checkbox
element can be any string, so a JSON object is perfectly valid. You will have to be sure to make sure that it's a properly encoded JSON object ("
for quoting strings, not '
) and that it's also correctly HTML-escaped.
The example you provided is invalid JSON:
<input type="checkbox" value="{'id': 100, 'postcode': 'WA8 6QF'}" />
Instead, you should have:
<input type="checkbox" value="{"id":100,"postcode":"WA8 6QF"}" />
It's due to these sorts of encoding issues that most people would discourage this sort of usage. There's nothing wrong with it per-se, but it's very easy to make mistakes that go unnoticed.
That all being said, if you simply want to associate data with an element, jQuery's data
method is much easier to use, and you wont have to worry about encoding.
Additionally, if you're passing information from the server. jQuery's data
method will pull out the information from all the [data-*]
attributes:
<input id="example" type="checkbox" data-id="100" data-postcode="WA8 6QF" value="...some value..." />
<script>//ideally in an external .js file rather than inline
var exampleData = $('#example').data();
</script>
exampleData
will be:
{
id: 100, //will even be nicely cast to a Number
postcode: 'WA8 6QF'
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With