php - 文本输入更改值和即时检查

标签 php jquery ajax angularjs

我想知道是否可以在不单击提交的情况下检查数组在更改文本框(输入字段)的值时更新结果 div。< br/> 在我的尝试中,我尝试使用 php 和 jQuery,但无济于事。我希望能够在用户单击按钮并替换输入字段 ($query) 中的文本后立即检查数组。
还有其他方法可以尝试吗?
代码如下:

<?php 
//arrays
$results = array();
$results["car"] = array( "name" => "toyota");
$results["food"] = array( "name" => "bread");
$results["tool"] = array( "name" => "hammer");
$query = "";
?>
<script>
function colour() {
    document.getElementById("s").value = "colour";
}
function tool() {
    document.getElementById("s").value = "tool";
}
</script>

<div id="form">
<input type="text" value="<?php echo $query; ?>" id="s" />
</div>

<button onclick="colour()">Check colours</button>
<button onclick="tool()">Check tools</button>




<div id="result">
<?php  
         foreach ($results as $key => $val) {
           if ($key === $query) {
               echo " match found! for " . $key;
           }
         }
    ?>
</div>

我期待您的意见。 :)

最佳答案

假设您不想提交表单,您可以在 javascript 中全部完成。

首先,您需要确保将结果中的值正确传递给脚本:

<?php 
//arrays
$results = array();
$results["car"] = array( "name" => "toyota");
$results["food"] = array( "name" => "bread");
$results["tool"] = array( "name" => "hammer");
?>
<script>
// Generate a variable / object that contains the necessary information
var results = <?php echo json_encode($results); ?>;

function colour() {
    document.getElementById("s").value = "colour";
}
function tool() {
    document.getElementById("s").value = "tool";
}
</script>

现在您的脚本中将有一个对象可用,您可以在单击按钮后立即使用该对象检查值。

所以在你的函数中你可以使用它

function colour() {
    document.getElementById("s").value = "colour";
    // here you can use `results`
    // you would need to add some details / logic to your question
    // if you need more information
}

另请注意,button 元素的默认设置是提交按钮,至少在 HTML 4 中是这样,因此如果您的表单元素周围有一个表单,您可能应该取消默认事件。

您可以在点击处理程序中执行此操作,同时删除您的内联 javascript:

$('button').on('click', function(event) {
  event.preventDefault();
  // the rest of your click event handler
});

关于php - 文本输入更改值和即时检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29743105/

相关文章:

jquery - JQuery 中的 CSS 问题

javascript - AJAX Javascript 元素未更新

php - Laravel 5.6 Eloquent 在没有人要求时尝试更新不存在的列。 (多对多关系)

php - 使用 MySQL + PHP 更新多个变量

jquery - Ajax post 从 Django 返回 CSRF 错误

javascript - ASP.NET WebForms 无法使用 ajax 从 javascript 调用 webmethod

jquery - 使用 jQuery 解析 JSON [2]

php - Inner Join limit 左表结果限制为 1

javascript - JQuery Remove 在页面刷新后返回?

javascript - 在父div中添加类