Aaron Aaron - 27 days ago 15
Javascript Question

Use onclick with <li> to add to form POST data

I have a typical html form which I use to post data to a database. In this form I want to include clickable javascript li elements with boolean values, like a radio button. But how do I post this with the form when it is submitted? I'm guessing I have to call a function with onclick that checks or unchecks a hidden form element. How do I do this?

<h3 class="text-left">Questions</h3>
<div class="input-group" style="max-height: 300px;overflow: inherit;">
<ul class="list-group checked-list-box">

<li class="list-group-item">Question 1
<input type="hidden" name="question_1_input"></li>

</ul>

</div>

<script>


$(function () {
$('.list-group.checked-list-box .list-group-item').each(function () {

// Settings
var $widget = $(this),
$checkbox = $('<input type="checkbox" class="hidden" />'),
color = ($widget.data('color') ? $widget.data('color') : "primary"),
style = ($widget.data('style') == "button" ? "btn-" : "list-group-item-"),
settings = {
on: {
icon: 'glyphicon glyphicon-check'
},
off: {
icon: 'glyphicon glyphicon-unchecked'
}
};

var checkedValues = $("li input[type=checkbox]:checked").map(function () {
return $(this).val();
});
console.log(checkedValues.get());
$widget.css('cursor', 'pointer');
$widget.append($checkbox);

// Event Handlers
$widget.on('click', function () {
$checkbox.prop('checked', !$checkbox.is(':checked'));
$checkbox.triggerHandler('change');
updateDisplay();
});
$checkbox.on('change', function () {
updateDisplay();
});


// Actions
function updateDisplay() {
var isChecked = $checkbox.is(':checked');

// Set the button's state
$widget.data('state', (isChecked) ? "on" : "off");

// Set the button's icon
$widget.find('.state-icon')
.removeClass()
.addClass('state-icon ' + settings[$widget.data('state')].icon);

// Update the button's color
if (isChecked) {
$widget.addClass(style + color + ' active');
} else {
$widget.removeClass(style + color + ' active');
}
}

// Initialization
function init() {

if ($widget.data('checked') == true) {
$checkbox.prop('checked', !$checkbox.is(':checked'));
}

updateDisplay();

// Inject the icon if applicable
if ($widget.find('.state-icon').length == 0) {
$widget.prepend('<span class="state-icon ' + settings[$widget.data('state')].icon + '"></span>');
}
}
init();
});

$('#get-checkget-checked-data').on('click', function(event) {
event.preventDefault();
var checkedItems = {}, counter = 0;
$("#check-list-box li.active").each(function(idx, li) {
checkedItems[counter] = $(li).text();
counter++;
});
$('#display-json').html(JSON.stringify(checkedItems, null, '\t'));
});


});

Answer

I created code which set hidden element in form to data-value attribute of selected li element:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <style media="screen">
        .active {
            background-color: #EDEDED;
        }
    </style>
</head>
<body>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>


    <ul>
        <li class="liElement" data-value="first">First</li>
        <li class="liElement" data-value="second">Second</li>
        <li class="liElement" data-value="third">Third</li>
        <li class="liElement" data-value="fourth">Fourth</li>
    </ul>
    <form action="index.html" method="get">
        <input type="hidden" id="formControl" name="control" value="">
        <button>Submit</button>
    </form>



    <script type="text/javascript">
        $(document).ready(function(){
            var liArr = [];
            var formControl = $("#formControl");

            $(".liElement").click(function(){
                $(this).toggleClass("active");

                var current = $(this).data("value");
                var index = liArr.indexOf(current);
                if (index != -1) {
                    liArr.splice(index, 1);
                } else {
                    liArr.push(current);
                }

                formControl.val(liArr.join('-'));
            });
        });
    </script>

</body>
</html>