簡體   English   中英

在JavaScript中獲取選定的單選按鈕

[英]Getting selected radio button in JavaScript

在實際提出這個問題之前,我已經在這里嘗試了很多解決方案,但是沒有一個對我有用。

我試圖使用onclick處理程序,試圖通過輸入名稱獲取,嘗試getElementId ,嘗試elementClassName我也試圖循環它們var i = 0, length = radios.length; i < length; i++ var i = 0, length = radios.length; i < length; i++ var i = 0, length = radios.length; i < length; i++沒有為我工作!

邏輯

  1. 我的單選按鈕將基於ajax動作追加到視圖
  2. 我選擇任何一個單選按鈕
  3. 我想獲取此選定單選按鈕的值

這就是我的收音機的附加內容,使I made it short to be clean and easy to read

success:function(data) {
        $('.shipoptions').empty();
        $('.shipoptionstitle').empty();
        $('.shipoptionstitle').append('<h6>Select your preferred method</h6>');
        $.each(data.data, function(key, value) {
          $.each(value.costs, function(key2, value2) {
            $.each(value2.cost, function(key3, value3) {
              // number format
              var number = value3['value'];
              var nf = new Intl.NumberFormat('en-US', {
                  maximumFractionDigits:0, 
                  minimumFractionDigits:0
              });
              var formattedNumber = nf.format(number);
              // number format
              $('.shipoptions').append('<ul class="list-form-inline"><li><label class="radio"><input type="radio" name="postchoose" data-code="'+value['code']+'" data-service="'+value2['service']+'" value="'+ value3['value'] +'"><span class="outer"><span class="inner"></span></span>'+ value['code'] + ' - ' + value2['service'] + ' - Rp ' + nf.format(number) + ' - ' + value3['etd'] +'</label></li></ul>');
            });
          });
        });
} //success function ends here

現在,我想獲取data-codedata-servicevalue選定單選按鈕value

對於臨時人員,請幫助我在控制台中獲取這些值,稍后我將自己修復打印部件。

任何想法?

<input type="radio" name="postchoose" data-code="'DC11'" data-service="'DS22'" value="'V33">

var dataCode = $('input[name="postchoose"]:checked').data('code');
var dataService = $('input[name="postchoose"]:checked').data('service');

var selectedVal= $("input:radio[name=postchoose]:checked").val();

解決了

$(function() {
        $(".shipoptions").on('change', function(){
            var radioValue = $("input[name='postchoose']:checked");
            if(radioValue){
                var val = radioValue.val();
                var code = radioValue.data('code');
                var service = radioValue.data('service');
                alert("Your are a - " + code + "- " +service+ "- " +val);
            }
        });
    });

我需要獲得更高級別的單選按鈕.shipoptions

試試這個jQuery方法。

$("input[type='radio']").click(function() {
 var radioValue = $("input[name='postchoose']:checked").val();
 var dataCode = $("input[name='postchoose']:checked").attr('data-code');
 var dataService = $("input[name='gender']:checked").attr('data-service');
 console.log(dataCode);
 console.log(dataService);
 console.log(radioValue);
});

暫無
暫無

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

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