How can I change the type of the input box with the value in the select box?


it's .KJ

 
$(function() { 
    var index = 1; 
    $("#addcon").on("click", function() {  
        num = index + 1;
        $("table.contact").append(`
            <tr>
                <td class='label'><label class='required'>Contact ${num}</label></td>
                <td>:</td>
                <td><select name=contact[${index}][type] class='contact' required>
                    <option style='display: none;' value='' selected>Select Type</option>
                    <option>Mobile</option>
                    <option>Landline</option>
                    <option>Email</option>
                    <option>Other</option>
                </select></td>
                <td><input type='text' name=contact[${index}][way] maxlength='300' class='way' required></td>
            </tr>
        `);
        index++;
    }); 
    
    $("#remcon").on("click", function() {  
        if(index - 1 >= 1) {
            $("table.contact tr").last().remove();
            index--;
        }
        else {  
            alert("One is must!");
        }
    });  
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="contact">
    <tr class="legend">
        <td colspan="6">CONTACT DETAILS</td>
    </tr>
    <tr>
        <td class="label"><label class="required">Contact 1</label></td>
        <td>:</td>
        <td><select name="contact[0][type]" required class="contact">
            <option style="display: none;" value="" selected>Select Type</option>
            <option>Mobile</option>
            <option>Landline</option>
            <option>Email</option>
            <option>Other</option>
        </select></td>
        <td><input type="text" name="contact[0][way]" required class="way"></td>
        <td style="text-align:left;"><a id="addcon" class="click">+</a></td>
        <td><a id="remcon" class="click">-</a></td>
    </tr>
</table>

Above is my contact form. Users can enter any number of contacts by clicking the "+" link, and delete contacts by clicking the "-" link. But in order to validate the data, I need to change the "type" of the input field based on the selection in the corresponding select box (combo box). Is there any way to do this using JQuery?

For example: if I select email in the select box, the type of the input field corresponding to this select box should be changed to email type.

Garson Luhage

To meet your requirements, the idea is that when a new row is created, you need to attach a change event listener to your <select>element, and when the user selects an option, the event callback will <input>use jQuery's attr ( on the element change property) method.

You also need to create some kind of mapping between option values ​​and actual HTML input types, you can find them here .

I've freely refactored your code to create some methods that help with code duplication. I also moved the + and - link buttons to the header of the table as there is no reason to attach them to the first contact.

The following is a working code snippet.

// mapping object from <select> values to input types
const selectTypesMapping = {
    Mobile: 'number',
    Landline: 'password',
    Email: 'email'
};
// gets a label cell
const getLabelCell = (index) => (`
    <td class="label">
        <label class="required">Contact ${index}</label>
    </td>
`);
// gets a colon cell
const getColonCell = () => (`<td>:</td>`);
// gets a select cell with a configured ID
const getSelectCell = (index) => (`
    <td>
        <select id="select-${index}" name="contact[index][type]"
                class="contact" required>
            <option style="display: none;" value="" selected>Select Type</option>
            <option>Mobile</option>
            <option>Landline</option>
            <option>Email</option>
            <option>Other</option>
        </select>
    </td>
`);
// gets an input cell with a configured ID
const getInputCell = (index) => (`
    <td>
        <input id="input-${index}" type="text" name="contact[index][way]" 
               maxlength="300" class="way" required />
    </td>
`);
// appends a row to a jQuery table and adds the change event to the select
const appendRow = (jQueryTable, index) => {
    jQueryTable.append(`
        <tr>
            ${getLabelCell(index + 1)}
            ${getColonCell()}
            ${getSelectCell(index)}
            ${getInputCell(index)}
        </tr>
    `);
    $(`#select-${index}`).change((event) => {
        $(`#input-${index}`).attr('type', selectTypesMapping[event.target.value]);
    });
};

$(function() {
    // manually append 1st row
    appendRow($('table.contact'), 0);
    let index = 1;
    $('#addcon').on('click', function() {
        // append on click and increment index
        appendRow($('table.contact'), index++);
    });
    $('#remcon').on('click', function() {
        if (index > 1) {
            $('table.contact tr').last().remove();
            index--;
        }
        else {
            alert('At least one contact is required!');
        }
    });
});
.click {
    cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="contact">
    <tr class="legend">
        <td colspan="4">CONTACT DETAILS</td>
        <td style="text-align:left;"><a id="addcon" class="click">+</a></td>
        <td><a id="remcon" title="Add" class="click">-</a></td>
    </tr>
</table>

Related


how can i get the value of the input box

Fremont Nesua <td class="stockQuantity"> <input class="form-control" id="Cart1" name="qty_req" required="required" type="text" value=""><br> <button type="button" onclick="appendCart(event,4,4,'Bottles',444,4)" class="btn btn-primary"> Add To Cart

How can I change the tab label when the input box changes?

annamull654 Say I have an input box and a label, so when I type on the input box, the label changes automatically as I type. example: //the result 4 is dynamically put in the label as a result of input value. <label class="result">4</label> //this is the inpu

AngularJS - Can't change value of input box

Jebaton The code below uses Angular to change the input value from 100 to 200. When using the controller to change the value of the input box, I get a TypeError. <div ng-controller="FooController" ...> <input ng-model="foo.price" type="text" name="price"

AngularJS - Can't change value of input box

Jebaton The code below uses Angular to change the input value from 100 to 200. When using the controller to change the value of the input box, I get a TypeError. <div ng-controller="FooController" ...> <input ng-model="foo.price" type="text" name="price"

AngularJS - Can't change value of input box

Jebaton The code below uses Angular to change the input value from 100 to 200. When using the controller to change the value of the input box, I get a TypeError. <div ng-controller="FooController" ...> <input ng-model="foo.price" type="text" name="price"

How can i get text not value in select box

Yuhan $('[name="campaign_template"]').on('click', function () { console.log($(this).val()); }) <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <label class="checkbox" for="id_campaign_template_1"> <i

How can i get text not value in select box

Yuhan $('[name="campaign_template"]').on('click', function () { console.log($(this).val()); }) <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <label class="checkbox" for="id_campaign_template_1"> <i

How can i get text not value in select box

Yuhan $('[name="campaign_template"]').on('click', function () { console.log($(this).val()); }) <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <label class="checkbox" for="id_campaign_template_1"> <i