如果搜索为空,使用jQuery传递静态值

3

我正在使用$('input[type="text"]').val()传递搜索字符串。

现在的要求是:
如果是一个空的搜索,则我想将空搜索作为值传递,而不是$('input[type="text"]').val()

同时,

如果不为空且有一个值,则我想使用$('input[type="text"]').val()传递相同的值。

我所尝试的:

$(document).on('click','.fa.fa-search', function()
{
    ga('create', {{ GA Property }}, 'auto'); 
    ga('send', 'event', 'Search', 
    function blank () 
    { 
      alert('hi');
        var srchStr = $('input[type="text"]').val(); 
        if(srchStr == '') { srchStr = "Blank Search"; }
    }, 
    window.location.href); 
}); 

如何做呢?

你可以使用三元运算符 ($('input[type="text"]').val().trim().length > 0) ? $('input[type="text"]').val() : "Blank Search" - Beginner
5个回答

0

试试这个:

var srchStr = $('input[type="text"]').val();
if(srchStr == '')
{
    srchStr = "Blank Search";
}

0
请参见以下示例,以避免额外的空格。
var v = $('input[type="text"]').val().replace(/\s+/,"");
v = v === "" ? "Blank Search" : $('input[type="text"]').val();

<script> $(document).on('click','.fa.fa-search', function(){ ga('create', {{GA Property}}, 'auto'); ga('send', 'event', '搜索', function blank () { var srchStr = $('input[type="text"]').val(); if(srchStr == '') { srchStr = "空白搜索"; }}, window.location.href); }) </script> 这是我的原始代码。如果搜索为空,则我希望该值为“空白搜索”,如果不为空,则我希望搜索值/字符串。 - kishoremcp

0

工作的Fiddle

HTML:

<input type="text" />
<input type="button" val="test">

jQuery:

$('input[type="button"]').on("click", function() {
  var val = $('input[type="text"]').val().trim().length > 0 ? $('input[type="text"]').val() : "Your Default value"
  alert(val);
});

0

最简单的方法:

if($('input[type="text"]').val() == '')
{
    $('input[type="text"]').val("Blank Search");
}

0
尝试这样做: var input = $('input[type="text"]'); var srchStr = input.val();
if(srchStr != '' && srchStr.trim().length > 0){
  input.val(srchStr);
}else{
  input.val("Blank Search");
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接