0

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.

1 Answer 1

1

Look at your HTML-Code that is generated than you see your mistake.

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

You see "else" is always true.

You need to write:

 <? 
 $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;
        }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.