Отображение большего количества переключателей на основе выбора радио?

0

Я честно не знаю, с чего начать. Я знаю, как сделать это с помощью базового html, но мне нужно вытащить вопросы из базы данных, но я чувствую, что этот способ намного сложнее.

Что заставляет смущать то, что мне нужно использовать цикл for для отображения всех вопросов верхнего уровня. Затем, когда они выбирают "Да" на вопрос верхнего уровня, он отображает вопрос более низкого уровня. Прямо сейчас у меня есть только отображение вопросов верхнего уровня, потому что я понятия не имею, как заставить его разблокировать вопросы более низкого уровня.

Вот мой код HTML.

<!doctype html>
<html>
<head>
 <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
  <script>
  jQuery(function($){

    // Prevents errors in old IE.
    if(!window.console || !window.console.log) window.console = {log: function(){}};

    // Enable debugging for complex logic.
    var debug = true;

    function checkConditions(inputs, views){
      views.each(function(){
        var view = $(this);
        var conditions = view.attr('data-view-conditions').split(',');
        var display = true;

        // Loop over all required conditions to be met.
        for(var i = 0; i < conditions.length; i++){
          var name = conditions[i].split(':')[0];
          var value = conditions[i].split(':')[1];
          var input = inputs.filter('[name="' + name + '"]:checked');

          if(debug) console.log('\nRecalculating view conditions.');

          if(!input.length){
            display = false;
            if(debug) console.log('View not show as no :checked input with the name "' + name + '" was found.');
          }else{
            if(value != undefined && input.val() != value){
              display = false;
              if(debug) console.log('View not show as no :checked input with the name "' + name + '" has the value of "' + input.val() + '". Value needed was: "' + value + '".');
            }
          }
        }

        if(display){
          view.css({display: 'block'});
        }else{
          view.css({display: 'none'});
        }

      });
    }

    $('form').each(function(){
      var form = $(this);
      var inputs = form.find('input[type="checkbox"], input[type="radio"]');
      var views = form.find('[data-view-conditions]');

      // Recalculate which views to be shown each time the inputs change.
      inputs.on('change', function(e){
        checkConditions(inputs, views);
      });

      // Check conditions to set up required view state on page load.
      checkConditions(inputs, views);
    });

  });
  </script>

   <!--<link href="css/bootstrap.min.css" rel="stylesheet">-->



<meta charset="utf-8">
<title>Submit a Ticket</title>

<link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.4.2/forms-min.css">
<style>
.myForm {
    margin-left: auto;
    margin-right: auto;
    max-width: 768px;
}
</style>
</head>

<body>
<form name="ticket1" class="pure-form pure-form-stacked myForm" action="flashpoint_processing.php" method="post">

<h2>Submit A Ticket</h2>


<legend> Your Details </legend>
<label> 
<span>First Name: </span>
    <input id="FirstName" name="FirstName" type="text" placeholder="" class="input-xlarge" required>
</label>
<label>
<label> 
<span>Last Name: </span>
    <input id="LastName" name="LastName" type="text" placeholder="" class="input-xlarge" required>
</label>
<label>  
<span> Business Name </span>
    <input id="Busname" name="Busname" type="text" placeholder="" class="input-xlarge">
 </label>

<label>Phone</label>
    <input id="Phone" name="Phone" type="text" placeholder="" class="input-xlarge" required>
<label>Extension</label>

    <input id="Ext" name="Ext" type="text" placeholder="" class="input-small">
<label> E-mail</label>
    <input id="email" name="email" type="text" placeholder="" class="input-xlarge" required>

<label>Preferred Method of Contact</label>
      <input type="radio" name="contact" id="contact-0" value="Phone" checked="checked">
      Phone
      <input type="radio" name="contact" id="contact-1" value="Email">
      Email


<label>
<legend>Issue</legend>  
<?
$topq = array();
$topid = array();
$results = mysql_query("select questions, ID from tbl_questions where top=1");
while($row = mysql_fetch_array($results)) {
    $topq[] = $row['questions'];
    $topid[] = $row['ID'];
};

for($i=0;$i<count($topq);$i++){
    echo "<label>";
    echo $topq[$i];
    echo "</label>";
    echo " <input type=\"radio\" name=\"question+$i\" id=\"$i\" value=\"1\" checked=\"checked\">No
      <input type=\"radio\" name=\"question+$i\" id=\"$i+1\" value=\"2\">Yes";
    echo $topid[$i];
    echo "<br>";
};
?>
<br>
<input type="submit" name="ticket" value="Submit">
</form>

Вот пример того, что я пытаюсь сделать. http://jcsites.juniata.edu/students/bookhjr10/flashpoint/test6.html

Если бы мы могли просто запрограммировать вопросы, я мог бы сделать это легко, но они хотят вытащить его из базы данных.

Теги:

1 ответ

0

JQuery изменит вашу жизнь. Вы можете установить прослушиватель событий для каждого переключателя, а затем в событии изменения выполнить вызов ajax для загрузки новых элементов в массив с сервера, а затем просто перебрать этот массив и сгенерировать html. Затем вы можете использовать метод.html(), чтобы вставить сгенерированный html в выбранный div :)

Ещё вопросы

Сообщество Overcoder
Наверх
Меню