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

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>

Related

Adding div on click only once and allowing customer to delete it and reclick it

I'm trying to make a button that when clicked displays only one div. If the user chooses they can click on the remove button and the data in any fields will be cleared and the text inside the div deleted. If a user chooses they can click the button again to bring back the div but cannot create the div more than once. I can make the initial div appear like its suppose to but beyond that I'm stuck.
Here is a list of things I've tried
$(document).on('click', '.remove', function(){
$document.getElementById("demo") .remove('.innerHTML');
$(document).on('click', '.empty', function(){
$('#demo').empty();
});
});
var count = 0;
function myFunction() {
document.getElementById("demo").innerHTML = '<div id="formwrap2" class="test' + count + '" name="test' + count + '"><div id="ddd"><div id="driverinfo">Renters Info<button type="button" name="remove" id="test2" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus">Remove Renters</span></button></div><div id="formwrap"><div id="ftx1">APT OR UNIT:</div><section class="plan cf"><input type="radio" name="aptorunit' + count + '" id="Apt' + count + '" value="Apt"><label class="free-label four col" for="Apt' + count + '">Apt</label><input type="radio" name="aptorunit' + count + '" id="Unit' + count + '" value="Unit" ><label class="basic-label four col" for="Unit' + count + '">Unit</label></section></div><div id="formwrap"><div id="ftx1">COVERAGE :</div> <input type="text" id="addy" name="propcover" size="" maxlength="15" placeholder="10k to 100k"/></div></div><br><br><br></div>';
}
$(document).on('click', '.empty', function() {
$('#demo').empty();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Add Renters</button>
<p id="demo"></p>
</body>
</html>
You're close check those steps to achieve what you want :
Add type="button" to your button to prevent the submit when you click.
Remove the inline onClick attribute and attach the click event from the JS code.
Check inside myFunction() function if the demo is empty or not before adding the content.
Attach another click event using event delegation on() (since the element was added dynamically to the DOM) to the button with .remove class to remove the content.
NOTE : Since you're using jQuery prevent the mix with vanillaJS like this line :
document.getElementById("demo").innerHTML = ...
Will be better to be :
demo.html(...)
$('button').on('click', myFunction);
$('body').on('click', '.remove', function() {
$('#demo').empty();
});
function myFunction() {
var demo = $('#demo');
if (!demo.html().length) {
demo.html('<div id="formwrap2" class="test' + count + '" name="test' + count + '"><div id="ddd"><div id="driverinfo">Renters Info<button type="button" name="remove" id="test2" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus">Remove Renters</span></button></div><div id="formwrap"><div id="ftx1">APT OR UNIT:</div><section class="plan cf"><input type="radio" name="aptorunit' + count + '" id="Apt' + count + '" value="Apt"><label class="free-label four col" for="Apt' + count + '">Apt</label><input type="radio" name="aptorunit' + count + '" id="Unit' + count + '" value="Unit" ><label class="basic-label four col" for="Unit' + count + '">Unit</label></section></div><div id="formwrap"><div id="ftx1">COVERAGE :</div> <input type="text" id="addy" name="propcover" size="" maxlength="15" placeholder="10k to 100k"/></div></div><br><br><br></div>');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<body>
<button type="button">Add Renters</button>
<p id="demo"></p>
</body>
</html>

How to get the name of a button pressed in Javascript?

I have 2 <div>s of at least 81 buttons, all with the same class, but they have different ids and names. I am trying to figure out how to alert the name of the current button that was being pressed.
function runMe(e){
return function(){
console.log(e.getAttribute("id"));
}
}
var eles = document.getElementsByClassName("myButton")
Array.prototype.forEach.call(eles,function(ele){
ele.onclick = runMe(ele);
})
<button id="a1" class="myButton">A1</button>
<button id="b2" class="myButton">B2</button>
Get all the buttons with the same class name and assign the click event listener to each buttons so that when you click the button the listener is invoked:
function btnClick(){
console.log(this.id + " " + this.name);
}
var allButtons = document.getElementsByClassName('myButton');
for(i=0; i<allButtons.length; i++){
allButtons[i].addEventListener('click', btnClick);
}
<button id="1" class="myButton" name='name1'>B1</button>
<button id="2" class="myButton" name='name2'>B2</button>
<button id="3" class="myButton" name='name3'>B2</button>
<button id="4" class="myButton" name='name4'>B2</button>
<button id="5" class="myButton" name='name5'>B2</button>
You can try the following way by using this.name inside the click handler function:
var btns = document.querySelectorAll('button');
btns.forEach(function(btn){
btn.addEventListener('click', function(){
console.log('Name of the cliked button is:', this.name)
})
})
<div>
<button type="button" id="btn1" name="btnName1">Button 1</button>
<button type="button" id="btn2" name="btnName2">Button 2</button>
<!--------- More Buttons--------->
</div>
<div>
<!--------- More Buttons--------->
<button type="button" id="btn48" name="btnName48">Button 48</button>
<button type="button" id="btn49" name="btnName49">Button 49</button>
<button type="button" id="btn50" name="btnName50">Button 50</button>
<!--------- More Buttons--------->
</div>

Add input fields with JQuery not working

I am trying to create an input field dynamically, using JQuery. It works up to a point but then absolutely stops working, no error in console and I am confused, please help.
I will attach a snippet alongside the code so you can better understand what's happening.
I can't define the problem because I don't fully understand what's happening, but I can try:
When I create a color I also want to create a size under that color, it works for the first color but doesn't work for other colors. What am I doing wrong?
$(document).ready(function() {
$("#add-color").click(function() {
$("#color-input-house")
.html($("#color-input-house")
.html() + '<div class="form-group">' +
'<input type="text" class="form-control colors" placeholder="Color">' +
' <button type="button" class="add-size small btn btn-primary rounded form-control">Add Size</button>' +
' <button type="button" class="remove-size small btn btn-warning rounded form-control">Remove Size</button>' +
' <div class="size-input-house"></div></div>');
});
$("#remove-color").click(function() {
if ($(".colors").length !== 1) {
$(".add-size").last().remove();
$(".remove-size").last().remove();
$(".colors").last().remove();
}
});
$(".add-size").click(function() {
$(this)
.parent()
.find(".size-input-house")
.html($(".size-input-house")
.html() + '<div class="form-group">' +
'<input type="text" class="form-control sizes" placeholder="Size"></div>');
});
$(".remove-size").click(function() {
if ($(".sizes").length !== 1) {
$(".sizes").last().remove();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<input type="text" class="form-control colors" placeholder="Color">
<button type="button" class="add-size small btn btn-primary rounded form-control">Add Size</button>
<button type="button" class="remove-size small btn btn-warning rounded form-control">Remove Size</button>
<div class="size-input-house"></div>
</div>
<div id="color-input-house"></div>
<div class="form-group">
<div>
<button type="button" id="add-color" class="small btn btn-primary rounded form-control">Add Color</button>
<button type="button" id="remove-color" class="btn btn-warning rounded form-control">Remove Color</button>
</div>
</div>
when you add something with jquery and you want to apply click on them it is better to use following format in jquery:
$(document).on("click",".add-size",function(){
$(this)
.parent()
.find(".size-input-house")
.html($(".size-input-house")
.html()+'<div class="form-group">' +
'<input type="text" class="form-control sizes" placeholder="Size"></div>');
});
and the same way for another:
$(document).on("click",".remove-size",function(){
if($(".sizes").length !== 1){
$(".sizes").last().remove();
}
});
Here is the solution and a working code:
$(document).on("click","#add-color",function(){
$("#color-input-house")
.html($("#color-input-house")
.html()+'<div class="form-group">' +
'<input type="text" class="form-control colors" placeholder="Color">' +
' <button type="button" class="add-size small btn btn-primary rounded form-control">Add Size</button>' +
' <button type="button" class="remove-size small btn btn-warning rounded form-control">Remove Size</button>' +
' <div class="size-input-house"></div></div>');
});
$(document).on("click","#remove-color",function(){
if($(".colors").length !== 1){
$(".add-size").last().remove();
$(".remove-size").last().remove();
$(".colors").last().remove();
}
});
$(document).on("click",".add-size",function(){
$(this)
.parent()
.find(".size-input-house")
.html($(this)
.parent()
.find(".size-input-house")
.html()+'<div class="form-group">' +
'<input type="text" class="form-control sizes" placeholder="Size"></div>');
});
$(document).on("click",".remove-size",function(){
if($(".sizes").length !== 1){
$(".sizes").last().remove();
}
});
Notice the $(document).on("click","#add-color",function(){ changes throughout the code. Thanks to the genius who gave an answer above.

Issues with converting label to input field on button click

I have modified the answer in the post dicussed here.
In my application I have two buttons - edit and save. When clicked on edit, the labels get converted into input fields, where the user can edit the content and save.
Everything is working fine, but the problem is that when the user clicks on the edit button twice, the content in the input fields becomes blank, i.e. the <input> value becomes blank.
Please suggest me a fix for this. Where am I going wrong?
<div id="companyName">
<label class="text-cname"><b>#Html.DisplayFor(m => m.Company)</b></label>
</div>
<div class="row center-block">
<input type="submit" class="btn btn-success" value="Save" id="btnSave" />
<input type="button" id="edit" class="btn btn-primary" value="Edit" />
</div>
<script>
$(document).ready(function () {
$('#edit').click(function () {
// for company name
var companyName = $('.text-cname').text();
var lblCName = $('<input id="attrCName" type="text" value="' + companyName + '" />')
$('.text-cname').text('').append(lblCName);
lblCName.select();
});
$('#btnSave').click(function () {
var text = $('#attrCName').val();
$('#attrCName').parent().text(text);
$('#attrCName').remove();
});
});
</script>
You can use replaceWith() method to convert label to textarea.
$("#edit").click(function(){
var text = $("label").text();
$("label").replaceWith("<input value='"+text+"' />");
});
$("#save").click(function(){
var text = $("input ").val();
$("input ").replaceWith("<label>"+text+"</label>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="edit">Edit</button>
<button id="save">Save</button>
<br/><br/>
<label>Text</label>
The most simple fix would be to disable the edit button once you've clicked it, and enable it again after saving:
$(document).ready(function () {
$('#edit').click(function () {
$(this).prop('disabled', true);
/*for company name*/
var companyName = $('.text-cname').text();
var lblCName = $('<input id="attrCName" type="text" value="' + companyName + '" />')
$('.text-cname').text('').append(lblCName);
lblCName.select();
});
$('#btnSave').click(function () {
$('#edit').prop('disabled', false);
var text = $('#attrCName').val();
$('#attrCName').parent().text(text);
$('#attrCName').remove();
});
});
When you click the second time the value of companyName is empty, that's why the <input> value becomes blank. This is a very simple solution, but you lose the focus on edit box which is easy to fix.
$('#edit').click(function () {
/*for company name*/
var companyName = $('.text-cname').text();
var lblCName = $('<input id="attrCName" type="text" value="' + companyName + '" />');
if(companyName != "")
$('.text-cname').text('').append(lblCName);
lblCName.select();
});
Try This one
function EditContent(){
var companyName = $('.text-cname').text();
var lblCName = $('<input id="attrCName" type="text" value="' + companyName + '" />');
if (companyName != "") {
$('.text-cname').text('').append(lblCName);
}
lblCName.select();
}
function SaveContent(){
var text = $('#attrCName').val();
$('#attrCName').parent().text(text);
$('#attrCName').remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="companyName">
<label class="text-cname"><b>Company</b></label>
</div>
<div class="row center-block">
<input type="submit" class="btn btn-success" value="Save" id="btnSave" onclick="SaveContent()" />
<input type="button" id="edit" class="btn btn-primary" value="Edit" onclick="EditContent()" />
</div>

How to get focused textbox

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);
});
});

Categories