簡體   English   中英

想要使用 jquery 獲取最近的內部選中單選按鈕的值

[英]want to fetch value of closest inner checked radio button using jquery

想要使用 jquery 獲取最近的內部選中單選按鈕的值:

我的代碼片段:

HTML 代碼片段:

<div class="rating" data-islogin="<?php echo $this->session->userdata('vhkrt_clt_logged_in')==TRUE ? 1:0;?>" data-userid="<?=$cltId?>" data-prodid="<?=$prod->prod_id?>">
    <input type="radio" id="star5_<?=$prod->prod_id?>" name="rating" value="5" />
    <label class = "full" for="star5_<?=$prod->prod_id?>"></label>
    <input type="radio" id="star4_<?=$prod->prod_id?>" name="rating" value="4" />
    <label class = "full" for="star4_<?=$prod->prod_id?>"></label>
</div>

jQuery 代碼片段:

$('.rating').click(function(){
    var rating = $(this).closest('input[name = rating]:checked').value;
    alert(rating); //getting "undefined"
})  

我正在嘗試上面的代碼片段,但我得到的評級值是“未定義”的警報

請建議我正確的聲明來檢查單選按鈕的值。

由於某些情況,我不想實現單選按鈕的“onchange”事件。

jQuery closest用於查詢祖先,在您的情況下,您需要子標簽。 你可以用children來代替

 $('.rating').click(function(){ var rating = $(this).children(`input[name = 'rating']:checked`).val(); alert(rating); })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="rating" data-islogin="<?php echo $this->session->userdata('vhkrt_clt_logged_in')==TRUE? 1:0;?>" data-userid="<?=$cltId?>" data-prodid="<?=$prod->prod_id?>"> <input type="radio" id="star5_<?=$prod->prod_id?>" name="rating" value="5" /> <label class = "full" for="star5_<?=$prod->prod_id?>"></label> <input type="radio" id="star4_<?=$prod->prod_id?>" name="rating" value="4" /> <label class = "full" for="star4_<?=$prod->prod_id?>"></label> </div>

試試這個代碼:

$('.rating').click(function(){
    var rating = $(this).find("input[name = 'rating']:checked").val();
})  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM