【问题标题】:Clean all selected option after ajax requestajax请求后清除所有选定的选项
【发布时间】:2016-09-18 02:26:09
【问题描述】:

通过单击更新链接,根据从 Ajax 请求检索到数据库的数据从下拉列表中选择值,当我在 console.log 响应时,我可以看到数据已被检索,并且我能够成功地将其与 drop 进行比较-down 列表,如果匹配,将选择其中一个选项值。

如果我点击清除按钮来清除选定的选项,它是第一次工作。

但是,如果我再次单击更新链接以检索数据,我可以看到数据已被检索,当我控制台记录响应时,但没有从下拉列表中选择任何内容。

任何帮助 - 下面是我的代码

<p>
    <a href="javascript:;" class="updateCenter">Update</a>
</p>

<form method="post" action="controller/update" class="formInuts">
    <select required="" name="semester_id" class="form-control semester">
        <option value="">Pleas Select</option>
        <option value="1">Semester 1</option>
        <option value="2">Semester 2</option>
        <option value="3">Semester 3</option>
    </select>
    <button type="submit" class="btn btn-primary saveCorCnt">SAve</button>
    <button type="" class="btn btn-primary clearCorCnt">Clean</button>
</form>


// Update 
$('.updateCenter').on('click', function(event) {
    event.preventDefault();

    // semester id
    var corcnt_id = 1;

    $.ajax({
        url: url+'/findcorcnt',
        type: 'POST',
        dataType: 'JSON',
        data: {
            corcntid: corcnt_id
        },
        beforeSend: function() {
        },
        success: function(respond) {
            // Data retrieved successfully 
            // first time and every time i click on update link
            // Changing the current action to update
            var formInuts = $('.formInuts').attr('action',url+'/updatecorcnt');

            // Change save btn to update
            var saveBtn   = $('.saveCorCnt').text('update');

            // Selecting the values from dropdowns semesters
            $('.semester option').each(function(){
                if (parseInt(this.value) == respond.semester_id) {
                    $(this).attr('selected', true);
                }
            });
        });


$('.clearCorCnt').on('click', function(event) {
    event.preventDefault();

    $(':input','.formInuts')
        .removeAttr('checked')
        .removeAttr('selected')
        .not(':button, :submit, :reset, :hidden, :radio, :checkbox')
        .val('');

    var saveBtn   = $('.saveCorCnt').text('save');
});

【问题讨论】:

  • 附带说明,在使用checkedselected 等时,您希望使用属性而不是属性,即使用.prop()跨度>

标签: jquery


【解决方案1】:

无需使用循环进行比较。只需尝试如下。

$('.semester').val(respond.semester_id);

【讨论】:

  • 我认为我应该循环并比较这些值。 :) 我会试试这个
猜你喜欢
  • 2023-03-14
  • 1970-01-01
  • 2019-03-31
  • 2017-12-09
  • 2021-08-30
  • 1970-01-01
  • 1970-01-01
  • 2015-09-09
  • 1970-01-01
相关资源
最近更新 更多