简体   繁体   中英

How to validate dynamically created select boxes in javascript?

I have a html table where the rows are being added dynamically by a javascript function. I have a select box to select the product name in each row. Its working fine.

Now I want to validate the selectbox. I got no clue how to do it. The values in the textboxes shouldn't be selected more than once in the upcoming rows.

I want to show an alert msg like "The product you selected is already selected" onSelect and change the selected value to --Select--- .

See it in action here

Assuming you don't want to allow multiple select boxes to hold same value. Well in the insSpec() method, you can iterate for the existing rows ie select boxes and capture those values.Then you can check that is it already selected or not using selected property of all the select boxes.

UPDATE

var table = document.getElementById("mytab1");
for (var i = 0, cell; cell = table.cells[i]; i++) {
     //iterate through cells
     for (var j = 0, cell2; cell2 = table.cells[j]; j++) {
     //check already selected selectboxes have same value or not
     //compare only selected select boxes
     if(cell.getElementsByTagName('select')[0].selected && cell2.getElementByTagName('select')[0].selected){
         //compare values of both cell's select boxes using value property and alert message                  
    }         
}

Please don't directly copy paste this code.This is just a way to do the stuff.

Reference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM