Guide: Generating a dynamic textbox on click event without needing to reload the page

I need assistance with the following form:-

    <form action="">
    <table border="0">
        <td colspan="2" class="instruction">Please select an option to search.</td>
    </table>
      <table>
        <tr>
          <td><label>
            <input onClick="generatenew();" type="radio" name="search_option" value="code" id="search_option_0">
            Customer Code</label></td>
          <td><label>
            <input type="radio" name="search_option" value="company" id="search_option_1">
            Customer Company</label></td>
          <td><label>
            <input type="radio" name="search_option" value="name" id="search_option_2">
            Customer Name</label></td>
          <td><label>
            <input type="radio" name="search_option" value="email" id="search_option_3">
            Customer Email</label></td>
        </tr>
      </table>
      <input class="Button" name="search_submit" type="submit" value="Search">
    </form>

Following the last </table>, I am looking to add a text box that appears dynamically based on the selected radio button. This should happen without refreshing the page.

Answer №1

Creating an input element using Javascript:

// Dynamically create and customize input element
var input = document.createElement("input");
input.type = 'text';
input.name = 'inputName';
input.value = 'some value';
input.size = 10;
input.maxLength = 10;
input.className = 'someClass';

// Insert the created input element before a specified button
var btn = document.getElementsByName('search_submit')[0]; 
btn.parentElement.insertBefore(input, btn);

Using jQuery to achieve the same result:

$('input[name="search_submit"]').before('<input type="text" name="inputName" size="10" maxlength="10" class="someClass" />');

To see this in action, check out the jsfiddle here.

If you're interested in generating only one click on the radios, visit this jsfiddle link.

Answer №2

When using vanilla JavaScript, you would need to generate an additional div element following the initial one and then update its innerHTML property with the desired HTML content of the input element.

On the other hand, jQuery provides convenient functions such as .after or .append that perform equivalent actions in a more streamlined manner.

Answer №3

For enhancing your skills, I suggest exploring jQuery (http://jquery.com/). In addition, you may find this article helpful in gaining a better understanding of the issue:

Answer №4

            <html>
            <body>
            <table border=3>
            <tr>
            <td>USERNAME</td>
            <td><input type="radio" name="radGroup" id="rad1" onchange="showElement('1')">
            DEFAULT USERNAME
            <input type="radio" name="radGroup" id="rad1" onchange="showElement('2')">
            NEW UNAME</td></tr>
            <tr><td></td><td>
            <span id="elementNum1" style="display:none;visibility:hidden;">
            <input type="text" id="txt1" value="abc123" /> your default 
            </span>
            <span id="elementNum2" style="display:none;visibility:hidden;">
            <input type="text" id="txt2" value="" />confirm
            </span>
            </td>
            </tr>
            <script type="text/javascript">
            function showElement(iShow) 
            {       
            var oPageInfo;
            var bContinue=true;
            var iCounter=1;
            while (bContinue) 
            {
                try 
                {
                    oPageInfo=document.getElementById('elementNum'+iCounter);
                    oPageInfo.style.display='none';
                    oPageInfo.style.visibility='hidden';
                    iCounter++;
                } 
                catch(oErr) 
                {
                    bContinue=false;
                }
            }
            oPageInfo=document.getElementById('elementNum'+iShow);
            oPageInfo.style.visibility='visible';
            oPageInfo.style.display='inline';
            }
            </script>
            </table>
            </body>
            </html>

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

Allow undici fetch requests to use self-signed certificates

What is the correct way to execute fetch('https://localhost:8888') when dealing with a locally hosted HTTP server that uses a self-signed certificate (using fetch which is derived from undici)? ...

Tips for extracting the formData from an extensive form with a lot of fields

I'm currently experimenting with implementing a lengthy form in NextJS and recently discovered the server action feature. I am trying to figure out how to handle the form and mutate data using it. The example provided for handling server actions looks ...

How can I sort by the complete timestamp when using the Antd table for dates?

I have an item in my possession. const data: Item[] = [ { key: 1, name: 'John Brown', date: moment('10-10-2019').format('L'), address: 'New York No. 1 Lake Park', }, { ...

What might be preventing combineLatest from executing?

Currently, I am attempting to run a block of code utilizing the combineLatest function. Within my translation library, there exists an RXJS Observable that is returned. Imported as individual functions are combineLatest, map, and tap. combineLatest(this. ...

Sending images as a base64 string from a Titanium app to a Ruby on Rails web service

I am encountering an issue when trying to upload an image from an app that has been converted into a base64 string to a Ruby on Rails server. The app is developed using Titanium. However, after retrieving and decoding the image string back into an image, ...

Use VB.NET to dynamically update cell content in HTML

Can you assist me with updating cellContent in HTML using vb.net? The DataGrid view is on a website. Below is the inspected HTML: <div class="grid-controls"> <form method="post" class="vss-app-form grid-control-popover none" id="gridMorePopov ...

Ramjet: Unveiling the Magic of Making Elements Appear and Disappear

Currently, I am attempting to implement the code for ramjet from . However, I am facing an issue where element a does not disappear when transitioning into b. Additionally, I am encountering an error message "--Uncaught TypeError: Cannot read property &apo ...

Unable to minimize or hide the ace editor widget with Cypress

Today marks the beginning of my journey into posting on this platform, and I am eager to get it right. In my current project using Cypress for writing integration tests, I encountered a challenge while attempting to click on an Ace editor widget within a ...

How can I populate a form in Meteor with data from a MongoDB collection that was previously inserted?

Recently, I completed constructing a lengthy form field where users can enter a plethora of information. This form consists of various text and number fields, radio button sets, and checkbox groups. The data is successfully saved in a Mongo collection with ...

Spin an object around the global axis using the tween.js library

I'm trying to achieve a gradual rotation of a cube on the world axis using tween. Initially, I was able to rotate the cube around the world axis without tweening with the following code: rotateAroundWorldAxis(cube[1], new THREE.Vector3(0,1,0),degreeT ...

How to Call a Nested Object in JavaScript Dynamically?

var myObj = { bar_foo : "test", bar : { foo : "hi there"; }, foo : { bar : { foo: "and here we go!" } } } How can we achieve the following: var arr = [["bar", "foo"], ...

Verify the presence of a cookie before initiating a geo-redirection process

Here is a functional geo-redirect code snippet: <script async src="https://get.geojs.io/v1/ip/geo.js"></script> <script> function checkCountry() { $.ajax({ type: 'get', url: 'https://get.geojs ...

Clear Input Field upon Selection in JQuery Autocomplete

I've been experimenting with the Azure Maps API to add autosuggestions for addresses in an input field. https://github.com/Azure-Samples/AzureMapsCodeSamples/blob/master/AzureMapsCodeSamples/REST%20Services/Fill%20Address%20Form%20with%20Autosuggest. ...

Scatter plot showcasing repeated values along the x-axis

When creating a scatter chart using an ajax call, I encountered a situation where some values on the x-axis were duplicated while the values on the y-axis were different. For example: { "cols": [ {"id":"","label":"Sold Year ...

React components are graced with a clear icon that is visible on every element

I'm attempting to show a remove icon on a grid display when the user hovers over it with their mouse. this.state = { action: [], } <div> {this.state.action.map((value, index) => { return ( <div key={index} onMouseEnte ...

The information being sent from Angular is not being successfully transmitted to the XAM

Here is my Angular service post method: getUserDetails(username , password) { alert(password); return this.http.post<myData>("http://localhost/test/api/auth.php", { username, password }); } This is the structure of my PHP file: <?php ...

Displaying variables in JavaScript HTML

<script type ="text/javascript"> var current = 0; </script> <h3 style={{marginTop: '10', textAlign: 'center'}}><b>Current Status: <script type="text/javascript">document.write(cur ...

Contrasting bracket notation property access with Pick utility in TypeScript

I have a layout similar to this export type CameraProps = Omit<React.HTMLProps<HTMLVideoElement>, "ref"> & { audio?: boolean; audioConstraints?: MediaStreamConstraints["audio"]; mirrored?: boolean; screenshotFormat?: "i ...

Why does everything seem to move in sync with the table's scrolling?

I recently had an issue resolved that fixed most of my concerns: I needed to make three separate edits, and now when I reintroduce the other two edits, they are included within the table section and scroll along with the table instead of being stuck beneat ...

The HTML code as content

While working on an AJAX project, I ran into this issue: http://jsbin.com/iriquf/1 The data variable contains a simple HTML string. After making the AJAX call, I noticed that the returned string sometimes includes extra whitespaces. I attempted to locat ...