1

I want to create Buttons in a loop, depending on a value it has to create x buttons, for the beginning I'm trying to get the creation of a Button via Javascript. th e button with the function has to be in one , but the button it creates has to be created in another .

How do I get this done?

My idea, shown below, does not work.

function createButton(context, func){
    var button = document.createElement("input");
    button.type = "button";
    button.value = "im a button";
    button.onclick = func;
    context.appendChild(button);
}
html,body { margin:0; padding: 0; }
#inputpanel {
  width: calc(40vw - 10px);
}
#selectpanel {
  width: calc(20vw - 10px);
}

#inputpanel,#selectpanel {
  display: inline-block;
  box-sizing: border-box;
  height: calc(100vh - 200px);
  margin: 0;
  padding: 0;
}
<div id="inputpanel">
  
 <button type="button" id="createBut" onclick="createButton(document.selectpanel, function(){
    alert('it works');})">create Button</button>
</div>

<div id="selectpanel">
adsadasdasd<br />
asfdsdfsdfgdf

</div>

Thanks Adrian

2
  • use document.createElement('button'); Commented Jul 12, 2017 at 11:52
  • document.selectpanel does not exist. Either pass a proper, existing element reference - or pass the element id as string only, so that you can then use getElementById inside your function to get the element. Commented Jul 12, 2017 at 11:54

2 Answers 2

2

Here is the code to create buttons:

function createButton(context, func) {
  var button = document.createElement("input");
  button.type = "button";
  button.value = "im a button";
  button.onclick = func;

  var selectPanel = document.getElementById('selectpanel');
  selectPanel.appendChild(button);
}
html,
body {
  margin: 0;
  padding: 0;
}

#inputpanel {
  width: calc(40vw - 10px);
}

#selectpanel {
  width: calc(20vw - 10px);
}

#inputpanel,
#selectpanel {
  display: inline-block;
  box-sizing: border-box;
  height: calc(100vh - 200px);
  margin: 0;
  padding: 0;
}
<div id="inputpanel">

  <button type="button" id="createBut" onclick="createButton(document.selectpanel, function(){
    alert('it works');})">create Button</button>
</div>

<div id="selectpanel">
</div>

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

Comments

0

I think the problem is located where you are declaring the button variable.

It should be:

var button = document.createElement('input');

Instead of:

var button = document.selectpanel.createElement('input');

1 Comment

yeah that was not intented, i fixed it.

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.