The value of input element changes but not shown in the browser(s)?

6.8k Views Asked by At

I wrote a live search field for a part of my form, when the suggestions come and user clicks on one of them, a js function (selectedService) is being called to get the innerHTML of the li which the user clicked on! everything works perfectly when you look at the code in 'Inspect Element' of the browser, but not on the web page!

after the user clicks on the on the suggestion the value property of input element changes in the code but on the browser. the content of input field is still what the user is typing in it.

here's the code :

<!DOCTYPE html>
<html dir="rtl">
<head>
<meta charset="UTF-8">
</head>
<body>

<input value="" id="services" placeholder="click or type plz..."/>
<ul id="suggestions">
</ul>
<style>
    /* some styles */
</style>
<script>
var input = document.getElementById("services");
var suggestions = document.getElementById("suggestions");

input.oninput = function() {
    var q = input.value;

    if (q.length < 2) {
        suggestions.setAttribute("style","display: none");
        return;
    }
    var xhr2 = new XMLHttpRequest;
    xhr2.open("GET", "theURL/service-request-handler.php?q="+q, true);
    xhr2.onreadystatechange = function() {
        if (xhr2.readyState == 4 && xhr2.status == 200)
        {
            var result = xhr2.responseText;
            console.log("server response = "+result);
            var json = JSON.parse(result);
            showSuggestions(json);
        }
    };
    xhr2.send();
};

function showSuggestions(json) {
    suggestions.setAttribute("style","display: block");
    var li_list = '';
    var i = 0;
    for (i=0; i<json.length; i++) 
        li_list += '<li id="'+i+'" onclick="selectedService('+i+')">'+json[i]+'</li>';

    suggestions.innerHTML = li_list;
}

function selectedService(i) {
    li_target = document.getElementById(i);
    console.log(li_target.innerHTML);
//    input.innerHTML = li_target.innerHTML;
    input.setAttribute("value",li_target.innerHTML);
    suggestions.setAttribute("style","display: none");
}


</script>

</body>
</html>

the result in the Inspect Element : before onclick event

when event happens!

I'd appreciate any help or suggestions :)

4

There are 4 best solutions below

0
On BEST ANSWER
input.value = li_target.innerHTML
1
On

You can use jQuery UI for autocomplete search.

0
On

You can set value property directly:

input.value=li_target.innerHTML;
0
On

Probably you are using firefox browser, you should use this to work in both, chrome and firefox.

input.value = li_target.innerHTML;

This happens because property and attributes are different.

Attributes are defined on the HTML markup but properties are defined on the DOM.