How to get focused textbox - javascript

HTML code :
<input type="button" id="btn1" class="textboxclass" onclick="input(this.id)" />
<input type="button" id="btn2" class="textboxclass" onclick="input(this.id)" />
<input type="button" id="btn3" class="textboxclass" onclick="input(this.id)" />
<input type="button" id="btn4" class="textboxclass" onclick="input(this.id)" />
and Javascript code :
function input(e) {
e = e.charAt(3);
$(".textboxclass").each(function(index, value) {
if ($(this).is(':focus')) {
$(this).val($(this).val() + e);
$(this).focus();
}
});
}
and
$(this).is(':focus')
line is not working but when i set alert($(this)) it works after that alert
Thank you

I guess you want to append the last character of the ID to the value of the clicked input field. Then Why don't you just do,
$(function(){
$(".textboxclass").click(function(){
var num = this.id.charAt(3);
$(this).val($(this).val() + e);
});
});

Related

Javascript implementation of arrows in input number - How to make so that changes concerned each item?

I have a basket of goods in which there can be many different entities. And I'm trying to implement changes in the number of goods using input - number without arrows, and with additional buttons +/-. I know that I could use identifiers and easily make my plans. But in my case, I need to use querySelectorAll. Help me please correct this code. quantity-arrow-minus decreases the field value and quantity-arrow-plus increases. How to make it so that the changes are concerned with each item?
var minus = document.querySelectorAll('.quantity-arrow-minus');
var update_cart = document.querySelectorAll('.update_cart');
var plus = document.querySelectorAll('.quantity-arrow-plus');
minus.forEach(function(node) {
node.addEventListener('click', function() {
update_cart.forEach(function(element) {
element.value = parseInt(element.value) - 1;
});
});
});
plus.forEach(function(node) {
node.addEventListener('click', function() {
update_cart.forEach(function(element) {
element.value = parseInt(element.value) + 1;
});
});
});
<form method="GET">
<button type="button" class="quantity-arrow-minus">-</button>
<input type="number" class="update_cart" value="1">
<button type="button" class="quantity-arrow-plus">+</button>
</form>
<form method="GET">
<button type="button" class="quantity-arrow-minus">-</button>
<input type="number" class="update_cart" value="1">
<button type="button" class="quantity-arrow-plus">+</button>
</form>
You can use previousElementSibling and nextElementSibling to access the input that corresponds to the button that was clicked:
var minus = document.querySelectorAll('.quantity-arrow-minus');
var update_cart = document.querySelectorAll('.update_cart');
var plus = document.querySelectorAll('.quantity-arrow-plus');
minus.forEach(function(node) {
node.addEventListener('click', function(e) {
const input = e.target.nextElementSibling
input.value = parseInt(input.value) - 1;
});
});
plus.forEach(function(node) {
node.addEventListener('click', function(e) {
const input = e.target.previousElementSibling
input.value = parseInt(input.value) + 1;
});
});
<form action="{% url 'cart:cart_update' %}" method="GET">
<button type="button" class="quantity-arrow-minus">-</button>
<input type="number" class="update_cart" value="0">
<button type="button" class="quantity-arrow-plus">+</button>
<br>
<button type="button" class="quantity-arrow-minus">-</button>
<input type="number" class="update_cart" value="0">
<button type="button" class="quantity-arrow-plus">+</button>
</form>
Use Number() instead. Assuming that the minus button will be just after your input, just use this.nextElementSibling. This is will make your code better instead of doing forEach on every element. What if there are many elements like these?
var minus = document.querySelectorAll('.quantity-arrow-minus');
var plus = document.querySelectorAll('.quantity-arrow-plus');
minus.forEach((node) => {
node.onclick = function () {
this.nextElementSibling.value = Number(this.nextElementSibling.value) - 1;
}
});
plus.forEach((node) => {
node.onclick = function () {
this.previousElementSibling.value =Number(this.previousElementSibling.value) + 1;
}
});
<button class="quantity-arrow-minus">-</button>
<input type="number" class="update_cart" value="1">
<button class="quantity-arrow-plus">+</button>
<br>
<button class="quantity-arrow-minus">-</button>
<input type="number" class="update_cart" value="1">
<button class="quantity-arrow-plus">+</button>
<br>
<button class="quantity-arrow-minus">-</button>
<input type="number" class="update_cart" value="1">
<button class="quantity-arrow-plus">+</button>

JQuery: Trying to append numbers into a text area on button click

I am having trouble getting one of my buttons to append data to a HTML text area. The button in question is "BPI". I am trying to append a few digits of pi to my first text area. The other 4 buttons operate within the 2nd text area. Thank you in advance for your help.
$(document).ready(function() {
$('#BAddition').click(function(e) {
$('#TOperator').val() += "+";
})
$('#BSubtract').click(function(e) {
$('#TOperator').val() += "-";
})
$('#BMultiplication').click(function(e) {
$('#TOperator').val() += "*";
})
$('#BDivision').click(function(e) {
$('#TOperator').val() += "/";
})
$('#BPI').click(function(e) {
$('#TFirstnum').val() += "3.141592657";
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Input:<br>
<textarea id="TFirstnum"></textarea>
<textarea id="TOperator"></textarea>
<textarea id="TSecondnum"></textarea>
<label id="LEquals"></label>
<br>
<button type="button" onclick="" id="BAddition">+</button>
<button type="button" onclick="" id="BSubtract">-</button>
<button type="button" onclick="" id="BDivision">/</button>
<button type="button" onclick="" id="BMultiplication">*</button>
<button type="button" onclick="" id="BPI">π</button>
<button type="button" onclick="" id="BEquals">=</button>
If you want to add a value use $(yourObject).val("yourvalue")
If you want to add a value to the already existing value use $(yourObject).val($(yourObject).val() + "yourvalue")
Working example below
$(document).ready(function() {
$('#BAddition').click(function(e) {
$('#TOperator').val($('#TOperator').val() + "+");
})
$('#BSubtract').click(function(e) {
$('#TOperator').val($('#TOperator').val() + "-");
})
$('#BMultiplication').click(function(e) {
$('#TOperator').val($('#TOperator').val() + "*");
})
$('#BDivision').click(function(e) {
$('#TOperator').val($('#TOperator').val() + "/");
})
$('#BPI').click(function(e) {
$('#TOperator').val($('#TOperator').val() + "3.141592657");
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Input:<br>
<textarea id="TFirstnum"></textarea>
<textarea id="TOperator"></textarea>
<textarea id="TSecondnum"></textarea>
<label id="LEquals"></label>
<br>
<button type="button" onclick="" id="BAddition">+</button>
<button type="button" onclick="" id="BSubtract">-</button>
<button type="button" onclick="" id="BDivision">/</button>
<button type="button" onclick="" id="BMultiplication">*</button>
<button type="button" onclick="" id="BPI">π</button>
<button type="button" onclick="" id="BEquals">=</button>
When you want to set an element's value attribute using Jquery, you need to set the value inside the parantheses: .val('newValue').
When you want to get an element's value, use blank parantheses: var x = elem.val().
So to concatenate (or append) values, you should use:
$('#TOperator').val($('#TOperator').val() + '+');
A longer version to elaborate:
var expr = $('#TOperator').val(); // Get current value
expr += '+'; // Concatenate the + sign
$('#TOperator').val(expr); // Set the new value
You are useing += which does not work. You have to get the value, and then set the value;
$('#BAddition').click(function(e) {
$('#TOperator').val( $('#TOperator').val() + "+");
});
You're repeating yourself a lot. I suggest you change the html a bit and create a much neater function.
<button type="button" class="MathSign" data-sign="+">+</button>
<button type="button" class="MathSign" data-sign="-">-</button>
<button type="button" class="MathSign" data-sign="/">/</button>
<button type="button" class="MathSign" data-sign="*">*</button>
<button type="button" id="BPI">π</button>
<button type="button" class="MathSign" data-sign="=">=</button>
// handle the [+ - * / =] in one go:
$('.MathSign').on('click', function(){
$('#TOperator').val( $('#TOperator').val() + $(this).data('sign'));
// Or,you can drop the data-sign attribute and use the content of the button
$('#TOperator').val( $('#TOperator').val() + this.innerHTML);
})
$(selector).val() is used to get the value of the input box.
If you want to set the value, you need to pass the value $(selector).val(value).
I have modified your example. One thing you need to consider is when you do $(selector).val(), you will get string. If you want to have addition instead of concatenation of two strings, You should probably use parseInt
$(document).ready(function() {
$('#BAddition').click(function(e) {
$('#TOperator').val($('#TOperator').val() + "+");
})
$('#BSubtract').click(function(e) {
$('#TOperator').val($('#TOperator').val() + "-");
})
$('#BMultiplication').click(function(e) {
$('#TOperator').val($('#TOperator').val() + "*");
})
$('#BDivision').click(function(e) {
$('#TOperator').val($('#TOperator').val() + "/");
})
$('#BPI').click(function(e) {
$('#TFirstnum').val($('#TFirstnum').val() + "3.141592657");
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Input:<br>
<textarea id="TFirstnum"></textarea>
<textarea id="TOperator"></textarea>
<textarea id="TSecondnum"></textarea>
<label id="LEquals"></label>
<br>
<button type="button" onclick="" id="BAddition">+</button>
<button type="button" onclick="" id="BSubtract">-</button>
<button type="button" onclick="" id="BDivision">/</button>
<button type="button" onclick="" id="BMultiplication">*</button>
<button type="button" onclick="" id="BPI">π</button>
<button type="button" onclick="" id="BEquals">=</button>

input a button value on corresponding textbox that is on focus

I am trying to create a touchscreen calculator like where the button value will be placed on the textbox after i set it on a focus by clicking but it appears on all the textboxes.I tried to use the code
if ($(impo).is(":focus")) {
but it doesnt work. Please see my snippet
Thanks in advance!
var impo = document.getElementById("imp_text");
var tess = document.getElementById("tess_text");
var FKeyPad = document.Keypad;
var Accumulate = 0;
var FlagNewNum = false;
var PendingOp = "";
document.getElementById('tess').onclick = function() {
document.getElementById('tess_text').focus();
}
document.getElementById('imp').onclick = function() {
document.getElementById('imp_text').focus();
}
function NumPressed(Num) {
if (impo) {
if (FlagNewNum) {
FKeyPad.ReadOut.value = Num;
FlagNewNum = false;
} else {
if (FKeyPad.ReadOut.value == " ")
FKeyPad.ReadOut.value = Num;
else
FKeyPad.ReadOut.value += Num;
}
}
if (tess) {
if (FlagNewNum) {
FKeyPad.readtess.value = Num;
FlagNewNum = false;
} else {
if (FKeyPad.readtess.value == " ")
FKeyPad.readtess.value = Num;
else
FKeyPad.readtess.value += Num;
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<html lang="en">
<head>
</head>
<body>
<form name="Keypad" action="">
<input type="button" value="Imp" id="imp" /> Importo :
<input name="ReadOut" id="imp_text" type="Text" value=" "> <br>
<input type="button" value="Tes" id="tess" /> Card Tess :
<input name="readtess" id="tess_text" type="Text" value=" ">
<br>
<input type="button" value=" 1" onclick="NumPressed(1)" />
<input type="button" value=" 2" onclick="NumPressed(2)" />
<input type="button" value=" 3" onclick="NumPressed(3)" /> <br>
</form>
</body>
</html>
if (impo) and if (tess) just tests whether the element exists, which they do, so the value gets written to both of them because they both exist. In a desktop environment, you can't do what you're asking - you can give a textbox the focus, but once the user clicks on one of the buttons in order to select that number, the textbox no longer has the focus (because the button has it).
You need a separate way to maintain which textbox is currently selected, something like the snippet below. It will update the currently "selected" element both on the click of the Imp/Tes buttons and whenever either of the textbox gains focus (e.g. by mouse click or touch).
var impo = document.getElementById("imp_text");
var tess = document.getElementById("tess_text");
var current_input = impo;
impo.onfocus = function() {
current_input = impo;
}
tess.onfocus = function() {
current_input = tess;
}
document.getElementById('tess').onclick = function() {
current_input = tess;
tess.focus();
}
document.getElementById('imp').onclick = function() {
current_input = impo;
impo.focus();
}
function NumPressed(Num) {
current_input.value += Num;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<html lang="en">
<head>
</head>
<body>
<form name="Keypad" action="">
<input type="button" value="Imp" id="imp" /> Importo :
<input name="ReadOut" id="imp_text" type="Text" value=""> <br>
<input type="button" value="Tes" id="tess" /> Card Tess :
<input name="readtess" id="tess_text" type="Text" value="">
<br>
<br>
<input type="button" value="1" onclick="NumPressed(this.value)" />
<input type="button" value="2" onclick="NumPressed(this.value)" />
<input type="button" value="3" onclick="NumPressed(this.value)" /> <br>
<input type="button" value="4" onclick="NumPressed(this.value)" />
<input type="button" value="5" onclick="NumPressed(this.value)" />
<input type="button" value="6" onclick="NumPressed(this.value)" /> <br>
<input type="button" value="7" onclick="NumPressed(this.value)" />
<input type="button" value="8" onclick="NumPressed(this.value)" />
<input type="button" value="9" onclick="NumPressed(this.value)" /> <br>
<input type="button" value="0" onclick="NumPressed(this.value)" /> <br>
</form>
</body>
</html>

Change a variable when button is clicked

Trying to make simple tic-tac-toe game. I'm trying to change the button's value when clicked, but I don't know which one the user will click first. Obviously, I've got 9 buttons like this:
<input type="button" id="Button1" onclick="Button1_Click()" />
and a function like this, to handle their onclick event.
<script>
var Caption = "X";
function Button1_Click() {
document.getElementById('Button1').value = Caption;
if (Caption=="X") {
Caption = "O";
Caption="X";
}
}
</script>
But the thing is, when i click other buttons, The caption is always the same (X), how can I change it?
I think you may just change your Button1_Click() like below:
function Button1_Click() {
document.getElementById('Button1').value = Caption;
if (Caption=="X") {
Caption = "O";
} else {
Caption="X";
}
}
But, in this way, you said you have 9 buttons. Then you have to create 9 separated but look quite the same function like the one above.
How about this:
<!--You need to make it look better..-->
<div id='buttonParent'>
<input type='button' id='btn1'>
<input type='button' id='btn2'>
<input type='button' id='btn3'>
<input type='button' id='btn4'>
<input type='button' id='btn5'>
<input type='button' id='btn6'>
<input type='button' id='btn7'>
<input type='button' id='btn8'>
<input type='button' id='btn9'>
</div>
<script>
// wrap all your 9 buttons in a tag <div id='buttonParent'> or whatever you like.
var buttonParentNode = document.getElementById('buttonParent');
var button_click = function(e) {
// this function handle all button click event
var btn = e.target; // DOM element which was click. It must be any tag inside buttonParentNode
if (btn.tagName == 'INPUT') { // if DOM element is a input tag.
if (btn.innerHTML == 'X') {
btn.innerHTML = 'O';
} else {
btn.innerHTML = 'X';
}
}
};
buttonParentNode.addEventListener('click', button_click, false);
</script>
Method 1: Closure
One way to do it is using a closure for the click handler, so it knows which button was pressed. Keep track of who'se turn it is in a variable.
// Do this only when the page is loaded.
window.addEventListener('DOMContentLoaded', function() {
// Variable to keep track of turns in.
var Xturn = true;
// A function that returns a specific click handler for a button.
function createClickHandler(element, index) {
// The anonymous function that is returned is the actual click handler.
return function() {
// Logs text in the console (press F12 to view it). Very useful for testing/debugging!
console.log('Button ' + index + ' clicked');
// Only do something if this button was still open.
if (element.innerText == '') {
element.innerText = Xturn ? 'X' : 'O';
Xturn = !Xturn; // Toggle player
};
}
}
// Now for the actual initialisation:
// Find all buttons.
var buttons = document.querySelectorAll('button');
// Attach a click handler to each of them.
for (n = 0; n < buttons.length; n++) {
buttons.item(n).addEventListener('click', createClickHandler(buttons.item(n), n));
}
});
button {
width: 50px;
height: 50px;
line-height: 50px;
vertical-align: bottom;
}
<div>
<button/><button/><button/>
</div>
<div>
<button/><button/><button/>
</div>
<div>
<button/><button/><button/>
</div>
Method 2: Event target
When an event is triggered, the event handler gets an event object as a parameter. This object contains information about the event, like the element that triggered it. This way you can also find the button. If you give every button an id or other recognizable property, you can distinguish between the buttons.
You can bind an event handler on every button, but it's even easier to bind it to a parent element. You can even bind the click handler to the document. That way you also don't have to wait for the DOM to be loaded. The even handler will capture every click, and it will even capture clicks on elements that are dynamically added later.
Inside the event handler, you can get the element that triggered it, and only respond if it is one of the buttons of the game:
// Variable to keep track of turns in.
var Xturn = true;
document.addEventListener('click', function(event) {
var event = event || window.event;
var element = event.target || event.srcElement;
// Only respond to button clicks
if (element.tagName == 'BUTTON') {
console.log('Button ' + element.id + ' clicked');
// Only do something if this button was still open.
if (element.innerText == '') {
element.innerText = Xturn ? 'X' : 'O';
Xturn = !Xturn; // Toggle player
}
}
});
button {
width: 50px;
height: 50px;
line-height: 50px;
vertical-align: bottom;
}
<div>
<button id='b1' /><button id='b2' /><button id='b3' />
</div>
<div>
<button id='b4' /><button id='b5' /><button id='b6' />
</div>
<div>
<button id='b7' /><button id='b8' /><button id='b9' />
</div>
function button_Click(e) {
if(e.value === 'X') {
e.value = 'O';
} else {
e.value = 'X';
}
}
<input type="button" id="button1" onclick="button_Click(this)" value="X" />
<input type="button" id="button2" onclick="button_Click(this)" value="O" />
<input type="button" id="button3" onclick="button_Click(this)" value="X" />
<input type="button" id="button4" onclick="button_Click(this)" value="O" />
<input type="button" id="button5" onclick="button_Click(this)" value="X" />
<input type="button" id="button6" onclick="button_Click(this)" value="O" />
<input type="button" id="button7" onclick="button_Click(this)" value="X" />
<input type="button" id="button8" onclick="button_Click(this)" value="O" />
<input type="button" id="button9" onclick="button_Click(this)" value="X" />
<input type="button" id="button10" onclick="button_Click(this)" value="O" />
However a better approach would be as follows:
document.addEventListener("DOMContentLoaded", buttonClickHandler);
function buttonClickHandler() {
var buttons = document.getElementsByClassName('button');
for(var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', function() {
if(this.value === 'X') {
this.value = 'O';
} else {
this.value = 'X';
}
});
}
}
<input type="button" class="button" value="X" />
<input type="button" class="button" value="O" />
<input type="button" class="button" value="X" />
<input type="button" class="button" value="O" />
<input type="button" class="button" value="X" />
<input type="button" class="button" value="O" />
<input type="button" class="button" value="X" />
<input type="button" class="button" value="O" />
<input type="button" class="button" value="X" />
<input type="button" class="button" value="O" />
try this,
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
</head>
<body>
<div>
<input type="button" id="Button1" class="btn" onclick="Button1_Click(this)" />
<input type="button" id="Button2" class="btn" onclick="Button1_Click(this)" />
<input type="button" id="Button3" class="btn" onclick="Button1_Click(this)" />
</div>
<div>
<input type="button" id="Button4" class="btn" onclick="Button1_Click(this)" />
<input type="button" id="Button5" class="btn" onclick="Button1_Click(this)" />
<input type="button" id="Button6" class="btn" onclick="Button1_Click(this)" />
</div>
<div>
<input type="button" id="Button7" class="btn" onclick="Button1_Click(this)" />
<input type="button" id="Button8" class="btn" onclick="Button1_Click(this)" />
<input type="button" id="Button9" class="btn" onclick="Button1_Click(this)" />
</div>
<script>
var Caption = "X";
function Button1_Click(btn) {
$(btn).val(Caption);
if (Caption == "X") {
Caption = "O";
} else {
Caption = "X";
}
}
</script>
</body>
</html>
<input type="button" value=' ' onclick="Button_Click(this)" />
<input type="button" value=' ' onclick="Button_Click(this)" />
<input type="button" value=' ' onclick="Button_Click(this)" /> <br/>
<input type="button" value=' ' onclick="Button_Click(this)" />
<input type="button" value=' ' onclick="Button_Click(this)" />
<input type="button" value=' ' onclick="Button_Click(this)" /> <br/>
<input type="button" value=' ' onclick="Button_Click(this)" />
<input type="button" value=' ' onclick="Button_Click(this)" />
<input type="button" value=' ' onclick="Button_Click(this)" /> <br/>
<script>
var turn = 'x';
function Button_Click(btn) {
if (btn.value == ' ') {
btn.value = turn;
turn = (turn == 'x') ? 'o' : 'x';
}
}
</script>
You may try it here

Dynamically add and remove TextBoxes and get value of dynamic TextBox using jQuery and display it in a textbox

i have code where you can add or delete textbox using .append() and .remove() in jquery, now i want to implode all the value of the textboxes separated by commas and pass it into another textbox located outside the script. how can i do it? here's the code for dymically adding and removing textbox. (not mine just got it here in stackoverflow)
HTML:
<input id="btnAdd" type="button" value="Add" />
<br />
<br />
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<br />
<input id="btnGet" type="button" value="Get Values" />
javascript:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs /jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnAdd").bind("click", function () {
var div = $("<div />");
div.html(GetDynamicTextBox(""));
$("#TextBoxContainer").append(div);
});
$("#btnGet").bind("click", function () {
var values = "";
$("input[name=DynamicTextBox]").each(function () {
values += $(this).val() + "\n";
});
alert(values);
});
$("body").on("click", ".remove", function () {
$(this).closest("div").remove();
});
});
function GetDynamicTextBox(value) {
return '<input name = "DynamicTextBox" type="text" value = "' + value + '" /> ' +
'<input type="button" value="Remove" class="remove" />'
}
</script>
Use .val() to set value of "another textbox" to values
$(function() {
$("#btnAdd").bind("click", function() {
var div = $("<div />");
div.html(GetDynamicTextBox(""));
$("#TextBoxContainer").append(div);
});
$("#btnGet").bind("click", function() {
var values =
$.map($("input[name=DynamicTextBox]"), function(el) {
return el.value
}).join(",\n");
$("#anotherTextbox").val(values);
});
$("body").on("click", ".remove", function() {
$(this).closest("div").remove();
});
});
function GetDynamicTextBox(value) {
return '<input name = "DynamicTextBox" type="text" value = "' + value + '" /> ' +
'<input type="button" value="Remove" class="remove" />'
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input id="btnAdd" type="button" value="Add" />
<br />
<br />
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<br />
<input id="btnGet" type="button" value="Get Values" />
<input id="anotherTextbox" type="text" />

Categories