简体   繁体   中英

Javascript `onclick` doesn't work in separate JS file

I have to delete some answer so I used onclick event. This event only worked in same html page within the script tag, but it doesn't working on separate js file.

editquestion.php

<a href="javascript:void(0);" title="delete" onClick="deleteAnswer('<?php  if($option->answerId != ''){ echo "{$option->answerId}"; } ?>','old');"><i class="icon md-recycle"></i></a>

user.js

function deleteAnswer(uid,value){
  //alert(uid);
  if(value=='old'){
    $("#answer_form_group_"+uid).empty().hide();
    $("#answer_form_group_"+uid).append("<input type='hidden' name='deleteAnswer[]' value='"+uid+"'>");
    } else {
    $("#answer_form_group_"+uid).remove();
  }
}

function addans(){
$('.addans').unbind("click");
$('.addans').on("click",function(e){
    if ((($('#ansform').find(".form-group").length > 4)&&($("#sel1").val() == "multiplechoice"))||
        (($('#ansform').find(".form-group").length > 1)&&($("#sel1").val() == "trueorfalse"))||
        (($('#ansform').find(".form-group").length > 4)&&($("#sel1").val() == "multipleselect"))){
            noty({ text: 'your exceeded the maximium limit',type: 'error',modal:true,timeout:1000});
    } else {
        if(($('#ansform').find(".form-group").length > 0) &&($("#sel1").val() == "")){
            noty({ text: 'select Type of Question ',type: 'warning',modal:true,timeout:1000});
            } else {
            var uid = generateUid();
            var input_type = ($("#sel1").val() == "multiselect")?"checkbox":"radio";
            $('#ansform').append(     
            '<div class="form-group" id="answer_form_group_'+uid+'">'+
            '<div class="input-group">'+
            '<input type="text" id= "ans_'+uid+'" class="ans form-control input-lg ans inline" placeholder="Write answers here" name="ans[]">'+'&nbsp;&nbsp;'+
            '<input type="hidden" name="crt[]" value="0" />'+
            '<input type="'+input_type+'" id= "ctr_'+uid+'" class="correct" name="crt[]" value="1">'+'&nbsp;&nbsp;'+
            '<a href="javascript:void(0);" title="delete" onClick="deleteAnswer(\''+uid+'\',\'new\')"><i class="icon md-recycle"></i></a>'+
            '</div>'+
            '</div>'
            ); 
        }   
        e.preventDefault();
    }
});
}

function deleteAnswerOption(){
$("#ansform").off('click','.answer-delete');
$('#ansform').on('click', '.answer-delete', function(e) {
    e.preventDefault();
    //alert($(this).parent().parent().parent().attr('class'));
    // $(this).parent().parent().parent().remove();
});
}

All other functions are working properly but only this one shows error like Uncaught ReferenceError: deleteAnswer is not defined at HTMLAnchorElement.onclick .

Try with document.ready()

$( document ).ready(function() {
    //Paste your functions inside this

});

or

$(function() {
    //Paste your functions inside this;
});

make sure you put it into the head section of your html as follows

<head> <script type="text/javascript" src="path/to/script.js"></script> <!--other script and also external css included over here--> </head>

just replace src="path/to/script.js" with the name of your js file. if its in the the same folder, you won't need to put anything but this

"<script type="text/javascript" src="script.js"></script>"

again, script.js needs to be replaced with the name of your js file

deleteAnswer(uid, value) requires two parameters uid and value .

In your code, you are passing the first parameter via PHP snippet which contains an if clause to echo some value. What if that PHP snippet doesn't echo anything, what would happen? Exactly! Code will break.

Recommendation: Please insert else clause in your PHP snippet which should echo empty string literal .

You are welcome :)

Try this code

$(document).ready(function(){
    $('body').on('click','.addans',function(){
       alert('Hello Clieck me')
  })
})

https://jsfiddle.net/ta0ubp8j/3/

To check actual error follow these steps:

  1. GO to the browser console of editquestion.php page(press f12 key). 2.write deleteAnswer("xyz",""); then press enter 3.if it will give same "deleteAnswer is not defined error" then there will be two case four this error otherwise it will work.

    • your deleteAnswer function not define globally so you need to define it globally.
    • define all javascript code within $(document).ready(function(){*** your javascript code *******})
  2. if this will not work then check in browser console , anchor tag will not with proper deleteAnser function may be your php script breaks function syntax.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM