I am trying to select a input value from the selected list.Input value (stationerytype) containing spaces or braket are not getting selected,What is wrong with my code
For example stationery type CELLOTAPE(BROWN) is not getting selected whereas other value are getting selected.
function random() {
const input = document.querySelector('[name="stationerytype[]"]');
input.value = ""
var a = document.getElementById('purpose').value;
if (a === "Meeting") {
var datalist = "datalist1";
} else if (a === "Departmental") {
var datalist = "datalist2";
}
const options = Array.from(document.getElementById(datalist).options).map(option => option.value);
input.setAttribute("list", datalist);
input.setAttribute("pattern", options.join('|'));
}
function ondataListSelect() {
const input = document.getElementById('stationerytype');
if (!input.validity.valid) {
input.value = '';
}
}
<select type="text" name="purpose" id="purpose" class="form-control" onchange="random()" required >
<option></option>
<option value="Meeting">Meeting</option>
<option value="Departmental">Departmental</option>
</select>
<td>
<input type="text"
name="stationerytype[]"
id="stationerytype"
class="form-control"
onchange="ondataListSelect()"
autocomplete="off"
required>
<datalist id="datalist1">
<option value=""></option>
<option value="MEETING PEN">MEETING PEN</option>
<option value="NOTEPAD">NOTEPAD</option>
<option value="PLASTIC FOLDER">PLASTIC FOLDER</option>
</datalist>
<datalist id="datalist2">
<option value=""></option>
<option value="A4 GREEN REAM">A4 GREEN REAM</option>
<option value="A4 WHITE REAM">A4 WHITE REAM</option>
<option value="CELLOTAPE(BROWN)">CELLOTAPE(BROWN)</option>
</datalist>
</td>
This is because ( and ) have special meaning in regex, but you concatenate all those values directly with a | in between. You need to properly escape any special characters in the values, that are not meant to have their special meaning.
Using the solution from the accepted answer to Is there a RegExp.escape function in JavaScript?, you can fix the issue by changing the following from
const options = Array.from(document.getElementById(datalist).options)
.map(option => option.value);
to
const options = Array.from(document.getElementById(datalist).options)
.map(option => option.value.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'));