Click here to Skip to main content
15,886,806 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi All,

<input class="input" name="location" type="text" placeholder="Search or choose..." id="txtLocation" autocomplete="off" value="">


Now I want to place button next to this text box.

I tried below code using Javascript but not working. When I inspect the textbox then button element is inside the text box but not visible on UI. I want this button to be visible next to text box.

function onload()
{
   //1st approach
   debugger;
   var ele = document.getElementById('txtLocation');
   var btn = document.createElement('BUTTON');
   btn.id= 'btnGo';
   btn.type='button'
   btn.onclick = 'setSelectedValue()';
   btn.innerHTML = 'Go';   
   ele.append(btn);
   
   //2nd approcah
  const btn1 =  document.createElement("BUTTON");
  btn1.innerHTML = "Go";
  ele.appendChild(btn1);
}

window.onload = onload;


What I have tried:

I tried createElement & appendChild / append but no luck.
Posted
Updated 29-Aug-22 21:27pm
Comments
[no name] 23-Aug-22 21:21pm    
Why can't you just "hide / show" an existing button instead of "adding on the fly"? You're probably running into (re)flow issues.

No puedes agregar otros elementos HTML dentro de un input pero usa esta forma para que se vean.
Google translate:
You can't add other HTML elements inside an input but use this way to show them.

JavaScript
var ele = document.getElementById('txtLocation');

var btn = document.createElement('button');
btn.id= 'btnGo';
btn.type='button'
btn.onclick = 'setSelectedValue()';
btn.innerHTML = 'Go';   
ele.parentElement.append(btn);

//2nd approcah
const btn1 =  document.createElement("button");
btn1.innerHTML = "Go";
ele.parentElement.appendChild(btn1);
 
Share this answer
 
v2
Comments
Richard Deeming 25-Aug-22 4:30am    
Este es un sitio en inglés. Por favor publique en inglés.
I found some issues in your mentioned JS code.

1) If you want to add any element after other HTML element then pick its parent and add as a child.
2) You created one function named "onload" and function can be called with "()". So, code should be "window.onload = onload();" instead of "window.onload = onload;"

function onload()
{
   var btn = document.createElement('button');
   btn.id= 'btnGo';
   btn.type='button'
   btn.onclick = 'setSelectedValue()';
   btn.innerHTML = 'Go';
   
   var body = document.getElementsByTagName("body")[0];
   body.appendChild(btn);
}

window.onload = onload();
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900