Using custom data-attributes in html in onchange event

人走茶凉 提交于 2019-12-25 00:03:35

问题


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:


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'))


来源:https://stackoverflow.com/questions/32460568/using-custom-data-attributes-in-html-in-onchange-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!