Search code examples
jqueryjsononselect

json onselect show/hide multi id div element


I have a table like this

id - type   - contact          - function
---------------------------------------------------
10 - phone  - 123/456789       - edit(button)
21 - mail   - [email protected] - edit(button)
58 - phone  - 456/789000       - edit(button)

On EDIT button click start a modal frame that have a code like this

<div class="col-lg-6">
 <label>type</label>
 <select name="contact_type" class="form-control" id="tipo_contatto_<?php echo $id; ?>">
  <option value="phone">phone</option>
  <option value="Mail">Mail</option>
 </select>
</div>

<div class="col-lg-6" id="contatto_<?php echo $id; ?>">
 <label>Contact</label>
 <input type="text" class="form-control" name="contact" value="">
</div>

<div class="col-lg-2" id="prefisso_<?php echo $id; ?>">
 <label>Prefix</label>
 <input type="text" class="form-control" name="prefix" value="">
</div>

<div class="col-lg-4" id="numero_<?php echo $id; ?>">
 <label>Number</label>
 <input type="text" class="form-control" name="number" value="">
</div>

Then I want that on phone select show div with prefix and number, instead contact...

This solution work with 1 id, but with dynamic multi id?

$('#contact').hide();
$('#contact_type').change(function(){
 if ( $('#contact_type').val() == 'Phone') {
   $('#number').show(); 
   $('#prefix').show(); 
   $('#contact').hide(); 
 } else {
   $('#number').hide(); 
   $('#prefix').hide(); 
   $('#contact').show();               
 } 
});

Solution

  • You could consider selecting the elements based on some other attribute using jQuery as opposed to using the id attribute as seen below :

    // Whenever a contact type element is changed
    $('[name="contact_type"]').change(function(){
       // Get the ID value for this row (appended to each element) by removing
       // all non-digits from the ID
       var id = $(this).attr('id').replace(/\D/g, '');
       // If it is phone, do something
       if ($(this).val() == 'phone') {
            $('#numero_' + id).show(); 
            $('#prefisso_' + id).show(); 
            $('#contatto_' + id).hide(); 
       } else {
            $('#numero_' + id).hide(); 
            $('#prefisso_' + id).hide(); 
            $('#contatto_' + id).show();               
       } 
    });
    

    Example

    You can see a working example of this here and demonstrated below :

    enter image description here