获取列表使用foreach在javascript里面php codeigniter [英] getting list using foreach in javascript inside php codeigniter
问题描述
我有一个JS函数在我的PHP视图文件。我想做的是当函数验证输入在数据库中不存在时启用按钮。所以这里是我的函数:
I have a JS function inside my PHP view file. What I want to do is enable a button when the function verifies that the input does not exist in the database. So here's my function:
var name = 0;
$("#edit-name").on("change", edit_name);
function edit_name() {
if ($('#edit-name').val()== ""){
$('#edit-name').addClass('required');
$('#warning').html('Please fill required input.');
name = 0;
}
else {
<?php foreach ($name_list as $list) { ?>
if ($('#edit-name').val() == '<?php echo $list->name ?>') {
name = 0;
$('#warning').html('Name already exists');
}
else {
$('#warning').html('');
name = 1;
}
<?php } ?>
}
enableButton();
}
function enableButton(){
if (name == 1)
document.getElementById('edit-btn').disabled = false;
else
document.getElementById('edit-btn').disabled = true;
}
我不知道有什么问题,正确,我的代码不能正常工作:它检查是否有输入时工作。但是即使我输入一个新的名字,按钮也不会发生什么。在输入现有名称时,不会出现警告。
I don't know what's wrong but even if the inputs are correct, my code is not working properly: It works when it checks if there is an input or not. But nothing happens to the button even if I input a new name. When I input an existing name, the warning doesn't appear.
推荐答案
查看您生成的HTML代码看你的错误。
Look at your HTML-Code that is generated than you see your mistake.
如果你有一个Array [name=>test],[name=>test2生成以下HTML:
If you have for example a Array ["name" => "test"], ["name" => "test2"] than you view generates the following HTML:
if ($('#edit-name').val() == 'test') {
name = 0;
$('#warning').html('Name already exists');
}
else {
$('#warning').html('');
name = 1;
}
if ($('#edit-name').val() == 'test1') {
name = 0;
$('#warning').html('Name already exists');
}
else {
$('#warning').html('');
name = 1;
}
您看到else总是为真。
You see "else" is always true.
您需要写:
<?
$stringarray = "";
foreach($name_list as $list){
$stringarray .= '"'.$list->name.'",';
}
// Del last ,
$stringarray = substr($stringarray,0,-1);
?>
var names = [<?php echo $stringarray;?>];
if (names.indexOf($('#edit-name').val()) != -1) {
name = 0;
$('#warning').html('Name already exists');
}else {
$('#warning').html('');
name = 1;
}
这篇关于获取列表使用foreach在javascript里面php codeigniter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!