0

I have a form with various input boxes. I use jQuery on a click event to take the text in the input boxes and populate several select menus. This all works quite happily.

I noticed the problem when I used PHP to submit the form data to MySQL: the selected values in the select menus were included but if there was a space in the string then it only included text to the first space.

Tracking the problem back using an onchange event on the select menu and outputting it to the console.log shows it happens immediately, it is not lost in translation.

I use some pre-set select menus and they work fine, even if I add spaces.

Below some code examples, shortened:

HTML

<input type="text" name="head_loss1" id="head_loss1">
<select name="loss_depend1" id="loss_depend1">

JS/JQ

<script> 
$(document).ready(function() {
    $( "#collapse5" ).one("click", create_holoss_list);

        function create_holoss_list(){

        var lo1 = $('#head_loss1').val();

        $('#loss_depend1').append('<option value=""></option><option  value='+lo1+'>'+lo1+'</option><option value='+lo2+'>'+lo2+'</option><option value='+lo3+'>'+lo3+'</option><option value='+lo4+'>'+lo4+'</option><option value='+lo5+'>'+lo5+'</option><option value='+lo6+'>'+lo6+'</option><option value='+lo7+'>'+lo7+'</option><option value='+lo8+'>'+lo8+'</option><option value='+lo9+'>'+lo9+'</option><option value='+lo10+'>'+lo10+'</option>');

    };
});    
</script>       

JS (for output to console)

loss_depend1.addEventListener("change", myScript);


function myScript() {
    console.log(loss_depend1.value);
}

So if the text in the input box is: one two

The select menu will show one two as an option, but when I output the selected value it will be one

I am hoping I have done something stupid because I have been looking at it too long and I can't see where I should have " instead of ' or vice versa!

Thanks for any assistance

Blair

  • Could you recreate that in a JSFiddle, there's no reason the spaces wouldn't be transferred to the options – adeneo Oct 19 '16 at 22:10
  • 2
    I have no time to check everything you wrote right now, but quickly skimming the question. change: to: and same for lo2, lo3, lo4, lo5 till the end. I added the double quotes inbetween 'value' attribute (before the single quote) – tomJO Oct 19 '16 at 22:19
  • ^ @tomJO spotted your problem, you're missing quotes around the values, which is why they don't work with spaces – adeneo Oct 19 '16 at 22:21

1 Answers1

0

After taking a break I came back and noticed:

$('#loss_depend1').append('<option value=""></option><option  value='+lo1+'>'+lo1+'</option>

should be:

$('#loss_depend1').append('<option value=""></option><option  value="'+lo1+'">'+lo1+'</option>

"'+lo1+'"

It's the simple things...