سؤال

I am new to jquery and javascript, and I have searched for this answer and couldn't find it.

My select tag:

<select id="selectarea" name="sometext" size="10" width="250" style="width: 250px" onchange="openDisciplina(this)">
<?php
    foreach ($areas as $name) {
        echo "<option value='" . htmlentities($name[0]) . "'>" . htmlentities($name[0]) . "</option>";
    }
?>
</select><br>

and my js function:

<script>
function openDisciplina(element)
{
    jQuery.ajax({
        type: "POST",
        url: "http://arenautfpr.com/professor/stage/disciplina/disciplina.php",
        data: {dados:element.value},
        success: function(data){
            $('#novidades2').html(data);
        }
    });
}
</script>

when I call this function it does not work at all, nothing happens. Even if I put only an alert inside the function it won't work, so I don't think it is a problem with the ajax part.

On the error console I get this error when I choose an option:

ReferenceError: Can't find variable: openDisciplina

---- SOLVED

I Found that the problem was with the code not being on the <head> tag, so it was not working.

هل كانت مفيدة؟

المحلول

I would remove the javascript from the select element and use this script:

$(document).ready( function() {
    $("body").on( "change", "#selectarea", function() {
        alert("changed");
        //test with alert before putting your code in here
        //jQuery.ajax({
            //type: "POST",
            //url: "relative/path/to/disciplina.php",
            //data: {dados:this.value},
            //success: function(data){
                //$('#novidades2').html(data);
            //}
        //});
    });
});

Note that:

  • in the ajax call I changed dados to this.value instead of element.value.
  • using relative path instead of absolute path to disciplina.php
  • delegation is needed for the event since #selectarea is generated dynamically after the dom is loaded. I used delegation from the body, but it may be more efficient to delegate from a closer parent element of #selectarea.

نصائح أخرى

Check the error in console. it not calling because there is some error which is preventing to call this function.

try onchange event handler. here is fiddle link

<select id="selectarea" name="sometext" size="10" >
    <option val=1>One</option>
    <option val=2>Two</option>
    <option val=3>Three</option>
    <option val=4>Four</option>
</select>
<script>
var s=document.getElementById('selectarea');
s.onchange=function(e){
    console.log(e.target.value)
}
<script>

And if you want to use previous code only then try to put script block in head of page.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top