在jquery中选择单选按钮

时间:2015-03-13 11:34:49

标签: jquery

我有一些HTML文档:

<ul class="ShippingProviderList">
<li>
<label id="shippingMethod">
    <div id="uniform-shippingCheck" class="radio">
     <span>
     <input type="radio" value="0">
     </span>
    </div>
    <span class="ShipperName">Shipping One</span>
    </label>
</li>

<li>
<label id="shippingMethod">
    <div id="uniform-shippingCheck" class="radio">
<span>
     <input id="shippingCheck" type="radio" value="2" name="selectedShippingMethod">
</span>
</div>
     <span class="ShipperName">Shipping Two</span>
</label>
</li>

<li>
<label id="shippingMethod">
<div id="uniform-shippingCheck" class="radio">
<span>
      <input id="shippingCheck" type="radio" value="1" name="selectedShippingMethod">
</span>
</div>
<span class="ShipperName">Shipping Three</span>

</label>
</li>

我想尝试检查本文档中是否包含字符串“Shipping One”。 如果包含“Shipping One”,我想自动选中单选按钮(此处为值“0”)。 但是这个值会动态变化(“0”或“1”或“2”等等)。如果值改变了我的代码将是错误的。 当值改变时,如何实现自动选择?

我的javascript代码:

    $(document).ready(function() {
var smethods = [];
    $('.ShippingProviderList .ShipperName').each(function() {
        var txt = $(this).html();
            smethods.push(txt);
    }); // end each

if($.inArray('Shipping One', smethods)==0){        
   $("input[type=radio][value='0']").prop("checked",true);
}else{
 $('.ShippingProviderList').prepend('<li><input type="radio" value="0"></li>');
}

});

2 个答案:

答案 0 :(得分:0)

您需要检查-1

if($.inArray('Shipping One', smethods) === -1){        
    $("input[type=radio][value='0']").prop("checked",true);
}else{
    $('.ShippingProviderList').prepend('<li><input type="radio" value="0"></li>');
}

如果'Shipping One'在数组'smethods'中,那么它将返回它的索引,无论它在任何索引上是否可用,但如果它不在其中,那么它将返回-1

下面是一个简短的例子:

如果在数组中找到任何内容,则$.inArray()将返回找到的对象的索引,否则它将返回-1

&#13;
&#13;
   var smethods = ['Shipping One', 'Shipping Two'];
   alert("Is 'Shipping One' in the array : " + $.inArray('Shipping One', smethods))
   alert("Is 'Shipping Two' in the array : " + $.inArray('Shipping Two', smethods))
   alert("Is 'Shipping Three' in the array : " + $.inArray('Shipping Three', smethods))
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

按文字查找范围,然后在其上一个兄弟中找到广播:

$("span:contains('Shipping One')").prev().find('input').prop("checked",true);