Looking to display dropdown menus on a new line along with a text input field using jQuery?

  <script type="text/javascript">
  var arr = [{
  val: 1,
text: 'Option 1'
   }, {
     val: 2,
   text: 'Option 2'
      }];

   $(function () {
       $('a').click(function () {

    var sel = $('<select>').appendTo('body');
    var textbox = $('<input type="text" />');
    $('<br>').appendTo('body');

    $(arr).each(function () {
        sel.append($("<option>").attr('value', this.val).text(this.text));
    });
    return false;
  });

      });

       </script>

  <a href="">Add Select Box</a>

When the anchor tag is clicked in the code above, select boxes appear. If the anchor tag is clicked multiple times, each click will show a new select box on a new line with a text box alongside it. Any assistance on ensuring these elements display correctly would be greatly appreciated. Thank you in advance.

CSS for the code...

      a {display: block; background-color: #eee; border: 1px solid #aaa; color: #000; text-decoration: none; width: 200px; padding: 5px; font-family: arial; text-align: center;}

      </style>

Answer №1

 $(function () {
       $('button').on('click', function () {
           var container = $('<div/>');
           var selection = $('<select>');

           $(optionsArray).each(function () {
               selection.append($("<option>").attr('value', this.value).text(this.label));
           });

           container.append($("<input>"));
           container.append(selection);
           $("body").append(container);
           return false;
       });
  });

CodePen: http://codepen.io/username/pen/XyZ123/

Answer №2

Make sure to add CSS code to properly display the select element as a block:

select { display: block; }

To see an example, check out this jsfiddle: http://jsfiddle.net/6ve49/1/

UPDATE: If you also require a textbox in addition to the select element, please refer to Kevin's answer for a suitable solution :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The HTML table is not fully filled with data from the XML file

Trying to populate an HTML table using XML data retrieved from an AJAX call is proving to be a challenge for me. The main issue I am facing is the inability to fully populate the HTML table. Being new to AJAX, understanding how XML interpretation works an ...

What are the reasons for the dynamic exclusion of an element in Angular?

Can someone help me figure out why my data is not being added dynamically using ng-repeat? I have entered the "name" which should be added to the data, but it is not displaying in the UI. You can see the issue in this demo app.controller("studentcntr", ...

Is it possible to utilize CSS rules for a non-existent div within CSS?

Can this be achieved using CSS? If .div1 is not present, enforce the following rule: .div2{ property: value; } For example, <div class="div1"> ... </div> <div class="div2"> <!-- it exists, so no action needed --> </div& ...

Eliminate any blank spaces and unproductive searches by utilizing AJAX and CodeIgniter

I am having an issue where I receive results from the database using a jQuery Ajax function when I enter only spaces. However, if I enter a space and then remove it, all results are returned from the database. Can someone please help me fix this problem? H ...

Having trouble with the position function in JavaScript?

I'm working on creating a small game, but I've encountered some difficulties at the start. Every time I attempt to obtain the position of track or trackCont, it consistently returns x: 0, y: 0. The DIV doesn't move to the correct position w ...

How come my Bootstrap container columns are not remaining evenly divided into four parts?

Struggling to split a section of my project into 4 equal parts using the bootstrap col attribute. Unfortunately, every time I try, the last container ends up breaking and shifting below the other 3, creating an unsightly code layout. index.html <sec ...

When going through an array using jquery, only the final object is returned

I am diving into the world of jQuery and dealing with what seems to be a basic issue. <input type="text" name="text1" value=""></input> <input type="text" name="text2" value=""></input> <input type="text" name="text3" value=""&g ...

Using CSS absolute/relative positioning in a flyout menu: Utilizing specific parent properties (such as left, top, width, vertical/horizontal alignment) while disregarding others

I recently encountered a common issue in CSS involving flyout menus with sub-menus that are shown on hover. When attempting to position the sub-menu directly below the parent list item, I used position:relative; on the parent item and position:absolute;top ...

Exploring the HTMLUnknownElement using jQuery.find() and an XML file

Trying to load an XML document (specifically, an RSS feed) through an Ajax request to parse and incorporate information into my webpage. Surprisingly, the code functions properly in Firefox, Opera, Chrome, and Safari but encounters issues with IE7. Upon i ...

What is the best method to update numerous low-resolution image sources with higher resolution images once they have finished loading?

I'm currently developing a website that implements a strategy of loading low-resolution images first, and then swapping them for high-resolution versions once they are fully loaded. By doing this, we aim to speed up the initial loading time by display ...

What methods are available for parsing JSON data into an array using JavaScript?

I possess an item. [Object { id=8, question="وصلت المنافذ الجمركية في...طنة حتّى عام 1970م إلى ", choice1="20 منفذًا", more...}, Object { id=22, question="تأسست مطبعة مزون التي تع... الأ ...

Modifying the jquery cookie's value

As soon as a user lands on my site, a persistent cookie (x1st) is set with a unique value (such as 'hdflashfafafxx233ddd'). This particular cookie is utilized for tracking purposes. However, if the user chooses to opt out of tracking cookies, I ...

I am experiencing difficulty in successfully transmitting a variable from my jQuery code to my PHP code

I've been attempting to pass a variable from my jQuery code to my HTML/PHP code using AJAX and POST. However, I'm encountering an error message stating "Notice: Undefined index: testData in C:\xampp\htdocs\teszt\test1.php on l ...

What is the best way to zoom in on an image and make it move off the screen as I scroll through my webpage?

I am working on a website design where I would like to implement an image zoom effect as the user scrolls down. Additionally, I want the image to move to either the left or right side of the screen as it goes out of view when scrolling to the bottom. While ...

jQuery Files in Conflict

The issue I am facing involves the code below. The first function requires linked js and css, while the second one needs a jQuery and javascript file inherited from base.html. However, there seems to be a conflict in loading these files (possibly because o ...

Internal styles are effective, while external styles seem to be less efficient

For some reason, internal CSS is working fine, but external CSS just won't cooperate. I even tried using the code !important, but it's like it doesn't understand. I'm trying to incorporate a gallery into my website, but I've hit a ...

Does using .stopImmediatePropagation() in the click event of a menu item have any impact on analytical tools?

Scenario I've implemented a navigation menu that loads subpages into a div using AJAX. While everything seems to be working fine, I noticed a bug where if I navigate to a subpage, then return to the main page and revisit the same subpage, it gets loa ...

How to Disable a Button with JavaScript in a Vue.js Application Without Using jQuery

I'm currently in the process of transitioning old jQuery code to JavaScript for a Vue.js application. function DisableSubmit() { submitButton.prop('disabled', true); submitButton.attr('data-enabled-value', submitButton.val ...

Is it possible to have a button within a table that, when clicked, opens a card overlaying the entire table?

I'm having an issue with a table and card setup. When I click the button in the table, the card that appears only covers part of the table. I want it to cover the entire table area based on the content inside the card. How can I make this happen? I&a ...

Exploring GitHub's sleek popup: in search of CSS styling!

Exciting news from Github: they have introduced a new feature called maps. This feature is developed using Leaflet, and it has some unique custom CSS for the pop-up design: I'm eager to implement something similar on my site, but I'm having trou ...