Validate Specified TextBox Only

2019-08-21 12:02发布

问题:

I have three <input type="text" /> and each one has a button associated with it.

ie

TextBox1 --> Submit1 TextBox2 --> Submit2 TextBox3 --> Submit3

I want Validation to occur only on the corresponding textbox only. If user click Submit2 only validation occurs on TextBox2.

How can I do this?

回答1:

You could put them in separate <form>s and have a single submit button per form.



回答2:

I am not that good with jQuery, but I suppose one way you can do it is to handle the validation with each button click. Here is the html/javascript for the followinng jsfiddle I setup:

<input type="text" id="input1" /><button id="button1">button 1</button><br/>
<input type="text" id="input2"/><button id="button2"> button 2</button><br/>
<input type="text" id="input3"/><button id="button3">button 3</button>​

$(document).ready(function(){
$('#button1').click(function()
                    {
                       //Handle validaton
                       $('#input1').val("You clicked button 1"); 
                    });

$('#button2').click(function()
                    {
                        //Handle validaton
                       $('#input2').val("You clicked button 2"); 
                    });

$('#button3').click(function()
                    {
                        //Handle validaton
                       $('#input3').val("You clicked button 3"); 
                    });

});​



回答3:

Insted of doing it by id you could have a class. such as textbox on the text boxes then you could do

Javascript

$(document).on('click', '.textbox', aFunction);

function aFunction(event){
   var text = $(this).prev().val();
   //validation, text is the text of the box.
}​

HTML

<input type="text" id="input1" /><button class='textbox' id="button1">button 1</button><br/>

<input type="text" id="input2"/><button class='textbox' id="button2"> button 2</button><br/>

<input type="text" id="input3"/><button id="button3" class='textbox'>button 3</button>​

jsfiddle http://jsfiddle.net/FERMIS/zE6uK/1/