2015-12-21 67 views
-1

我有一個帶複選框和輸入文本的表單。這裏是我的表格:PHP僅當勾選複選框時才提交表單

<form action="index.php?option=com_platiniumchristmas&view=success" method="post"> 
    <label> 
    <input type="checkbox" name="termsConditions" id="chbx" value="Yes" onclick="foo()" /> 
    <?php echo JText::_('COM_PLATINIUMCHRISTMAS_TERMSCONDITIONS_TEXT');?> 
    </label> 
    <input type="submit" value="Emitir Voucher" class="btn btn-success" style="float: right" /> 
    <div style="overflow: hidden; padding-right: .5em;"> 
    <input type="text" name="friendName" style="width: 100%;" /> 
    <input type="hidden" name="canal" value="<?php echo $_POST[" canal "]; ?>"/> 
    </div> 
</form> 

這個想法是隻提交表格,如果檢查複選框值。我怎麼去解決這個問題。我曾嘗試使用JavaScript,但沒有成功。

我試圖使用JavaScript:

<script type=」text/javascript」> 
var checkbox = document.getElementById("chbx"); 
function foo(){ 
    if(checkbox.checked){ 
    alert("meap"); 
    }; 
}; 
</script> 
+0

告訴我們你試過了什麼。 – Inurosen

回答

1

你並不需要的JavaScript的。只需使用屬性即可。

<form action="index.php?option=com_platiniumchristmas&view=success" method="post"> 
    <label> 
    <input type="checkbox" name="termsConditions" id="chbx" value="Yes" required /> 
    <?php echo JText::_('COM_PLATINIUMCHRISTMAS_TERMSCONDITIONS_TEXT');?> 
    </label> 
    <input type="submit" value="Emitir Voucher" class="btn btn-success" style="float: right" /> 
    <div style="overflow: hidden; padding-right: .5em;"> 
    <input type="text" name="friendName" style="width: 100%;" /> 
    <input type="hidden" name="canal" value="<?php echo $_POST[" canal "]; ?>"/> 
    </div> 
</form> 

這將停止表單提交,除非複選框被選中。請記住,您始終需要後端驗證來驗證,因爲如果有足夠的努力,請求可能會被僞造。

+0

所需的工作正常。謝謝 –

0

嘗試完整的例子,它應該工作。

然後更正您的代碼。

<!DOCTYPE html> <html> <head> <script> function validateForm() { 
    var x = document.forms["myForm"]["fname"].value; 
    if (x == null || x == "") { 
     alert("Name must be filled out"); 
     return false; 
    } } </script> </head> <body> 

<form name="myForm" action="index.php" onsubmit="return validateForm()" method="post"> Name: <input type="text" name="fname"> <input type="submit" value="Submit"> </form> 

</body> </html> 

感謝 阿米特

+0

是的,如果有可能你的幫助我會坦克滿。 Javascript我新使用這種語言 –

-1

你失去了你的代碼的上下文。嘗試:

<script type=」text/javascript」> 

function foo(){ 
var checkbox = document.getElementById("chbx"); 
    if(checkbox.checked){ 
    alert("meap"); 
    }; 
}; 
</script> 
+0

嗨。我使用該代碼並沒有任何反應。 –

0
$("#form").submit(function(e) { 
    if(!$('input[type=checkbox]:checked').length) { 
     alert("Please select the checkbox."); 

     //stop the form from submitting 
     return false; 
    } 

    return true; 
}); 

<form id='form'> 
    <div> 
     <input type="checkbox" name="option-1" id="option-1"> <label for="option-1">Option 1</label> 
    </div> 
    <div> 
     <input type="submit" value="Do thing" > 
    </div> 
</form> 

使用本

相關問題