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

Ways to retrieve the neighboring element's value and modify it with the help of JavaScript or jQuery

I am encountering a problem with selecting an adjacent element and updating its value. My goal is to update the input value by clicking the minus or plus buttons. I have successfully retrieved all the buttons and iterated through them, adding onclick eve ...

What is the best way to ensure that a specific number of XHR callbacks have successfully completed before proceeding with further actions?

I have four requests that each have their own callback and can fire in any order. However, I need all the callbacks to finish successfully before executing mergeData. The issue with my current approach is that the initial parameter values do not refresh ...

What are some effective strategies for reducing excessive re-rendering of React components?

Here is how I am displaying a list of components on the screen: const MessagesContainer = ({ messages, categories, addHandler }) => { const options = categories.map(category => ( { value: category.name, label: category.name } )); ...

The effectiveness of Ajax when working with filenames

Currently, I am utilizing jQuery to trigger PHP files using the $.get method function retrieveDepartment(companyID) { $.get("ajax/fetchDepartment.php?sec=departments&company_id="+companyID, function(info){ $("#department_id").html(info); ...

Limiting the size of images within a specific section using CSS

When using CSS, I know how to resize images with the code snippets below: img {width:100%; height: auto; } img {max-width: 600px} While this method works effectively, it applies to every image on the page. What I really need is for some images to be ...

Understanding how to decode querystring parameters within a Django view

In the application I'm working on, there is a search form that utilizes a jQuery autocomplete plugin. This plugin processes the querystring and sends back the suggested item using encodeURI(q). For example, an item like Johnny's sports displays ...

What steps should I follow to incorporate channel logic into my WebSocket application, including setting up event bindings?

I'm currently tackling a major obstacle: my very own WebSocket server. The authentication and basic functionality are up and running smoothly, but I'm facing some challenges with the actual logic implementation. To address this, I've create ...

The dimensions of the HTML table do not adjust properly when new items are being appended using JavaScript

I utilized this HTML Code to generate a table: <div class="noten_tabelle"> <table id="grades_table" style="width:100%"> <tr> <th>Subject</th> <th>Oral</th&g ...

Responsive design element order rearrangement

My code example is as follows: <div class="info-container"> <span class="item1">item1</span> <a class="item2" href="#">item2</a> <a class="item3" href="#">item3</a> </div> I want to rearran ...

NodeJS Fork - React each instance a new line is detected from the child process

I am currently working on creating a NodeJS function (on Windows7) that listens to a subprocess and handles each newline sent through the subprocess in Node. The following example demonstrates this: var express = require('express'); var app = ex ...

"Learn how to add up elements in an array based on their unique IDs and generate a new array using

There is an array called data that looks like this: const data = [ {"id": "One", "number": 100}, {"id": "One", "number": 150}, {"id": "One", "number": 200}, ...

How to completely disable a DIV using Javascript/JQuery

Displayed below is a DIV containing various controls: <div id="buttonrow" class="buttonrow"> <div class="Add" title="Add"> <div class="AddButton"> <input id="images" name="images" title="Add Photos" ...

Find the name of the region in the user's query

I've implemented the weather-js npm module (weather-js) to retrieve weather information for a specific region. While everything is functioning correctly, I'm looking to customize it based on user input. The module currently only accepts region ...

Pass an array using AJAX to my Python function within a Django framework

I am attempting to pass an array to my python function within views.py, but I am encountering issues. It consistently crashes with a keyError because it does not recognize the data from js. Code: Python function in views.py: def cargar_datos_csv(request ...

Implementing a dynamic function with jQuery Tokenize's change event

I'm currently facing an issue with triggering the on change event on the select box from jQuery Tokenize. Below is the code snippet I am working with: <select id="tokenize" multiple="multiple" class="tokenize-sample"> <option value="1"&g ...

Unable to execute the new firebase on node server

I'm currently watching this google talk. However, I am facing an issue trying to create a firebase object. Following my package.json file, I initiated with: npm install firebase --save Then proceeded with the following steps: let Firebase = requir ...

Various web browsers may exhibit varying behaviors when processing extremely lengthy hyperlinks

I am curious to understand why browsers handle long URLs differently based on how they are accessed. Let me explain further: Within my application, there is a link to a specific view that may have a URL exceeding 2000 characters in length. I am aware that ...

retrieving attribute values from JSON objects using JavaScript

I am struggling to extract certain attribute values from a JSON output and use them as input for a function in JavaScript. I need assistance with this task! Below is the JSON data that I want to work with, specifically aiming to extract the filename valu ...

Display content exclusively within a modal specifically designed for mobile devices

I want to implement a feature where a button triggers a modal displaying content, but only on mobile devices. On desktop, the same content should be displayed in a div without the need for a button or modal. For instance: <div class="container&quo ...

Organize array by "categories" in Javascript and preserve the original sequence

There is a dataset presented below: [ { "name": "Item1", "section": "section1", "total": 3, }, { "name": "Item1", "section": "section2", "total": 4, }{ "name": "Item1", "section": "section3", "total": 7, }, { "name" ...