Link to home
Start Free TrialLog in
Avatar of Tammu
Tammu

asked on

jQuery make textboxes required based number of options selected from a select box

Hi Everyone,

I have a select box where a user can select how many charms he/she wants. Based on that select I showing textboxes where they enter the charm text. You can see that in my test site

http://dev.mommyjewelry.com/TESTPROD.html

In the above link by default one charm is selected and its textbox is shown below. I have a small JS code which checks if the textbox length and displays an alert box saying that the textbox is required.

The code also checks when there are multiple charms selected what I means is if you select 2 charms you will 2 textboxes and even if one of them is empty the alert box shows.

But for some reason my code is always showing the length is 1 even there is no text in the textbox, I am doing this on form submit. here is the code

<script type="text/javascript">
$(document).ready(function(){ $("#product_form").submit(function(e) {
var number_of_charms = $("#charm").prop("selectedIndex") + 1;
var fields_not_empty = $(":text[name^=Product_Attribute]:visible[value]").length;
if(number_of_charms > fields_not_empty) {
$(".error").show();
alert("You left one or more required fields empty. Please check your selection above and adjust as needed.");
e.preventDefault();
}
});
});
</script>

Open in new window


What am I doing wrong?

Thanks and appreciate it
ASKER CERTIFIED SOLUTION
Avatar of Rainer Jeschor
Rainer Jeschor
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial