Escape HTML "value" attribute for a select menu - javascript

I have a select menu and I dynamically insert some values from a database:
markup += '<option value=' + option["value"] + '>' + option["alias"] + '</option>';
some values, however, contain double quotes. to try and get around this I tried:
markup += '<option value=' + JSON.stringify(option["value"]) + '>' + option["alias"] + '</option>';
For examples sake lets assume the value is 6"Rocket (this is actually my problem child)
When I try and read the value using Jquery .val() I always get 6.
What to do SO?

The simplest way of avoiding this problem is to DOM-sript rather than insert strings of HTML.
var sel = $('#some_dropdown');
...
$('<option />', {value: option.value, text: option.alias}).appendTo(sel);

Related

Why jQuery append() removes words after first blank space in string

I'm trying to dynamically generate a form after an ajax request. Below is the relevant code sample :
for (var i in response.responseJSON[0].fields) {
var field = response.responseJSON[0].fields[i];
$('#properties_form').append('<label for=' + i + '>' + i + '</label>' +
'<input id=' + i + ' value=' + field + '>');
}
My problem is that, when var i and var field are strings with blank spaces like "Hello world", my label and inputs will be like <label id="Hello" world=""> and <input value="Hello" world="">. However, the label text will be displayed correctly i.e. <label>Hello world</label>.
I've no idea what kind of sorcery that is, but I'll be very grateful for any help. Thanks in advance.
There's a much more robust way of doing this.
for (var i in response.responseJSON[0].fields) {
var field = response.responseJSON[0].fields[i];
$('#properties_form')
.append($('<label>').attr('for', i).text(i))
.append($('<input>').attr('id', i).val(field));
}
You won't have to worry about the content of the strings as jQuery and the DOM will handle it for you. Not to mention this is much easier to read.
Use " to enclose the attributes.
$('#properties_form')
.append('<label for="' + i + '">' + i + '</label>' +
'<input id="' + i + '" value="' + field + '">');
EDIT
This will break for the cases where the value for i is something like This "works". Best solution is to append as jQuery or JS objects rather than using HTML string just like Daniel's answer.
Following snippet contains the correct fix for this. Updated based on the answer from Daniel.
i = 'Hello "World"';
field = 'Hello "World"s';
$('#properties_form')
.append($('<label>').attr('for', i).text(i))
.append($('<input>').attr('id', i).val(field));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="properties_form"></div>

how to preserve space in HTML select option list<option value='hi this'>hi</option> [duplicate]

This question already has answers here:
How to set HTML value attribute (with spaces)
(6 answers)
Closed 11 months ago.
I have one select control. I try to update this control with jquery but the value after space omitting.
if (brandObj != "") {
brandObj = eval("(" + brandObj + ")");
$.each(brandObj, function(i, item) {
$("#<%=listBrand.ClientID%>").append( "<option value="+ item.Brand + ">" + item.Brand + "</option>");
});
}
The data which I get from server
But after it render as HTML select , it omit the word after space.whole value is there but once I get the value , it have only half(the value which in double quote). I tried to add but it is showing as it is. it is not rendering as space. please give your suggession.
You should wrap value of attribute value in quote(Quote It). If you do not wrap them in quote then value after space will be considered as attribute itself:
$("#<%=listBrand.ClientID%>").append("<option value='"+ item.Brand + "'>" + item.Brand + "</option>");
As I've mentioned in the comment, the problem can be solved by wrapping the value attribute value in the quotes.
.append("<option value='" + item.Brand + "'>" ...
^ ^
However, I'll recommend the use of Option constructor to create new <option> element dynamically.
Demo:
var arr = [{
text: 'Hello World!',
value: 'hello World'
}, {
text: 'Bye World!',
value: 'bye World'
}];
var select = document.getElementById('mySelect');
// Iterate over array
arr.forEach(function (obj, i) {
// Create new <option> with dynamic value and text
// Add the <option> to the <select>
select.appendChild(new Option(obj.text, obj.value));
});
<select id="mySelect"></select>
Thanks to : Milind Anantwar, I adapted his idea and solved a problem that’s been nagging for about 5 days.
<?php
foreach($rows as $row):
$outputstr="$row[Mfrname]";
$goodstr="<option value='".$outputstr."''>".$outputstr."</option>";
echo $goodstr;
endforeach;
?>

String Interpolation not working as expected for a string with more than one word

The code removes all options from a select box and updates them. The issue is that the value for each option is not updating correctly.
What is happening is the value for each option is updated with just the first word of a string, which is incorrect. I want the value to be updated with the entire string.
Code:
service_selection.children().remove();
$.each(data, function(index,value){
service_selection.append("<option value=" + value.description + ">" + value.description + "</option>");
});
Example: Let's say value.description = "Hello World Foo Bar".
The html shows it only assigns "Hello" to the option's value instead of "Hello World Foo Bar" to the option's value.
The current html after being updated looks like this:
<option value="Hello" World Foo Bar>Hello World Foo Bar</option>
You forgot to add " for the actual html value (it has to be surrounded by "), therfor it will cut after the first white space.
The correct code would look like this:
service_selection.children().remove();
$.each(data, function(index,value){
service_selection.append("<option value='" + value.description + "'>" + value.description + "</option>");
});
(notice the single ' I added after value= and before >)
You have issues with quotes in your current code.
I'd personally do something like:
var opts = "";
$.each(data, function(index, value) {
opts += '<option value="' + value.description + '">' + value.description + '</option>';
});
service_selection.html(opts);

access dropdown value generating on runtime

I am using C# asp.net. On button click I am generating a dropdown by using Javascript.
<scripttype="text/javascript">
var counter = 0;
function AddFileUpload() {
//debugger;
var div = document.createElement('DIV');
div.innerHTML = '<input id="file' + counter + '" name = "file' + counter + '"Type="file"/>' +
'<select id="Droplist' + counter + '" name="droplst"/>' +
'<option value="SCR">Student Count request</option>' +
'<option value="DRO">Documents recieved from others</option>' +
'<option value="TE">total estimates</option>' +
'<option value="PRE">Presentation</option>' +
'<option value="PRI">Pricing</option>' +
'<option value="Quest">Questions to student</option>' +
'<option value="RelvExp">RelevantExperience-Case Studies</option>' +
'<option value="ResReq">Resource requests</option>' +
'<option value="SSP">Student submitted paper</option>' +
'<option value="WIP">WIP</option>' ;
document.getElementById("FileUploadContainer").appendChild(div);
counter++;
}
</script>
I am accessing the dropdown values in page behind like this
string val = Request.Form["droplst"];
It is working fine,but what I am receiving is option value. Like "SCR" when "Student Count request" is selected. is there any way to access the selected value like "Student Count request" instead of getting the option value?
Please let me know if the question is vague and further clarification is required.
Are the values of the options necessary? The easiest change to make would be to remove the values. E.g:
<option>Student Count request</option>
If you do require the values, then it's a bit more tricky: you have added the dynamic control to the page using JavaScript, so the code behind won't be able to find it easily. You could add an ASP HiddenField control to the page, then when a dropdown is selected, populate that hiddenfield with the text value using JQuery/JavaScript. Then in the code behind you can access the value of the hidden field (which will be the dropdown selected text).
Do you understand? You can read further here which is a duplicate of this question and has already been answered: How to access dropdown text (not value) using Request.Form()?

Javascript selected item value not pulling correctly

I'm doing a select box with a list of items(dynamically created from an XML created by a webservice), and I'm unable to pull the selected value correctly. Here is what is happening.
What I'm sending:
onchange="changeFunction(this.options[this.selectedIndex].value)"
What I'm receiving:
function (a){if(f.isFunction(a))return this.each(function(b){var c=f(this);c.text(a.call(this,b,c.text()))});if(typeof a!=
I'm the only thing I'm using is some self built functions and jQuery.
Any help would be superb.
Edit: here is the change function. All it is intended to do is build a form populated with values for given selected item.
function changeFunction(selection) {
console.log(selection);
$('#right').empty();
var addNewFields = 'these will be the fields';
$('#right').append(addNewFields);
}
Here is the select in question:
<select class="userSelection" id="userSelection" size="10" style="width:150px;" onchange="changeFunction(this.options[this.selectedIndex].value)"></select>
This is literally all the code in the html part of it. It's being populated via ajax, and there are 2 divs, one for left, containing the select, and one for right, containing the content for the user.
Just for giggles, here is the code creating the options:
var optionTag = '<option value="' + $(this).find('optionID').text + '" >' + $(this).find('optionName').text() + '</option>';
$('#userSelection').append(optionTag);
var optionTag = '<option value="' + $(this).find('optionID').text + '" >' + $(this).find('optionName').text() + '</option>';
should be:
var optionTag = '<option value="' + $(this).find('optionID').text() + '" >' + $(this).find('optionName').text() + '</option>';
Notice that $(this).find('optionID').text should be $(this).find('optionID').text().
or even better, to avoid this soup:
var optionTag = $('<option/>', {
value: $(this).find('optionID').text(),
html: $(this).find('optionName').text()
});
When you set the event handler of a DOM object to a function it get passed an event object as it's argument.
selectBox.onchange = function(event) {
changeFn(this.options[this.selectedIndex].value);
};

Categories

Resources