I’m trying to create this form page. I already have a form ready for data insertion to database. I just need to stylize it so that the form changes dynamically after selection change.
I’m trying to create it dynamic so that when you select something else, the previous fieldset changes to new one and the last selection disappears. Nothing works with my code. I tried traditional JS – same results. I already put the div as display:none
in CSS. Maybe my syntax is wrong?
$('body').on('change', '##productType', function() {
if ($(this).val() == "DVD")
$("#DVD").show();
else
$("#DVD").hide();
});
<form>
<fieldset>
<label for="#productType">Type Switcher</label>
<select id="#productType">
<option>--Select a Type</option>
<option value="DVD" id="#DVD" onchange="show(this)">DVD</option>
<option value="Book" id="#Book" onchange="show(this)">Book</option>
<option value="Furniture" id="#Furniture" onchange="show(this)">Furniture</option>
</select>
</fieldset>
<br>
<div class="subform-test-class">
<fieldset id="#DVD" class="info-block">
<label for="#DVD">Size (MB)</label>
<input type="text" id="#DVD" name="dvdSize">
<p>*Please provide size of the DVD (MB)</p>
</fieldset>
<br>
<fieldset id="#Book" class="info-block">
<label for="#weight" id="book">Weight (KG)</label>
<input type="text" id="#weight" name="bookWeight">
<p>*Please provide weight of the book in KG.</p>
</fieldset>
<br>
<fieldset id="#Furniture" class="info-block">
<label for="#height" id="height">Height</label>
<input type="text" id="#height" name="fHeight">
<label for="#width" id="width">Width</label>
<input type="text" id="#width" name="fWidth">
<label for="#length" id="length">Length</label>
<input type="text" id="#length" name="fLength">
<p>*Please provide size of the furniture in dimensions of HxWxL</p>
</fieldset>
</div>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
Answers
There are many mistakes in your code:-
There are some other minor errors also, but you will figure it out by looking at the updated code. Here is the updated code:-
There are different ways to achieve your desired outcome, the first of which – with explanatory comments in the code – is below:
Obviously, you can use jQuery if you really wish though there’s not really much reason to do so; however, if you must then the following may be of use:
In short, however, the original problem was your use of the
#
character within a declaredid
attribute-value; this is a CSS selector, but should not be present in theid
itself (similarly, a.
character is the selector forclass-names, but should not be present in the
class
). The character can be present, but does require escaping:References:
:not()
.document.querySelector()
.document.querySelectorAll()
.Event
.Event.currentTarget
.HTMLElement.hidden
.each()
.on()
.toggle()
.val()
.