简体   繁体   中英

How to differenciate 2 buttons calling the same jquery function

I have 2 textfields and 2 buttons calling the same function.

<input type="text" id="value1"/>
<input type="button" value="Get value" id="getvalue"/><br>

<input type="text" id="value2"/>
<input type="button" value="Get value" id="getvalue"/><br>

$('#getvalue').click(function(){       
        recording one value at a time
});

How can I record each individual values from the same function. Any advices would very welcomed.

Thanks.

Id's should be unique.

Why don't u use the code like this.

<input type="text" id="value1"/>
<input type="button" value="Get value" class="getvalue" id="btn1" /><br>

<input type="text" id="value2"/>
<input type="button" value="Get value" class="getvalue" id="btn2"/><br>

$('input.getvalue').click(function(){       
   if (this.id == "btn1") {
   }
   if (this.id == "btn2") {
   }
});

Try this- Working Fiddle

And i agree with Mr.Alien

$('#getvalue').click(function(){       
   var value1 = $('#value1').val();
   var value2 = $('#value2').val();
   alert(value1);
   alert(value2);
});

You can do it also as per below:

<input type="text" id="value1"/>
<input type="button" value="Get value" data="val1" id="getvalue"/><br>

<input type="text" id="value2"/>
<input type="button" value="Get value" data="val2" id="getvalue"/><br>

$('#getvalue').click(function(){       
       var data=$(this).attr('data');
if(data=="val1")
{
alert($('#value1').val());
}
else if(data=="val2")
{
alert($('#value2').val());
}
});

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