how to use javascript onkeyup for multiple ids at sametime - javascript

I have 2 html textbox for users to enter numbers. To sum those numbers, I am passing the values to JavaScript variable and after addition displaying the result to html div section
<div class="input-left"><span><input class="textbox" id="left" name="count" type="text" size="5" value="" /></span></div>
<div class="input-right"><span><input class="textbox" id="right" name="count" type="text" size="5" value="" /></span></div>
<div id="result"> </div>
javascript:
document.getElementById('left').onkeyup = function() {
var a = parseFloat(this.value);
}
document.getElementById('right').onkeyup = function() {
var b = a + parseFloat(this.value);
document.getElementById("result").innerHTML = b || 0 ;
}
But I have an issue with JavaScript. It not displaying the result. How to add both functions in same onkeyup function.
FIDDLE SETUP

Try this:
window.onload = function(){
var left = document.getElementById('left');
var right = document.getElementById('right');
var result = document.getElementById("result");
left.onkeyup = calc;
right.onkeyup = calc;
function calc() {
var a = parseFloat(left.value) || 0;
var b = parseFloat(right.value) || 0;
result.innerHTML = a + b ;
}
}
JSFiddle: http://fiddle.jshell.net/gYV8Z/3/
Update: To hide the result in case the sum equals zero , change the last line like this:
result.innerHTML = ( a + b ) || "";
JSFiddle: http://fiddle.jshell.net/gYV8Z/4/

document.getElementById('left').onkeyup = function() {
var a = parseFloat(this.value);
}
document.getElementById('right').onkeyup = function() {
var b = a + parseFloat(this.value);
document.getElementById("result").innerHTML = b || 0 ;
}
it your code, var a is local variable. make it global variable.
but i would use this code.
function add(){
return parseFloat(document.getElementById('left').value) + parseFloat(document.getElementById('right').value);
}
document.getElementById('left').onkeyup = function() {
document.getElementById("result").innerHTML = add();
}
document.getElementById('right').onkeyup = function() {
document.getElementById("result").innerHTML = add();
}

Related

HTML and Javscript field returning NaN, when field is blank

I am working on a webapp, and the formatting of the one text field is working almost perfectly, however, the only thing that is happening I do not want to happen is when I click out of the field and there is no value, it returns NaN
HTML
<input type="text" class="rounded" name="sname" id="investamt" onblur="handleChange()"><br>
Javascript
var fnf = document.getElementById("investamt");
fnf.addEventListener('keyup', function(evt){
var n = parseInt(this.value.replace(/\D/g,''),10);
fnf.value = n.toLocaleString();
}, false);
function handleChange() {
var myValue = document.getElementById("investamt").value;
if (myValue.indexOf("$") != 0)
{
myValue = "$" + myValue;
}
document.getElementById("investamt").value = myValue;
}
Why is it returning NaN when I click out of the text field and it is blank, I would like it to return 0 instead, for example.
You can check the value and zero it out with if (isNaN(n)) n = 0;
var fnf = document.getElementById("investamt");
fnf.addEventListener('keyup', function(evt) {
var n = parseInt(this.value.replace(/\D/g, ''), 10);
if (isNaN(n)) n = 0;
fnf.value = n.toLocaleString();
}, false);
function handleChange() {
var myValue = document.getElementById("investamt").value;
if (myValue.indexOf("$") != 0) {
myValue = "$" + myValue;
}
document.getElementById("investamt").value = myValue;
}
<input type="text" class="rounded" name="sname" id="investamt" onblur="handleChange()"><br>
when you parse something empty string it will return NAN. try this on console:--
parseInt(''.replace(/\D/g,''),10)
try this code....
hope it will fill your requirments :)
var fnf = document.getElementById("investamt");
fnf.addEventListener('keyup', function(evt){
var n
n = this.value.replace(/\D/g,'')
fnf.value = n;
}, false);
function handleChange() {
var myValue = document.getElementById("investamt").value;
if(myValue.length === 0){ myValue = '0'}
if (myValue.indexOf("$") != 0)
{
myValue = "$" + myValue;
}
document.getElementById("investamt").value = myValue;
}
<input type="text" class="rounded" name="sname" id="investamt" onblur="handleChange()"><br>

How can I handle expression in text box depend upon check box in java script?

My question is if the check box is checked the value inserted inside the text box gives a square. If it is 3 inside the text box, after clicking on checkbox the result have to be 9 in text box.
Kindly resolve it using JavaScript and HTML only.
function myfun() {
var a = document.getElementById("checkedid");
var b;
var c = document.getElementById("txtbox");
if(a.checked == true){
alert("Value will be doubled");
b = c*c;
document.myform.txt.value = b;
return false;
}
}
<form name="myform">
TextBox<input type="text" value="" name="txt" id="txtbox">
<br/>
Check Box<input type="checkbox" name="checkbx" id="checkedid" onclick="myfun()">
</form>
Replace var c = document.getElementById("txtbox"); with var c = document.getElementById("txtbox").value;. You have to get the value of from the input.
function myfun() {
var a = document.getElementById("checkedid");
var b;
var c = document.getElementById("txtbox").value;
if(a.checked == true){
alert("Value will be doubled");
b = c*c;
document.myform.txt.value = b;
return false;
}
}
<form name="myform">
TextBox<input type="text" value="" name="txt" id="txtbox">
<br/>
Check Box<input type="checkbox" name="checkbx" id="checkedid" onclick="myfun()">
</form>
function myfun() {
var a = document.getElementById("checkedid");
var b;
var c = document.getElementById("txtbox");
if(a.checked == true){
var temp = c.value
b = temp * temp;
c.value = b;
return false;
}
}
<form name="myform">
TextBox<input type="text" value="" name="txt" id="txtbox">
<br/>
Check Box<input type="checkbox" name="checkbx" id="checkedid" onclick="myfun()">
</form>
Here you are getting elemnet from ID. You need to perform square operation on value not on element
Use
c.Value instead of only c
function myfun()
{
var a = document.getElementById("checkedid");
var c = document.getElementById("txtbox");
var b;
if(a.checked == true){
//Use c.Value not c
var temp = c.value;
b = temp * temp;
c.value = b;
return false;
}
}
This should work. The only assumption is that the textbox has a value.
function myFunc() {
var chk = document.getElementById("checkedid");
if (chk.checked == true) {
var x = parseInt(document.getElementById("txtbox").value);
var result = x * x;
document.myform.txt.value = result.toString();
return false;
}
}

How to add dynamic textbox in java script

I need to create text box using JavaScript. I coded as below:
<script>
function _(x) {
return document.getElementById(x);
}
function popuptxt() {
var i = _("no_room").value;
for(a = 1; a <= i; a++) {
my_div.innerHTML = my_div.innerHTML + "Room number for " + a + "<br><input type='text' name='mytext'+ i><br>"
}
}
<script>
HTML file:
<input type="text" style="width:200px;" id="no_room" onChange="popuptxt()" required>
<div id="my_div"></div>
It displays number of textbox when I type a number, but I need to clear them when I type another number.
Just reset the content of you block each time :
<script>
function _(x) {
return document.getElementById(x);
}
function popuptxt() {
my_div.innerHTML = "";
var i = _("no_room").value;
for(a = 1; a <= i; a++) {
my_div.innerHTML = my_div.innerHTML + "Room number for " + a + "<br><input type='text' name='mytext'+ i><br>"
}
}
</script>
Just add my_div.innerHTML = ""; before the for loop in popuptxt(). That way it will be cleared each time its called.

how to get dynamic id of dynamically created textbox in jquery

i want to perform keyup event via textbox id, and all textbox are dynamically created with onclick button event. for this i have to make 20 keyup function. if i use 20 keyup function then my code will become too lengthy and complex. instead of this i want to use a common function for all textbox. can anybody suggest me how to do it..thanks
here is what i am doing to solve it:
<div class="input_fields_wrap">
<button class="add_field_button">Add Booking</button></div>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
var counter = 2;
$(".add_field_button").click(function() {
if (counter > 10) {
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<div id="target"><label>Textbox #' + counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="firsttextbox' + counter + '" value="" > <input type="text" name="textbox' + counter +
'" id="secondtextbox' + counter + '" value="" > Remove<input type="text" id="box' + counter + '" value="">sum</div>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
function check(a, b) {
var first = a;
var second = b;
var temp = temp;
var novalue = "";
result = parseInt(first) + parseInt(second);
if (!isNaN(result)) {
return result;
} else {
return novalue;
}
}
$(this).on("keyup", "#firsttextbox2", function(e) {
e.preventDefault();
var a = document.getElementById('firsttextbox2').value;
var b = document.getElementById('secondtextbox2').value;
var number = 2;
result = check(a, b);
document.getElementById('box2').value = result;
});
$(this).on("keyup", "#firsttextbox3", function(e) {
var number = 3;
e.preventDefault();
var a = document.getElementById('firsttextbox3').value;
var b = document.getElementById('secondtextbox3').value;
result = check(a, b);
document.getElementById('box3').value = result;
});
$(this).on("keyup", "#firsttextbox4", function(e) {
var number = 4;
e.preventDefault();
var a = document.getElementById('firsttextbox4').value;
var b = document.getElementById('secondtextbox4').value;
result = check(a, b);
final = document.getElementById('box4').value = result;
});
$(this).on("keyup", "#secondtextbox2", function(e) {
e.preventDefault();
var a = document.getElementById('firsttextbox2').value;
var b = document.getElementById('secondtextbox2').value;
result = check(a, b);
document.getElementById('box2').value = result;
});
$(this).on("keyup", "#secondtextbox3", function(e) {
e.preventDefault();
var a = document.getElementById('firsttextbox3').value;
var b = document.getElementById('secondtextbox3').value;
result = check(a, b);
document.getElementById('box3').value = result;
});
$(this).on("keyup", "#secondtextbox4", function(e) {
e.preventDefault();
var a = document.getElementById('firsttextbox4').value;
var b = document.getElementById('secondtextbox4').value;
result = check(a, b);
document.getElementById('box4').value = result;
});
$(this).on("click", "#remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('#target').remove();
counter--;
});
});
</script>
See the snippet below to see how you can make this implementation more modular and useable. The trick is to think: what do I want to do? I want to be able to add multiple inputs and add their value, printing the result in another input.
It comes down to using classes - since we are going to use the same kind of thing for every row. Then apply something that works for all classes. No IDs whatsoever! You can even use the name property of the input that contains the value you want to save. Using the [] in that property will even pass you back a nice array when POSTING!
I know this looks like a daunting lot, but remove my comments and the number of lines reduces dramatically and this kind of code is almost infinitely extendable and reusable.
But have a look, this works and its simple and - most of all - it's DRY (don't repeat yourself 0 once you do, re-evaluate as there should be a better way!)!
Update
You could also use a <ol>as a wrapper and then add an <li> to this every time, so you get automatic counting of boxes in the front end without any effort from your end! Actually, thats so nice for this that I have changed my implementation.
var add = $('#add_boxes');
var all = $('#boxes');
var amountOfInputs = 2;
var maximumBoxes = 10;
add.click(function(event){
// create a limit
if($(".box").length >= maximumBoxes){
alert("You cannot have more than 10 boxes!");
return;
}
var listItem = $('<li class="box"></li>');
// we will add 2 boxes here, but we can modify this in the amountOfBoxes value
for(var i = 0; i < amountOfInputs; i++){
listItem.append('<input type="text" class="input" />');
}
listItem.append('<input type="text" class="output" name="value" />');
// Lets add a link to remove this group as well, with a removeGroup class
listItem.append('<input type="button" value="Remove" class="removeGroup" />')
listItem.appendTo(all);
});
// This will tie in ANY input you add to the page. I have added them with the class `input`, but you can use any class you want, as long as you target it correctly.
$(document).on("keyup", "input.input", function(event){
// Get the group
var group = $(this).parent();
// Get the children (all that arent the .output input)
var children = group.children("input:not(.output)");
// Get the input where you want to print the output
var output = group.children(".output");
// Set a value
var value = 0;
// Here we will run through every input and add its value
children.each(function(){
// Add the value of every box. If parseInt fails, add 0.
value += parseInt(this.value) || 0;
});
// Print the output value
output.val(value);
});
// Lets implement your remove field option by removing the groups parent div on click
$(document).on("click", ".removeGroup", function(event){
event.preventDefault();
$(this).parent(".box").remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<ol id="boxes">
</ol>
<input type="button" value="Add a row" id="add_boxes" />
You can target all your textboxes, present or future, whatever their number, with a simple function like this :
$(document).on("keyup", "input[type=text]", function(){
var $textbox = $(this);
console.log($textbox.val());
})
$("button").click(function(){
$("#container").append('<input type="text" /><br>');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<input type="text" /><br>
<input type="text" /><br>
<input type="text" /><br>
</div>
<button>Create one more</button>
You don't need complicated generated IDs, not necessarily a class (except if you have other input[type=text] you don't want to conflict with). And you don't need to duplicate your code and write 20 times the same function. Ever. If you're duplicating code, you're doing wrong.
Add classes "a" and "b" to the textboxes and "box" to the box. Then add data-idx attribute with the index (unused!?). Finally register the event handlers:
$('.a').on('keyup', function(e){
e.preventDefault();
var $this = $(this)
var $p = $this.parent()
var a= this.value;
var b= $p.find('.b').val()
var number =$this.data('idx') //unused!?
var result = check(a,b)
$p.find('.box').val(result)
})
$('.b').on('keyup', function(e){
e.preventDefault();
var $this = $(this)
var $p = $this.parent()
var a= $p.find('.a').val()
var b= this.value
var result = check(a,b)
$p.find('.box').val(result)
})
Or a general one:
$('.a,.b').on('keyup', function(e){
e.preventDefault();
var $p = $(this).parent()
var a= $p.find('.a').val()
var b= $p.find('.b').val()
var result = check(a,b)
$p.find('.box').val(result)
})
You can assign a class to all textboxes on which you want to perform keyup event and than using this class you can attach the event on elements which have that class. Here is an example
var html="";
for (var i = 0; i < 20; i++)
{
html += "<input type='text' id='txt" + i + "' class='someClass' />";
}
$("#testDiv").html(html);
Attach keyup event on elements which have class someClass.
$(".someClass").keyup(function () {
alert($(this).attr("id"));
});
A little helper to combine with your favorite answer:
var uid = function () {
var id = 0;
return function () {
return ++id;
};
}();
Usage:
uid(); // 1
uid(); // 2
uid(); // 3
Providing a code-snippet which may give you some hint:
$(".add_field_button").click(function ()
{
if (counter > 10)
{
alert("Only 10 textboxes allow");
return false;
}
var txtBoxDiv = $("<div id='TextBoxDiv"+counter+"' style='float:left;width:10%; position:relative; margin-left:5px;' align='center'></div>");
//creating the risk weight
var txtBox1 = $('<input />',
{
'id' : 'fst_textbox_' + counter,
'name' : 'textbox'+counter,
'type' : 'text',
'class' : 'input_field',
'onClick' : 'txtBoxFun(this,'+counter+')'
});
var txtBox2 = $('<input />',
{
'id' : 'sec_textbox_' + counter,
'name' : 'textbox'+counter,
'type' : 'text',
'class' : 'input_field',
'onClick' : 'txtBoxFun(this,'+counter+')'
});
var txtBox3 = $('<input />',
{
'id' : 'sum_textbox_' + counter,
'name' : 'textbox'+counter,
'type' : 'text',
'class' : 'input_field',
});
$(txtBoxDiv).append(txtBox1).append(txtBox2);
$(txtBoxDiv).append(txtBox3);
});
function txtBoxFun(obj, count)
{
var idGet = $(obj).attr('id');
var idArr = new Array();
idArr = idGet.split("_");
if(idArr[0] == "fst")
{
var sumTxt = parseInt(parseInt($(obj).val()) + parseInt($("#sec_textbox_"+count).val()));
}
else if(idArr[0] == "sec")
{
var sumTxt = parseInt(parseInt($(obj).val()) + parseInt($("#fst_textbox_"+count).val()));
}
$("#sum_textbox_"+count).val(sumTxt);
}

Limiting character in textbox input

please be nice. I'm trying to create a page which sets limit and cut the excess (from the specified limit). Example: Limit is 3. then, I'll input abc if I input d it must say that its limit is reached and the abc will remain. My problem is that it just delete my previous input and make new inputs. Hoping for your great cooperation. Thanks.
<html>
<script type="text/javascript">
function disable_btn_limit(btn_name)
{
/* this function is used to disable and enable buttons and textbox*/
if(btn_name == "btn_limit")
{
document.getElementById("btn_limit").disabled = true;
document.getElementById("ctr_limit_txt").disabled = true;
document.getElementById("btn_edit_limit").disabled = false;
}
if(btn_name == "btn_edit_limit")
{
document.getElementById("btn_limit").disabled = false;
document.getElementById("ctr_limit_txt").disabled = false;
document.getElementById("btn_edit_limit").disabled = true;
}
}
function check_content(txtarea_content)
{
/*This function is used to check the content*/
// initialize an array
var txtArr = new Array();
//array assignment
//.split(delimiter) function of JS is used to separate
//values according to groups; delimiter can be ;,| and etc
txtArr = txtarea_content.split("");
var newcontent = "";
var momo = new Array();
var trimmedcontent = "";
var re = 0;
var etoits;
var etoits2;
//for..in is a looping statement for Arrays in JS. This is similar to foreach in C#
//Syntax: for(index in arr_containter) {}
for(ind_val in txtArr)
{
var bool_check = check_if_Number(txtArr[ind_val])
if(bool_check == true)
{
//DO NOTHING
}
else
{
//trim_content(newcontent);
newcontent += txtArr[ind_val];
momo[ind_val] = txtArr[ind_val];
}
}
var isapa = new Array();
var s;
re = trim_content(newcontent);
for(var x = 0; x < re - 1; x++){
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}
}
function trim_content(ContentVal)
{
//This function is used to determine length of content
//parseInt(value) is used to change String values to Integer data types.
//Please note that all value coming from diplay are all in String data Type
var limit_char =parseInt(document.getElementById("ctr_limit_txt").value);
var eto;
if(ContentVal.length > (limit_char-1))
{
alert("Length is greater than the value specified above: " +limit_char);
eto = limit_char ;
etoits = document.getElementById("txtarea_content").value;
//document.getElementById("txtarea_content").value = "etoits";
return eto;
//for(var me = 0; me < limit_char; me++)
//{document.getElementById("txtarea_content").value = "";}
}
return 0;
}
function check_if_Number(ContentVal)
{
//This function is used to check if a value is a number or not
//isNaN, case sensitive, JS function used to determine if the values are
//numbers or not. TRUE = not a number, FALSE = number
if(isNaN(ContentVal))
{
return false;
}
else
{ alert("Input characters only!");
return true;
}
}
</script>
<table>
<tr>
<td>
<input type="text" name="ctr_limit_txt" id="ctr_limit_txt"/>
</td>
<td>
<input type="button" name="btn_limit" id="btn_limit" value="Set Limit" onClick="javascript:disable_btn_limit('btn_limit');"/>
</td>
<td>
<input type="button" name="btn_edit_limit" id="btn_edit_limit" value="Edit Limit" disabled="true" onClick="javascript:disable_btn_limit('btn_edit_limit');"/>
</td>
</tr>
<tr>
<td colspan="2">
<textarea name="txtarea_content" id="txtarea_content" onKeyPress="javascript:check_content(this.value);"></textarea>
<br>
*Please note that you cannot include <br>numbers inside the text area
</td>
</tr>
</html>
Try this. If the condition is satisfied return true, otherwise return false.
<html>
<head>
<script type="text/javascript">
function check_content(){
var text = document.getElementById("txtarea_content").value;
if(text.length >= 3){
alert('Length should not be greater than 3');
return false;
} else {
return true;
}
}
</script>
</head>
<body>
<div>
<textarea name="txtarea_content" id="txtarea_content" onkeypress=" return check_content();"></textarea>
</div>
</body>
</html>
Instead of removing the extra character from the text area, you can prevent the character from being written in the first place
function check_content(event) { //PARAMETER is the event NOT the content
txtarea_content = document.getElementById("txtarea_content").value; //Get the content
[...]
re = trim_content(newcontent);
if (re > 0) {
event.preventDefault(); // in case the content exceeds the limit, prevent defaultaction ie write the extra character
}
/*for (var x = 0; x < re - 1; x++) {
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}*/
}
And in the HTML (parameter is the event):
<textarea ... onKeyPress="javascript:check_content(event);"></textarea>
Try replacing with this:
for(var x = 0; x < re - 6; x++){
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}
Any reason why the maxlength attribute on a text input wouldn't work for so few characters? In your case, you would have:
<input type="text" maxlength="3" />
or if HTML5, you could still use a textarea:
<textarea maxlength="3"> ...
And then just have a label that indicates a three-character limit on any input.

Categories