Reputation: 8367
I'm creating options of a dropdown using jquery. User will enter the option text in the textbox keyvalue
and on keyup()
it will be added to <select>
.
Eg: If user enter string Size , an option will be added in the dropdown like
<option value="Size">Size</option>
HTML
<input type="text" id="keyvalue" onkeyup="addvaluetoselect()">
<select id="key"></select>
jQuery
var keyvalue = $('#keyvalue').val();
if ($("#key option[value='"+keyvalue +"']").length == 0)
$('#key').append('<option value="'+keyvalue +'">'+keyvalue +'</option>');
If user types a value including double or single quotes, it should be added to the option. But currently it is not working. I tried by adding
var keyvalue = keyvalue .replace(/(['"])/g, "\\$1");
to escape the quotes. But when I try to enter a option Size's , the option is getting created like Size/'s instead of Size's.
Can anyone help me to fix this. Thanks in advance.
Upvotes: 1
Views: 98
Reputation: 66396
Don't append this as raw string, build it properly instead:
var keyvalue = $('#keyvalue').val();
var exists = $('#key option').map(function() {
return $(this).val();
}).toArray().indexOf(keyvalue) >= 0;
if (!exists) {
var newOption = $("<option></option>");
newOption.attr("value", keyvalue);
newOption.text(keyvalue);
$('#key').append(newOption);
}
As you can see, the check to see if the value already exists was also wrong, fixed that by iterating the existing options and checking their value against the value typed by the user.
Upvotes: 3