Ahtisham
Ahtisham

Reputation: 10116

Computing id of html tag at runtime with keyup function in jquery

What i am trying to do ?

I want to format the jquery keyup function in such a way so that it will compute id of html tags at runtime by checking which input is currently under user control ( active ).

For example :

html code :

 <input id="first" />
 <input id="second" />

jquery code:

 $(if 'first' is active then it should be passed here).keyup(func_name);

thanks

Upvotes: 0

Views: 51

Answers (2)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

You could use comma separator for the both fields :

$('#first,#second').on('input', func_name);

NOTE : It's better to use input event when you track the user inputs in field.

Hope this helps.

$('#first,#second').on('input', func_name);

function func_name(){
  console.log(this.value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="first" class='input-group'/>
<input id="second" class='input-group'/>

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337570

The pattern you're trying to follow is not how jQuery (or JS itself) is designed to work.

A better idea would be to put a common class on both the elements, and then attach the event handler to that class. You can then use the this keyword to reference the element which raised the event within your func_name() function. Try this;

$('.foo').keyup(func_name);

function func_name() {
  // your logic here...
  console.log(this.id, this.value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input id="first" class="foo" />
<input id="second" class="foo" />

Upvotes: 1

Related Questions