Various functions to execute depending on cursor location (javascript)

Currently, I have a button in the form of html that performs a function on click:

<input type="button" onclick="do_action_1();">

But I have two functions:

do_action_1()
do_action_2()

I also have two text fields:

<input id="tb1" type="text" name="textbox1">
<input id="tb2" type="text" name="textbox2">

If the user cursor is in text box 1, I want the button to execute

do_action_1

but if the user cursor is in textbox2, I want the button to execute

do_action_2.

I'm not sure where to start when this is done, so any help is greatly appreciated.

+4
source share
3 answers

Add an onclickevent for each input and change the attribute of the target element attrvalue

$('#tb1').click(function(){
  $('.change_function').attr("onclick","do_action_1();");
});
$('#tb2').click(function(){
  $('.change_function').attr("onclick","do_action_2();");
});

function do_action_1(){
  alert("function 1 is selected !");
}
function do_action_2(){
  alert("function 2 is selected !");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="button" onclick="do_action_1();" class="change_function" value="Change Function">
Function 1<input id="tb1" type="text" name="textbox1">
Function 2<input id="tb2" type="text" name="textbox2">
Run codeHide result

Edit

focus katz Eddie, , , , .

$('#tb1').focus(function(){
  $('.change_function').attr("onclick","do_action_1();");
});
$('#tb2').focus(function(){
  $('.change_function').attr("onclick","do_action_2();");
});
+3

, onfocus

var tb1 = document.getElementById('tb1');
var tb2 = document.getElementById('tb2');

tb1.onfocus = function(){
  console.log('1')
  do_action_1
}

tb2.onfocus = function(){
  console.log('2')
  do_action_2
}
+1

I would use onfocusto set the class in a text box, and then use this class to see what action to perform:

$('input[name^="textbox"]').on('focus',function () {
  $('input[name^="textbox"]').removeClass('active');
  $(this).addClass('active');
});

function do_action () {
  if ($('input[name="textbox1"]').is('.active')) do_action_1();
  else do_action_2();
}
+1
source

Source: https://habr.com/ru/post/1693564/


All Articles