0

Given I have object with a name property which is, say: 'Woodcutters Hut'. If I try to assign this to a button attribute:

$('#possible_constructions').append("<button name=" + object.name + ">" + object.name + "</button>")

The buttons writing is correctly the entire 'Woodcutters Hut' however the name attribute only consists of the first word 'Woodcutters'. and hut is displayed outside like so:

<button name="Woodcutters" hut>Woodcutters Hut</button>

Anyway to ensure the attribute is assigned properly?

4
  • replace space with a underscore name="Woodcutters_hut" using $('#possible_constructions').append("<button name=" + object.name.replace(/ /g, "_")+ ">" + object.name + "</button>") Commented Oct 25, 2014 at 18:40
  • @Sharky I see this would work, but then the buttons text has the underscore along with it - anyway to avoid that? Commented Oct 25, 2014 at 18:41
  • @user3317592 Why do the name and text need to be the same? Why does the button need a name in the first place? Commented Oct 25, 2014 at 18:41
  • refresh page to see my updated comment Commented Oct 25, 2014 at 18:42

2 Answers 2

1

Let jQuery handle the name value for you. Don't build a string.

$("<button></button>", { 
    name: object.name, 
    text: object.name
}).appendTo("#possible_constructions");

Though it's important to note that "Woodcutters Hut" isn't an appropriate name. You shouldn't be using spaces in your name values. You should consider instead consider reshaping that value into something more appropriate - perhaps by replacing non-alphanumeric characters with underscores:

object.name.replace(/[^\w]/g, "_");

This would convert "Woodcutters Hut" into "Woodcutters_Hut".

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

Comments

0

try this , if it works

  $('#possible_constructions').append("<button name='" + object.name + "'>" + object.name + "</button>")

3 Comments

This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post.
@Volker E.: But it does provide an answer! Look for the single ticks in the <button name=''>.
actually i recommend the working solution, i my point was to solve prolem not getting votes and repu so i said "try this" if this doesnt works we will try other things,but i was sure about that so didnt commented instead posted it as an answer @volker

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.