0

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.

4
  • "passing those parameters is creating a problem" and what is the problem exactly? Commented Nov 14, 2013 at 6:49
  • Use encodeURIComponent to encode the string and pass that to setlocation. Commented Nov 14, 2013 at 6:52
  • onclick="javascript:setlocation('{{state_obj.name}}')" Commented Nov 14, 2013 at 6:53
  • Note that the javascript: label is completely unnecessary there. Commented Nov 14, 2013 at 6:54

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

If you explain the downvote, I can improve my answer. Without an explanation, there is little I can do. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.