[英]How do I empty an input value with jQuery?
我正在嘗試使用圖像制作一個模態對話框,您可以在其中選擇多個圖像。 我需要從輸入中獲取值然后清空它,但我無法清空輸入。 我試過.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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.