Jquery получава и показва радио стойности на живо

Имам формуляр, съдържащ радио бутони. Те се наричат ​​option1, option2 и option3. Всеки един от тези радио бутони има 3 различни потенциални стойности.

Трябва да покажа текущата "проверена" стойност под формуляра. Следвам ръководството за jquery и се обърквам много.

<script>
function displayVals() {
  var opt1 = $('input:radio[name=option1]:checked').val() || [];
  var opt2 = $('input:radio[name=option2]:checked').val() || [];
  var opt3 = $('input:radio[name=option3]:checked').val() || [];
  $("p").html("First item is " + opt1.join(", ") + " the second is " + opt2.join(", ") + " and third is " + opt3.join(", ") + ".");
}

$("input").change(displayVals);
displayVals();

However, nothing displays below the form. For example, option1 could be either White, Red or Black. If they check black, I need it to say "First item is black the second is whatever and the third is whatever." Below the form updating each time one of the values changes.


person Michael Clarke    schedule 22.09.2012    source източник
comment
Обзалагам се, че тези неща хвърлят изключение, защото низовете нямат join метод.   -  person Prinzhorn    schedule 22.09.2012


Отговори (2)


Това трябва да работи. Ето цигулката jsfiddle

function displayVals() {
  var opt1 = $('input:radio[name=option1]:checked').val() || '';
  var opt2 = $('input:radio[name=option2]:checked').val() || '';
  var opt3 = $('input:radio[name=option3]:checked').val() || '';
  $("p").html("First item is " + opt1 + ", the second is " + opt2 + ", and third is " + opt3 + ",.");
}

$("input:radio").click(displayVals);
displayVals();​
person Sahil Kapoor    schedule 22.09.2012
comment
jsfiddle.net/HdtEj Добавих това към действителния код, който използвам, но не работи, изисква ли ID ? - person Michael Clarke; 22.09.2012
comment
Вашата цигулка нямаше етикет ‹p›, добавих го тук е актуализираният jsfiddle - person Sahil Kapoor; 22.09.2012

val() връща низ или undefined и никога масив. Така че това трябва да бъде

function displayVals() {
    var opt1 = $('input:radio[name=option1]:checked').val() || 'not selected';
    var opt2 = $('input:radio[name=option2]:checked').val() || 'not selected';
    var opt3 = $('input:radio[name=option3]:checked').val() || 'not selected';

    $("p").html("First item is " + opt1 + " the second is " + opt2 + " and third is " + opt3 + ".");
}
person Prinzhorn    schedule 22.09.2012