Reputation: 566
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
Reputation: 1808
The problem is that your loop keeps running after it encounters the right answer.
str
is the first element in the array, so it updates the button value to "Update"name
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