I’m just designing a web project which is about cooking recipes. When a user wants to add an ingredient to her recipe, she needs to add ingredients one by one using a dynamic list which I’m trying to code with jquery(AJAX).
My problem is, if user enters one word ingredient, it works great. But if user enters more than one word ingredient, weird things happening. (yes I even cannot explain what’s exactly going on. newbie javascript coder spotted.) Here is the codeline:
$("#inglist").append("<br id="+i+"><div id="+i+">"+$("#ingredient").val()+" <a href='#' onClick=removeIngr('"+ingr+"',"+i+")>Remove</a></div>");
This codeline suppose to add <br> and <div> tags, index number of the ingredient as id attribute, name of the ingredient (from an input line with id =’ingredient’) tag with an onClick event which calls removeIngr(ingredientName,index) method
If user enters “Tomato”, it produces this:
<div xmlns="http://www.w3.org/1999/xhtml" id="0">Tomato <a onclick="removeIngr('Tomato',0)" href="#"> Remove</a></div>
It looks and works cool. (Except I’ve just realized that, href attribute is moving to the end somehow.)
If user enters “Black Pepper”, it produces this:
<div xmlns="http://www.w3.org/1999/xhtml" id="3">Black Pepper <a pepper',3)="" onclick="removeIngr('Black" href="#">Remove</a></div>
As you see, all mixed up with each other. So what’s happening? Any help?
Thanks for your time.
You need quotes around your
onClickattribute, otherwise a space marks the end of it. Use\"to have quotes inside quotes.I’ve changed the
idattributes todata-id, because you shouldn’t have multiple elements with the sameid, nor shouldids start with a number.