I want to make a discount system based on Dollar and Percentage. So I made this form:
<div >
<div >
<span >*</span>
<label for="type" >Type of discount</label>
<div >
<input type="radio" name="type" id="type">
<label for="type">
Dollar
</label>
</div>
<div >
<input type="radio" name="type" id="type" checked>
<label for="type">
Percentage
</label>
</div>
</div>
</div>
<div >
<div >
<span >*</span>
<label for="value" >Value of dicount</label>
<small id="typepercent">percentage</small>
<small id="typedollar">dollars</small>
<br>
<input type="text" id="value" name="value" value="" autofocus>
</div>
</div>
So basically users can choose the discount type between Dollar type or Percentage type.
Then at the next input, they have to write the value of discount. If they have selected Percentage, this text must be appears:
<small id="typepercent">percentage</small>
Otherwise, show this:
<small id="typedollar">dollars</small>
Now in order to do this, I added this script:
const typedis = document.querySelector('#type');
typedis.addEventListener('change', e => {
if(e.target.checked === true) {
$("#typepercent").hide();
$('#typedollar').show();
}else{
$("#typepercent").show();
$('#typedollar').hide();
}
});
But now it does not work out properly!
I mean the first time when I changes to Dollar, it shows #typedollar
correctly but when I go back to Percentage, the #typedollar
div still shows up however it must be hidden and #typepercent
must be appear.
So what's going wrong here? How can I fix this issue?
CodePudding user response:
Please don't use the same id for multiple elements. You just need to use simple jquery and add a class in your radio input elements.
$(document).ready(function() {
$('.form-check-input').on("change", function(){
if($(this).hasClass("dollar")) {
$("#typepercent").hide();
$('#typedollar').show();
}else{
$("#typepercent").show();
$('#typedollar').hide();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<div >
<span >*</span>
<label for="type" >Type of discount</label>
<div >
<input type="radio" name="type" id="type">
<label for="type">
Dollar
</label>
</div>
<div >
<input type="radio" name="type" id="type" checked>
<label for="type">
Percentage
</label>
</div>
</div>
</div>
<div >
<div >
<span >*</span>
<label for="value" >Value of dicount</label>
<small id="typepercent">percentage</small>
<small id="typedollar">dollars</small>
<br>
<input type="text" id="value" name="value" value="" autofocus>
</div>
</div>
</body>