Hash
Hash

Reputation: 566

Accessing action and value attributes using JS

let dealer={
    name : document.getElementById('dealer-name'),
    submit : document.getElementById('dealer-save'),
};
let dnames=['str', 'name'];

dealer.name.addEventListener('keyup', check);

function check(){

    for (let i=0; i<dnames.length; i++){
        if (dnames[i] === dealer.name.value) {
            console.log('same');
            dealer.submit.value = "Update";
        } else {
            dealer.submit.value = "Save";
        }

    };
}
<!DOCTYPE>
<html>
<body>
  <form action="/php/newdealer.php" id="addDealer">
    <input required type="text" id="dealer-name">
    <input type="submit" value="Save" id="dealer-save">
  </form>
</body>
</html>

Summary of the Code:

In the webpage a simple form is shown consisting an input field and submit button. Each time a character is inputted in the input field check() function is executed.

If the value in input field matches with any of the element in dnames[] array Then value of submit button is expected to be 'update' and the string 'same' is logged into console, else if the value in input field doesn't matches with any of the element in dnames[] array Then value of submit button is expected to be 'save'

Problem:

When i type in "str" in the input field 'same' is logged into the console as expected but the value of the submit button doesn't changes to 'update'. Why dealer.submit.value="Update" failed to work?

Upvotes: 0

Views: 28

Answers (1)

Estevan Maito
Estevan Maito

Reputation: 1808

The problem is that your loop keeps running after it encounters the right answer.

  1. str is the first element in the array, so it updates the button value to "Update"
  2. the loop goes to the next value in the array, name
  3. It's not the same as the input value, so it updates the button value back to 'Save'

It all runs almost immediately, so it looks like it's not uploading.

You can solve this adding a break or return after assigning "Update" to the button, like this:

let dealer={
    name : document.getElementById('dealer-name'),
    submit : document.getElementById('dealer-save'),
};
let dnames=['str', 'name'];

dealer.name.addEventListener('keyup', check);

function check(){

    for (let i=0; i<dnames.length; i++){
        if (dnames[i] === dealer.name.value) {
            console.log('same');
            dealer.submit.value = "Update";
            break; // add this to your code
        } else {
            dealer.submit.value = "Save";
        }

    };
}

Upvotes: 1

Related Questions