Home > database >  Hide Div based on select box using data-type not ID/Class
Hide Div based on select box using data-type not ID/Class

Time:05-06

Is it possible to hide DIV based on the value of a select box (the select box doesn't have a unique ID or class). The only unique way I can see to possibly target it, is it has 'Data-type="location"'

<div data-type="location"><label>Location</label> <div><select><option value="0">Select location</option><option value="3">A Club</option><option value="4">B Club</option><option value="1">C Club</option><option value="6">Mobile Hire</option></select></div> </div>

On the drop-down code above, if the user selects "Mobile Hire" it should then show the DIV pasted below...otherwise the DIV should be hidden.

<div data-type="duration"><label>Duration</label> <div><select><option value="3">3 h (£120.00)</option><option value="4">4 h (£160.00)</option><option value="5">5 h (£200.00)</option><option value="6">6 h (£240.00)</option><option value="7">7 h (£280.00)</option><option value="8">8 h (£320.00)</option></select></div> </div>

CodePudding user response:

Updated Code, this should work:

 //initially hide duration div
 $('div[data-type="duration"]').hide();

 $('div[data-type="location"] select').on('change' ,(function () {
    var value = $('div[data-type="location"] select option:selected').text();
    if(value === "Mobile Hire") {
        $('div[data-type="duration"]').show();
    }
    else {
        $('div[data-type="duration"]').hide();
    }
  }));

CodePudding user response:

What you want to achieve is done by the following code:

//First Import JQuery CDN, then Following Code inside a script tag

$(document).ready(function () {
  $('div[data-type="location"] select').on('change' , (function () {
      $('div[data-type="duration"]').hide();
  }));
});
Hope this helps!
  • Related