0

The code below gives me an error "Fieldname not defined" when I am defining data-attributes and using them as parameters in a function. The update_person.php is updating a record in a database using the attributes in the input field. Is there a way to work around this?

<!DOCTYPE html>

<html>
<head>
<script>

function update_person(str,fieldname,key,keyvalue) 
{
    if (str == "") {
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else { 
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET","update_person.php?q="+str+"&f="+fieldname+"&n="+key+"&nv="+keyvalue,true);
        xmlhttp.send();
    }
}
</script>

</head>

<body>

<form>
<input type="text" name="firstname" data-fieldname ="firstname" data-key ="PERSONID" data-keyvalue = "7" onchange = "update_person(this.value,this.data-fieldname, this.data-key,this.data-keyvalue)">
</form>
<br>
<div id="txtHint"> </div>
</body>
</html>

1 Answer 1

1

You can refer to a custom data attribute using the dataset property:

update_person(this.value,this.dataset.fieldname, this.dataset.key,this.dataset.keyvalue)

Ref:

Reading the values of these attributes out in JavaScript is also very simple. You could use getAttribute() with their full HTML name to read them, but the standard defines a simpler way: a DOMStringMap you can read out via a dataset property.

Or the alternative, and slightly longer format using getAttribute().

update_person(this.value,this.getAttribute('data-fieldname'), this.getAttribute('data-key'),this.getAttribute('data-value'))
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.