javascript validation on text boxes created dynamically

前端 未结 1 1193
抹茶落季
抹茶落季 2021-01-18 22:38

In a form a text box is created dynamically by clicking on add button such that the text box is created in a new row.Now my problem is the validation of text boxes which wer

1条回答
  •  盖世英雄少女心
    2021-01-18 23:06

    on the submit event of the form you simply need to collect all input text boxes that you find in the form and pass them into a validation function.

    Put this code in the section of your page

    //This function here is only a cross-browser events stopper
    stopEvent = function(ffevent)
    {
       var current_window = window;
    
       if(current_window.event) //window.event is IE, ffevent is FF
       {
          //IE
          current_window.event.cancelBubble = true; //this stops event propagation
          current_window.event.returnValue = false; //this prevents default (usually is what we want)
       }
       else
       {
          //Firefox
          ffevent.stopPropagation();
          ffevent.preventDefault();
       };
    }
    
    function validateAllInputBoxes(ffevent)
    {
       var inputs = document.getElementsByTagName('input');
       for(var i = 0; i < inputs.length; ++i)
          if(inputs[i].type === 'text')
             //@Satish, maybe below you wrote by mistake if(inputs[i].value = '') thus all input elements values get cleared out.
             if(inputs[i].value === '') 
             {
                alert("form could not be sent one input text field is empty");
                stopEvent(ffevent);
             }
    }
    

    and in the the

    tag place the following code:

    onsubmit="validateAllInputBoxes(event);"
    

    0 讨论(0)
提交回复
热议问题