如何使用 jQuery 清空输入值

How do I empty an input value with jQuery?

本文关键字:输入 清空 jQuery 何使用      更新时间:2023-09-26

我正在尝试与图像进行模态对话框,您可以在其中选择多个图像。我需要从输入中获取值,然后清空它,但我无法清空输入。我尝试了.val('').val(null),但都不适合我。

以下是完整的代码:

$("#hdselect").click(function(){
        $(".modal").html("");
        $.post('mediaservice.php',{hd:'ok',images:$("#hdimages").val()},function(data){
            $(".modal").append(data);
        });
        $(".modal").dialog({
            'modal':true,
            'title':"Click the image to select",
            'width':960,
            'height':600,
            'resizable':false,
            'show': {effect: 'drop', direction: "up"},
            'buttons': {"Ok": function() {  
                    var hd=Array();
                    var hdval=$("#hdimages").val();
                    $("#hdimages").attr('value',' ');
                    $("input[name='hd[]']:checked").each(function(){
                        hd.push($(this).val());
                    });
                    if(hdval!=''){
                        hdval=hdval+","+hd;
                    }else{
                        hdval=hd;
                    }                        
                    $("#hdimages").val(hdval);
                    var images=$("#hdimages").val();
                    $.post('mediaservice.php',{getHd:images},function(data){
                        $("#imgthumbBase").append(data);
                    });
                    $(this).dialog("close");
                }
            }
        });
    });

这个想法是用户单击一个按钮,然后打开一个包含多个图像和复选框的模式对话框。此时,我需要从输入中获取值,然后清除它。

要将值设为空,您可以执行以下操作:

 $("#element").val('');

要获取所选值,您可以执行以下操作:

var value = $("#element").val();

其中#element是要选择的元素的 id。

你可以试试:

$('input.class').removeAttr('value');
$('#inputID').removeAttr('value');

更好的方法是:

$("#element").val(null);

使用 jquery 清空文本框的常用方法是:

$('#txtInput').val('');

如果上面的代码不起作用,请检查您是否能够获取输入元素。

console.log($('#txtInput')); // should return element in the console.

如果仍然面临同样的问题,请发布您的代码。

另一种方法是:

$('#element').attr('value', '');
$('.reset').on('click',function(){
           $('#upload input, #upload select').each(
                function(index){  
                    var input = $(this);
                    if(input.attr('type')=='text'){
                        document.getElementById(input.attr('id')).value = null;
                    }else if(input.attr('type')=='checkbox'){
                        document.getElementById(input.attr('id')).checked = false;
                    }else if(input.attr('type')=='radio'){
                        document.getElementById(input.attr('id')).checked = false;
                    }else{
                        document.getElementById(input.attr('id')).value = '';
                        //alert('Type: ' + input.attr('type') + ' -Name: ' + input.attr('name') + ' -Value: ' + input.val());
                    }
                }
            );
        });

对我来说,这是解决这个问题的最好方法:

$('yourElementName').val(null);