2017-01-25 141 views
-1

以下代碼用於動態創建複選框。

但在Chrome控制檯中,它表示$未定義。這$錯誤是在這一行:

$.post(
      "index1.php", 
      { 
       "newopt": newopt 
      }, 

完整的代碼在這裏...

var optiondiv = document.getElementById('option-div'); 

document.getElementById('create').onclick = function() { 

    newopt = document.getElementById('new-option').value; 
    if(newopt){ 
     var input = document.createElement('input'), 
     label = document.createElement('label'); 
     /* IF USER DID NOT INPUT A TEXT, 'No Entered Text' WILL BE THE DEFAULT VALUE */ 
    newopt = (newopt == '')?'No Entered Text':newopt; 
     /* FILL OUT THE TAGS OF THE NEW INPUT ELEMENT */ 
     input.type = "checkbox"; 
     input.setAttribute("value", newopt); 
     input.setAttribute("checked", true); 
     input.setAttribute("name", "prints[]"); 
     /* PUT THE INPUT ELEMENT/RADIO BUTTON INSIDE THE LABEL */ 
     label.appendChild(input); 
     label.innerHTML += newopt+'<br>'; 
     /* PUT THE LABEL ELEMENT INSIDE THE option-div DIV */ 
     optiondiv.appendChild(label); 
     //optiondiv.appendChild(input); 
     //ele.appendChild(input); 
     //input.onclick = function(){ alert('this is test'); }; 

     //optiondiv.appendChild(label); 
     document.getElementById('new-option').value = ''; 

     $.post(
      "index1.php", 
      { 
       "newopt": newopt 
      }, 
      function(data) { 
       if(data.success){ 
        alert('Successfully Added To dB'); 
       }else{ 
        alert('Not Added To DB'); 
       } 

     }); 

    }else{ 
     alert('Please Enter Check Box Value.'); 
     return false; 
    } 



}; 
+0

這個問題是標記爲 「PHP」 因爲......? – Twinfriends

+2

這不是PHP,但JavaScript和jQuery。你有沒有包含jQuery? – jeroen

+0

你試過用'jQuery'替換'$'嗎? – Cashbee

回答

0

要在自己的JavaScript使用jQuery,你需要確保<script>元素包括jQuery的前您自己的JavaScript(無論是內聯還是包含)。

(嚴格地說,會延遲執行,你可以不那麼嚴格,但與簡單的方法開始。)

EG。這將工作:

<script src="https://code.jquery.com/jquery-3.1.1.js"></script> 
<script type='text/JavaScript'> 
    // Your code using jQUery 
</script> 

但這不會:

<script type='text/JavaScript'> 
    // Your code using jQUery 
</script> 
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>