简体   繁体   English

如何将Onchange放在Ajax返回的html select上

[英]How to put Onchange on Ajax returned html select

I have a problem putting Onchange() on a ajax returned html on my form. 我在将Onchange()放在表单上返回的Ajax html上时遇到问题。

Basically I have clients listed in a select. 基本上,我在选择中列出了客户。

<select name="company" id="company">                                                            
   <?php 
       $sqlget1 = "SELECT * FROM clients WHERE 1=1 ORDER BY company ASC;";
       $resget1 = mysql_query($sqlget1);
       while($row1 = mysql_fetch_array($resget1)) {                                                            
   ?>                                                            
       <option value="<?php echo $row1['id']; ?>"><?php echo $row1['company']; ?></option>                                                                                                                        
   <?php
       }
   ?>
</select>

And when some one selects a client, im using Ajax to fetch projects that are assigned to that client. 当有人选择一个客户端时,我将使用Ajax来获取分配给该客户端的项目。

$('#company').change(function() {                        
    var selectedProject = $("#company option:selected").val();
    $.ajax({
        type: "POST",
        url: "get_projects.php",
        data: { projects : selectedProject } 
    }).done(function(data){
        $("#response").html(data);
    });
});

It gets returned back to 它返回到

<div id="response"></div>

The code for get_projects.php is get_projects.php的代码是

<?php
include('inc.php');
if(isset($_POST["projects"])) {      
    $projects = $_POST["projects"];    
    $sqlget2 = "SELECT * FROM projects WHERE cid=\"$projects\" ORDER BY pname ASC;";        
    $resget2 = mysql_query($sqlget2);
    echo '<select name="project" id="project" class="select2 form-control">';
    echo '<option value="">-- Select a project --</option>';
    while($row2 = mysql_fetch_array($resget2)) {                                                            
?>                                                            
       <option value="<?php echo $row2['id']; ?>" pstatus="<?php echo $row2['pstatus']; ?>" ptype="<?php echo $row2['ptype']; ?>"><?php echo $row2['pname']; ?></option>                                                                                                                        
<?php
    }
    echo '</select>';
 }
?>

Now when i use on change function on the returned html from ajax it is not working. 现在,当我在从ajax返回的html上使用change函数时,它不起作用。

I tried to see the source code and found out that it is not there atall. 我试图查看源代码,发现它根本不存在。 It only shows the <div id="response"></div> 它仅显示<div id="response"></div>

But i can see the result on the form but cant see the source in the source code. 但是我可以在窗体上看到结果,但是在源代码中看不到源代码。

Hence i thought that's why the Onchange() is not working for <select name="project" id="project" class="select2 form-control"> because it is not showing. 因此,我认为这就是为什么Onchange()无法用于<select name="project" id="project" class="select2 form-control">原因,因为它没有显示。

When you use ajax, you add a piece of html later to the DOM (browsers view), because you use .change the onchange is only added to the '#company' elements wich already exist in the browser. 使用ajax时,稍后会在DOM(浏览器视图)中添加一段html,因为使用.change时,onchange仅添加到浏览器中已经存在的'#company'元素中。

You need to bind the onchange after you appended the html. 附加html后,需要绑定onchange。 for example: 例如:

$('#company').change(function() {        
    onCompanyChange()                
});

function onCompanyChange(){
    var selectedProject = $("#company option:selected").val();
    $.ajax({
        type: "POST",
        url: "get_projects.php",
        data: { projects : selectedProject } 
    }).done(function(data){
        $("#response").html(data);
        $('#company').change(function() {        
            onCompanyChange()                
        });
    });
}

OR 要么

You can also use an on change, on change does work with elements added later to to the dom. 您还可以使用on change,on change确实可以与稍后添加到dom中的元素一起使用。 so this code works with elements wich already exists and new added elements with for example ajax 因此,此代码适用于已经存在的元素以及例如ajax的新添加元素

$("#company").on("change",function(){
    console.log("change");
});

I see, the data which is return from Ajax is object 我看到,从Ajax返回的数据是对象
You should parse it to get the raw content an set into DIV 您应该解析它以将原始内容集放入DIV中

When you are dynamically adding mark up to the page the javascript doesn't know about the controls you have added through php. 当您在页面上动态添加标记时,javascript并不知道您通过php添加的控件。

Try finding the newly added control like this: 尝试找到新添加的控件,如下所示:

var select = document.getElementById('project');

Then you should be able to fire your on change method 然后,您应该可以触发变更方法

Not tested, but it should work 未经测试,但应该可以工作

<?php
include('inc.php');
if(isset($_POST["projects"]))
{
$projects = $_POST["projects"];    
$varOut = "";
$sqlget2 = "SELECT * FROM projects WHERE cid=\"$projects\" ORDER BY pname ASC;";        
$resget2 = mysql_query($sqlget2);
$varOut .= '<select name="project" id="project" class="select2 form-control">';
$varOut.= '<option value="">-- Select a project --</option>';
while($row2 = mysql_fetch_array($resget2))
{                                                            
    $varOut.= "<option value=" . $row2['id'] . " pstatus=". $row2['pstatus']. ">ptype=".$row2['ptype']."><".$row2['pname']."></option>";                                                                                                                       
}
$varOut.= '</select>';
}
echo $varOut;
?>

I've finally solved the issue. 我终于解决了这个问题。

Basicall i just pasted the Onclick() script for '#projects' inside the get_projects.php file. 基本来说,我只是将getclick.php文件中的#projects的Onclick()脚本粘贴了。

So now every time when it comes from ajax it also brings the javascript as well. 所以现在每次当它来自ajax时,它也带来了javascript。

Try below code. 尝试下面的代码。 Hope this works fine. 希望这能正常工作。

$(document).ready(function() {
    $(document).on('change', '#company', function() {
        var selectedProject = $("#company option:selected").val();
        $.ajax({
            type: "POST",
            url: "get_projects.php",
            data: { projects : selectedProject } 
        }).done(function(data){
        $("#response").html(data);
        });
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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