I have an issue with my HTML datalist and the javascript to manage it... My purpose is to change the values of a HTML "select" from a datalist.
Here is my datalist :
<input class="verylarge" id="choix_client" name="choix_client" type="text" list="client" autofocus="" required spellcheck="false" onChange="getSite(this.value);" title="Les simples quotes sont remplacées par des espaces"><br>
<datalist id="client">
<?php
foreach ($tabCLIENTS as $value) {
list($id,$nom) = explode(";",$value);
$nom = str_replace("'", " ", $nom);
?>
<option data-value="<?=$id?>" value="<?=$nom?>">
<?php } ?>
</datalist>
<input type="hidden" name="idClient" id="idClient">
With the id number ($id), i want to change de values of the next Select option menu. My Javascript is activated on datalist change :
function getSite() {
var NomClient = document.getElementById("choix_client").value;
var idClient = document.querySelector("#client option[value='" + NomClient + "']").dataset.value;
document.getElementById('idClient').value = idClient;
$.ajax({
type: "POST",
url: "getSite.php",
data: 'client=' + idClient,
success: function(data) {
$("#choix_site").html(data);
}
});
}
In my datalist, I have some Client names with single quote... (for examble : "L'EQUIPE"). It's a problem when i try to get the dataset value :
document.querySelector("#client option[value='"+NomClient+"']").dataset.value;
It's impossible to protect de single quote with \ because the querySelector won't find the good option...
If someone as an idea to help me...
You can use CSS.escape() for this:
var NomClient = "L'ÉQUIPE";
var idClient = document.querySelector("#client option[value='" + CSS.escape(NomClient) + "']").dataset.value;
console.log(idClient);
<div id="client">
<select>
<option value="L'ÉQUIPE" data-value="yes">L'ÉQUIPE</option>
<option value="Libération">Libération</option>
<option value="Marianne">Marianne</option>
</select>
</div>