Anurag Sharma
Anurag Sharma

Reputation: 5039

pass string containing white spaces in javascript

I have a div class like this and want to call setlocation function which will set the value of the state in the text box

<div class="overview over_widt">
    <ul>
        <li class="auto" title="All India"></li>
        {% for state_obj in state_list %}
            <li name="state" class="auto" title="{{state_obj.name}}"><a href="#{{state_obj.id}}" onclick=javascript:setlocation("{{state_obj.name}}")> {{ state_obj.name }}</a></li>
         {% endfor %}
    </ul>

my java script function

function setlocation(name){
    //alert(name);
    $('#id_autocomplete').val(name);
    document.getElementById('city_state').style.display="none"
}

and my textbox

<input type="text" class="text2" name="location" id="id_autocomplete" placeholder="Enter Location" onfocus="show_div();" onkeyup="div_autocomplete()"/>

The problem is I have some states which have "whitespaces" in them and passing those parameters is creating a problem . I tried passing the object also like

onclick=javascript:setlocation("{{state_obj}}")

but this also doesnt work.

Upvotes: 0

Views: 1938

Answers (1)

Felix Kling
Felix Kling

Reputation: 816590

You have to put the HTML attribute value in quotation marks:

onclick="setlocation('{{state_obj.name}}')"

Otherwise values with whitespace will mess up your HTML. If you don't use quotation marks, then only the characters up to the next whitespace are considered to be part of the value. So if the generated HTML was

onclick=setlocation("foo bar")

Then you would have an attribute onclick with value setlocation("foo and a boolean attribute bar") (though this would probably be invalid, I don't think attribute names can contain " or )).

But really, instead of using inline event handlers, you could use event delegation or any other way of binding event handlers.

Upvotes: 4

Related Questions