TimK TimK - 2 months ago 13
jQuery Question

How to remove whitespace on jquery ui selectable before inserting to SQL table

I have a selectable that posts comma separated items to my SQL table but there is a lot of white space in between the commas. I went down the rabbit whole of traying to remove the spaces after the post to the table but decided the best fix is to just make sure the data posts cleanly to the SQL table in the first place. This is the variable being posted.

positionTags = Request.Form["hidPostag"];


This is how I am building the selectable

var db = Database.Open("mydb");
foreach (var item in db.Query("SELECT positiontagName FROM positiontag"))
{
var positiontag = item.positiontagName;
<ul class="selectable" id="selectable1">
<li class="ui-state-default" id="@positiontag">
@positiontag
</li>
</ul>
}


This is my hidden field which I use to store the selected values

<input type="hidden" name="hidPostag" id="hidPostag">


And finally this is the script that grabs the selected items with class ui-selected and writes them to the hidden field (where I suspect the issue is).

<script>
function getSelected() {
var selectedVals = [];
$('#selectable1 .ui-selected').each(function(k,v) {
selectedVals.push($(v).text());
});
document.getElementById("hidPostag").value = $.trim(selectedVals);
}
$('#getVals').click(function() {
getSelected();
});
</script>


In the script above I thought maybe the issue was that I was grabbing the ul which scoops in the li bits and the extra space so I tried to modify the selector to grab child elements only but it doesn't work at all with the following

$('#selectable1 ul.ui-selected > li').each(func.....


My sql inserts look like this

"Community College Expert , Physician Researcher and Clinician , Physician Researcher and Clinician"

Answer

$.trim() will only remove leading and trailing whitespace, so you'll have to do it for each item:

<script>
    function getSelected() {
        var selectedVals = [];
        $('#selectable1 .ui-selected').each(function(k,v) {
            selectedVals.push( $.trim( $(v).text()) );
        });
        document.getElementById("hidPostag").value = selectedVals;
    }
    $('#getVals').click(function() {
        getSelected();
    });
</script>

P.S.: You really should sanitize the data before inserting it into the database.

Comments