could someone help me please and see where I am going wrong?
<script type="text/javascript">
function validateForm(){
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("Enter Name");
return false;
}
var x=document.forms["myForm"]["car[]"].value;
if (x==null || x=="")
{
alert("Select Car");
return false;
}
}
function add(tbl1) {
var tb = document.getElementById(tbl1);
var rowCount = tb.rows.length;
var row = tb.insertRow(rowCount);
var colCount = tb.rows[1].cells.length;
for(var i=0; i<colCount; i++) {
var newCell = row.insertCell(i);
newCell.innerHTML = tb.rows[1].cells[i].innerHTML;
}
}
</script>
</head>
<body>
<form name="myForm" action="post.php" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<br><br>
<p>2. Your previous cars</p>
<table id="cars" border="1">
<tr><td width = "150"><center>Car</center></td>
</tr><tr>
</td><td><select name="car[]">
<option value="" selected=“selected”>Select one please</option>
<option value=Ford> Ford </option>
<option value=Audi> Audi </option>
<option value=Volvo> Volvo </option>
<option value=Nissan> Nissan </option>
<option value=Car 5>Car 5 </option>
</select></td>
</tr></table><br><br>
<input type="button" value="Add Row" onclick="add('cars')"/>
<input type="submit" value="Submit">
</form>
I have created an array of cars so if personA has more cars, they can click add and select another one. If they have 1 car and just enter name and 1 car, the form works but when I click Add row and select another car, it doesnt work?
Thanks
Your problem is that
document.forms["myForm"]["car[]"]is an element when there is one select element named “car[]”, but it is an array (of elements) when there are multipel select elements named “car[]”. Your validation assumes that it is always an element, so it fails.You can either test if
document.forms["myForm"]["car[]"]is an array, which you will likely find awkward, or you can usedocument.getElementsByName("car[]"), which will always return an array of elements for you to iterate over.The following
ifwould evaluate to true if the array was empty or the first element didn’t meet your conditions for validity.This solution assumes that only the first must be valid (given the lack of “remove car” button, this seems most resonable; if that is not your intention, iterate over them and return false if any fails to meet the validity condition.