gpt4 book ai didi

javascript - 在 php codeigniter 内的 javascript 中使用 foreach 获取列表

转载 作者:行者123 更新时间:2023-12-03 12:36:03 25 4
gpt4 key购买 nike

我的 PHP View 文件中有一个 JS 函数。我想要做的是当函数验证数据库中不存在输入时启用一个按钮。这是我的功能:

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;
}

我不知道出了什么问题,但即使输入正确,我的代码也无法正常工作:它在检查是否有输入时起作用。但即使我输入新名称,按钮也没有任何反应。当我输入现有名称时,不会出现警告。

最佳答案

查看生成的 HTML 代码,然后发现错误。

例如,如果您有一个数组 ["name"=> "test"], ["name"=> "test2"],则您查看会生成以下 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”总是正确的。

你需要写:

 <? 
$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;
}

关于javascript - 在 php codeigniter 内的 javascript 中使用 foreach 获取列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23733275/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com