2012-01-10 93 views
0

我對JavaScript/jQuery不太熟悉,但是我已經設法編寫了一個輪詢腳本,它允許用戶在輪詢上投票並顯示結果,而無需刷新頁面。這是我想出了jQuery代碼:如何從輸入中獲取值並將其用作jQuery變量?

$("#poll_yes").click(function(){ 
        $("#poll_options").html(ajax_load); 
        $.post( 
         "query.php?module=vote", 
         {answer: "yes", pid: "<? display($_GET['username'], poll_id); ?>", to: "<?= $_GET['username'] ?>"}, 
         function(responseText){ 
          $("#poll_options").html(responseText); 
         }, 
         "html" 
        ); 
       }); 
$("#poll_no").click(function(){ 
       $("#poll_options").html(ajax_load); 
       $.post(
        "query.php?module=vote", 
        {answer: "no", pid: "<? display($_GET['username'], poll_id); ?>", to: "<?= $_GET['username'] ?>"}, 
        function(responseText){ 
         $("#poll_options").html(responseText); 
        }, 
        "html" 
       ); 
      }); 

這會得到在頁面上輸入元素的ID,並根據id它將然後將查詢發送到query.php。然後query.php會發回一個響應,然後這個響應就會顯示在頁面上。

這個腳本工作正常,但我遇到了另一個挑戰。我需要在一個頁面上顯示多個民意調查。我使用PHP來生成SQL數據庫中的民意調查,並想知道是否可以拉取「答案:否」,「答案:是」,「pid:$ id」,「to:$ username」等等。從一個領域。如果可能的話,整個頁面(每次投票)都需要多個表單?或者一個形式可以滿足多個輸入?

+0

測試閱讀文檔,它會幫助你很多......還有很多在網絡上的例子,這是很容易得到JQuery的真正深諳。 – trgraglia 2012-01-10 07:58:49

回答

1

你可以爲每個投票形式,以及包括PID與類型的輸入容易形成形式的Fileds = 「隱」。然後,即使在「是」或「否」按鈕(通過ID)上使用點擊,您也可以在所有表​​單提交事件上附加回調。這也可以讓你將兩個函數合併爲一個回調函數。

<script> 
$("form.Poll > input[type='button']").click(function(e) { 
    e.preventDefault(); 
    var form= $(this).closest("form"); 
    alert("QuestionId:"+$("input[name='QuestionId']", form).val()+" clicked on:"+$(this).val()); 
}); 
</script> 
<form method='POST' action='update.php' class='Poll'> 
    <input type='hidden' name='QuestionId' value='1'/> 
    Do you like jQuery? 
    <input type='button' name='Answer' value='Yes'/> 
    <input type='button' name='Answer' value='No'/> 
</form> 
<form method='POST' action='update.php' class='Poll'> 
    <input type='hidden' name='QuestionId' value='2'/> 
    Do you like AJAX? 
    <input type='button' name='Answer' value='Yes'/> 
    <input type='button' name='Answer' value='No'/> 
</form> 
<form method='POST' action='login.php'> 
    This form will fire like a normal form if you click on submit but it will not pass though the submit script defined above 
    <input type='submit' name='Answer' value='Login'/> 
</form> 

這可以在http://jsfiddle.net/te9YL/

+0

我不確定你的意思是在所有表單上附加回調。你能提供一些示例代碼嗎? – Xecure 2012-01-10 08:17:26

1

是的,你可以得到價值通過.VAL()的jQuery的功能

$("#yourid").val(); 
相關問題