Dre Dre - 6 months ago 14
jQuery Question

Show/Hide Div's even if input is required?

I have a form in which divs are shown/hidden based on what is selected in a drop down box. Using .show and .hide via jquery works great to show/hide the fields, however the input on these forms need to be required. What's happening is when one of the fields is hidden, the form won't submit - more than likely because this "hidden" field still required.

Is there a way to disable/remove this field all together instead of hiding the div when a certain item is selected in the drop down? I've attempted using the .attr("disabled", true) with no luck. Any help is appreciated.

JQuery snippet:

$('#productpr1').on('change',function() {

if(this.value=='PRODUCT1')
{
$('.initial').show();
$('.name').show();
$('.mono').hide();
$('.comment').show();

}
else if (this.value=='PRODUCT2')
{
$('.initial').hide();
$('.name').hide();
$('.mono').show();
$('.comment').show();

}
else if (this.value=='PRODUCT3')
{
$('.initial').show();
$('.name').show();
$('.mono').show();
$('.comment').show();
}
else
{
$('.initial').show();
$('.name').show();
$('.mono').show();
$('.comment').show();
}

});


HTML:

<select name="productpr1" id="productpr1">
<option value="Please Select:0">Please select your product</option>
<option value="PRODUCT1">PRODUCT1</option>
<option value="PRODUCT2">PRODUCT2</option>
<option value="PRODUCT3">PRODUCT3</option>
</select>
<br>
<br>

<div class="initial">
<div id="Profont"><b>Initial:</b>
</div>
<input name="product1[]" type="text" required id="thisone" size="5">
</div>

<div class="name">
<div id="Profont"><b>Name:</b>
<br>
</div>
<input name="product1[]" type="text" required id="thisone" size="5">
</div>


<div class="mono">
<div id="Profont"><b>Mono Initials:</b>
<br>
</div>
<input name="product1[]" type="text" required id="thisone" size="5">
</div>

<div class="comment">
<div id="Profont"><b>Additional Comments:</b>
<br>
</div>
<input type="text" name="product1[]" size="10" id="comments">
</div>

<input type="submit" value="Add to Cart" name="Cart" class="INDVbutton" />

Answer

You could remove the required attribute when you hide it.

$('.name').hide().find(':input').attr('required', false);

and add it back when you show it:

$('.name').show().find(':input').attr('required', true);