Nishant123 Nishant123 - 4 months ago 7
jQuery Question

How to select unquoted html attribute values?

I have a multiple

select
element which I am appending dynamically to a
form

from a hidden field. I have escaped the spaces in the element

This is my hidden field

<input type="hidden" id="field1" name="field1" value="<select id=multipleselectid1 name=multipleselectid1 multiple><option value=All&nbsp;Balance&nbsp;Types>All Balance Types</option><option value=010>010 - Opening Ledger Balance</option><option value=011>011 - Average Opening Ledger MTD</option></select>" />


I want to select the first value by default i.e
value="All&nbsp;Balance&nbsp;Types"


This is my code to select the first value

var elevalue='All Balance Types';// -------> This doesn't work
var arr1 = elevalue.trim().split('\,');
$('#multipleselectid1').val(arr1);


But this value is not getting selected

I also implemented a test code to check whether other values are getting selected or not. So I tried this code

var elementvalue='010,011'; //-----------> This works
var arr = elementvalue.trim().split('\,');
$('#multipleselectid1').val(arr);


This snippet is working

Why is only the first value not getting selected?

This is the fiddle to above example

Answer

Remove &nbsp; from value in selectbox and add single quote in value:

$(document).ready(function(){
   $('#myform').append($('#field1').val());
   var elementvalue='All Balance Types'; //-----------> This works
   var arr = elementvalue.trim().split('\,');
   $('#multipleselectid1').val(arr);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="hidden" id="field1" name="field1" value="<select id=multipleselectid1 name=multipleselectid1 multiple><option value='All Balance Types'>All Balance Types</option><option value=010>010 - Opening Ledger Balance</option><option value=011>011 - Average Opening Ledger MTD</option></select>" />

<form id="myform">

</form>