如何在单击一个按钮时存储多个值?

时间:2013-11-13 14:47:39

标签: javascript jquery

我试图获得一个按钮来存储按钮值(id answer0,'value2')以及一个下拉框选择(id answer1,'value'。因为代码没有保存,尽管我已经设法在之前的尝试中保存按钮'value2'。谷歌搜索3天无济于事。任何建议将不胜感激!

    $('.btn-answer').off('click').on('click', function(evt) {
        var answer0 = $(evt.target).attr("value2");
      //var answer1 = $("#answer1").val();
        var answer1 =$('#answer1 option:selected').text();
        var all_answers = {};
            all_answers['answer0'] = answer0;
            all_answers['answer1'] = answer1;
      if (typeof all_answers != 'undefined') {
        console.log(answer0);
        console.log(answer1);
        pybossa.saveTask(task.id, all_answers).done(function() {
                deferred.resolve();






<div>
            <select name="answer1" class = "btn-success btn-mini">
                <option value="none">Choose a Class</option>
                <option>Woodland and Scrub</option>
                        <option value="A1">Woodland</option>

                        ......
                        <option value="J5">Other Habitat</option>
                        </select>
                </div>




    <h1 id="question2"></h1> <!-- The question will be loaded here -->
    <h2><i class="icon-asterisk"></i> </h2>       
    <div id="answer0">             <!-- Start DIV for the submission buttons -->
        <!-- If the user clicks this button, the saved answer will be value2="Certai-->
        <button class="btn btn-success btn-answer" value2 ="a"><i class="icon icon-white icon-thumbs-up"></i> Certain</button>
        <!-- If the user clicks this button, the saved answer will be value2="Fairly Certain"-->
        <button class="btn btn-answer btn-warning" value2="b"><i class=""></i> Fairly Certain</button>
        <!-- If the user clicks this button, the saved answer will be value2="Fairly Certain"-->
        <button class="btn btn-answer btn-danger" value2="c"><i class="icon icon-white icon-thumbs-down"></i> Unsure</button>
    </div>
    <P></P>
    <!-- End of DIV for the submission buttons -->

1 个答案:

答案 0 :(得分:2)

更改此行:

var selected_answer1 = $("#answer1").val();

我猜$("#answer1")input,而$("#answer1").val("value")则试图设置其值。但是你想要获得它的价值。

从下拉列表中获取价值:

$('#id_of_drop_down').val();将返回值,而不是文本。

如果您需要选定option的文字,请使用此项:

$('#id_of_drop_down option:selected').text();