jQuery method to add a TextBox - javascript

UPDATED
I am new to jQuery but have been programming for about two years in C#. I wanted to create a jQuery method that would be used several times to add Textboxes. I thought that I create a jQuery function with parameters which I would set from the buttons when they get clicked. Here is my jQuery code, this wont necessarily work as I am a newbie but will definitely give a workflow of what I intended to achieve
$(document).ready(function () {
function add(someClass) {
var count = $("."+someClass).length;
if (count <= 20) {
var newTextBox = $(document.createElement('text'));
newTextBox.appendTo("."+ someClass+":last");
//$('.approvers:last').append($("<input type='text' value='' />"));
}
}
});
This is how I intend to call the function from a buttons onclick.
<input type="button" value="+" id="someId" class="someCssClass" onclick="addText('approvers')" />
I am doing this to avoid writing the same code to insert textboxes having different classes. Is this how it can be done? All I want is to add a new TextBox at the same time specifying its class from jquery.

Your code is a little off, try this:
<input type="button" value="+" id="someId" class="addButton" data-target-class="someClass"/>
<div class="someClass">
</div>
And the javascript:
$(document).ready(function(){
// Define a click handler for any input with the class addButton
$('input.addButton').click(function(){
// Extract the class that this input button is targeting
var target_class = $(this).attr('data-target-class');
// Add a textarea to that target
$("."+target_class).append("<textarea></textarea>");
});
});
Here is an example:
http://jsfiddle.net/1sfz4sda/

I tested below code and it works, do not put your function inside document.ready
DEMO : http://liveweave.com/RkHq5o
Here is the javascript
function addText(cssClass) {
var count = $("."+cssClass).length;
if (count <= 20) {
var newTextBox = $(document.createElement('textarea'));
newTextBox.appendTo("."+cssClass);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="button" value="+" id="someId" class="someCssClass" onclick="addText('approvers')" />
<div class="approvers"></div>

Related

How to store the values of different buttons separately in textbox on click event using Javascript?

I am working on a attendance module and this is the prototype of the code, but I have some errors.
As you can see there are dynamically generated buttons and they change colour on click event. I am also storing the value of the buttons in textboxes on click as I have to handle this data on backend with PhP, the error is that when I turn a button to green it's value goes into a textbox and when again i turn it red same value goes into another textbox also, which I don't want. So please help me in solving this problem by reducing the duplicacy of data or by providing a code of a different submit button which when clicked checks the color of all the buttons and stores the values in different textboxes respectively, one for red and one for green. Thanks in advance.
<html>
<head>
<title>Button click event</title>
</head>
<body>
<?php
for($i=0;$i<=10;$i++) {
?>
<button class="btnColorChange" id="<?php echo $i; ?>" style="background-color:#FF0000"><?php echo $i; ?></button>
<?php
}
?>
<div>
<input type="text" name="text1" id="textbox1" value=""/><br><br>
<input type="text" name="text2" id="textbox2" value=""/><br><br>
</div>
<script>
$(".btnColorChange").click(function(){
xyz = this.id
if(this.clicked){
$(this).css('background-color', '#FF0000');
const tb=document.querySelector("#textbox1");
tb.value=tb.value+","+xyz;
console.log(xyz)
this.clicked = false;
} else {
$(this).css('background-color', '#008000');
const tb2=document.querySelector("#textbox2");
tb2.value=tb2.value+","+xyz;
console.log(xyz)
this.clicked = true;
}
});
</script>
</body>
</html>
First, the below statement is wrong:
there are dynamically generated buttons...
When talking about "dynamic" elements, we talk about element that were not existing on page load. It's not the case here, since they were created before page load, on the server-side. Using a loop does not make them "dynamic".
To store clicked/unclicked ids, I suggest you to use some arrays for this.
As I understand it, you want all the "clicked" and "unclicked" ids separately.
The "never clicked" are ignored.
Using two arrays, you can store ids in the relevant group... And even sort them (optionnally).
And you can send those arrays straight to your backend... So the input elements would now be just for testing purposes.
See comments in code:
// Arrays to store ids
var clicked = [],
unclicked = [];
$(".btnColorChange").on("click",function(){
// useful for this demo
console.clear();
// Get the clicked element id
var this_id = this.id;
console.log("Clicked id: "+this_id);
// Toggle the classes (button colors)
$(this).toggleClass("clicked unclicked");
// Check if in array
var in_clicked = $.inArray(this_id,clicked);
var in_unclicked = $.inArray(this_id,unclicked);
//console.log(in_clicked+" "+in_unclicked)
// If clicked
if($(this).hasClass("clicked")){
if(in_clicked==-1){
clicked.push(this_id);
clicked.sort();
}
if(in_unclicked>-1){
unclicked.splice(in_unclicked,1);
}
}
// If unclicked
if($(this).hasClass("unclicked")){
if(in_unclicked==-1){
unclicked.push(this_id);
unclicked.sort();
}
if(in_clicked>-1){
clicked.splice(in_clicked,1);
}
}
// Show arrays content in console
console.log(clicked);
console.log(unclicked);
// Show the ids in inputs as a coma separated string
$("#textbox1").val(clicked.join(","));
$("#textbox2").val(unclicked.join(","));
});
.unclicked{
background-color: #FF0000;
}
.clicked{
background-color: #008000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btnColorChange unclicked" id="1">1</button>
<button class="btnColorChange unclicked" id="2">2</button>
<button class="btnColorChange unclicked" id="3">3</button>
<button class="btnColorChange unclicked" id="4">4</button>
<button class="btnColorChange unclicked" id="5">5</button>
<br>
<br>
<div>
<input type="text" name="text1" id="textbox1" value=""/><br><br>
<input type="text" name="text2" id="textbox2" value=""/><br><br>
</div>
Please run the snippet in full page mode, because of the console logs.
For more reading, the below demo uses the following methods:
.on()
.toggleClass()
$.inArray()
.hasClass()
.push()
.sort()
.splice
.val()
.join()
You certainly noticed that I used two CSS rules for the button colors, instead of inline style attributes.
CodePen
If i understood you well, you want for example the Button to handle updates of textbox1 on first click and update textbox2 on second click. You could do this.
$(".btnColorChange").on("click", function(){
var btn = $(this);
var id = btn.attr("id");
if(btn.hasClass('clicked')){
var textboxselected = $("#textbox1");
var backgroundColor = "#FF0000";
btn.removeClass('clicked');
}else{
var textboxselected = $("#textbox2");
var backgroundColor = "#008000";
btn.addClass('clicked');
}
btn.css("background-color", backgroundColor);
textboxselected.val(textboxselected.val()+id);
});
Suppose you want to update same textbox
$(".btnColorChange").on("click", function(){
var btn = $(this);
var id = btn.attr("id");
var textvalue = $("#textbox1").val();
if(btn.hasClass('clicked')){
var backgroundColor = "#FF0000";
btn.removeClass('clicked');
}else{
var backgroundColor = "#008000";
btn.addClass('clicked');
}
btn.css("background-color", backgroundColor);
$("#textbox1").val(textvalue);
});
Its untested but hopes it works for you.

How to add click listener to dynamically added button?

I'm adding a button dynamically by doing:
<input id="{Id}" type="submit" value="View">
{Id} is replaced at runtime with the record id.
I would like to have a function like:
function viewRecord(button) {
//Do something here...
}
How can I add a click listener to the button that corresponds to the correct button being clicked?
I've started learning jquery today and would like an answer that shows how it's implemented.
EDIT
Based on the answer below, I'm trying the following:
<td><input class="viewRecord" type="submit" value="View"></td>
$(".viewRecord").click(function () {
var $table = $('#table'),
var $tableBody = $table.find('tbody'),
var $text = $tableBody.closest('tr').attr('id');
alert($text);
});
However, no alert is being displayed.
Am I missing something?
use following code:
<div id="container">
<input id="{Id}" type="submit" value="View" class="dynamic-btn" />
</div>
(function($) {
var btnClick = function(){
var id = $(this).attr('id');
alert(id);
/*Do smth that you needed*/
};
$(function() {
$("#container").on("click", ".dynamic-btn", btnClick)
});
}(jQuery));
Two steps:
1) Find the input with:
var dynamicButton = document.getElementById('{Id}');
2) Add the click Event Listener with:
dynamicButton.addEventListener('click',function(){viewRecord(dynamicButton.id);},false);

Jquery multiple plus/minus script

I have multiple forms on a page and also multiple input boxes with plus/minus signs.
I'm having trouble to get those input boxes to work seperately. Probably because of some wrong/same id's or something like that or maybe a wrong setup of my code. The thing is I can't find my error in the code and I don't get any errors in my console.
What I have:
function quantity_change(way, id){
quantity = $('#product_amount_'+id).val();
if(way=='up'){
quantity++;
} else {
quantity--;
}
if(quantity<1){
quantity = 1;
}
if(quantity>10){
quantity = 10;
}
$('#product_amount_'+id).val(quantity);
}
And my html:
//row 1
<div class="amount"><input type="text" name="quantity" value="1" id="product_amount_1234"/></div>
<div class="change" data-id="1234">
+
-
</div>
//row 2
<div class="amount"><input type="text" name="quantity" value="1" id="product_amount_4321"/></div>
<div class="change" data-id="4321">
+
-
</div>
I thought something like this would do the trick but it doesn't :(
$(document).ready(function(){
$('.change a').click(function(){
var id = $(this).find('.change').data('id');
quantity_change(id)
});
});
Any help greatly appreciated!
You should use closest() method to get access to the parent div with class change, then you can read the data attribute id's value.
var id = $(this).closest('.change').data('id');
alert(id);
Since you are already binding the click event using unobutrusive javascript, you do not need the onclick code in your HTML markup.
Also your quantity_change method takes 2 parameters and using both, but you are passing only one. You may keep the value of way in HTML 5 data attributes on the anchor tag and read from that and pass that to your method.
<div class="change" data-id="1234">
+
-
</div>
So the corrected js code is
$(document).ready(function(){
$('.change a').click(function(e){
e.preventDefault();
var _this=$(this);
var id = _this.closest('.change').data('id');
var way= _this.data("way");
quantity_change(way,id)
});
});
Here is a working sample.

Delete button next to each array's value

I have a HTML-JavaScript script in which the user can insert data to a new array [] by using a form's text field and an insert button.
By pressing insert button, the user inserts the data typed into the array.
I have a function which prints all the values of the array into <p id="demo"></p> and runs itself every 100 milliseconds in order to be updated with the arrays values.
I also have a reset button to delete every array's value when clicked.
What I want to do is add a delete button next to each array's value in order to be easier for the user to delete the wrong value he inserted.
I am using this code to insert values and print them:
HTML:
<div align="center">
<form id="form1">
<input type="text" name="fname" id="fname" placeholder="Type here!">
</form>
<br>
<input type="button" id="Button Insert" onclick="myFunction()" value="Insert">
<input type="button" onclick="myFunction3()" value="Reset">
</div>
<p id="demo" align="center"></p>
JavaScript/JQuery:
var all_values =[];
function myFunction() {
var temp_val = $("#fname").val();
all_values.push(temp_val);
document.getElementById("form1").reset();
}
setInterval(function () {
$("#demo").html(all_values.join("<br>"));
}, 100);
function myFunction3() {
all_values.length = 0;
}
To be more specific I want something like these things: iOS example JSFiddle Example 1 JSFiddle Example 2.
Could you please help me? Thanks in advance.
I'd do it the other way around.
Remove setInterval as it's really bad way to do such things.
Remove white spaces from the id attribute (id="Button-Insert", not id="Button Insert")
Don't use onclick attributes. Instead, register click event handlers with jQuery
// caching is a good practice when you reffer to the same elements multiple times:
var all_values =[], demo = $("#demo"), form = $("#form1")[0], fname = $("#fname");
$('#Button-insert').click(function(){
var temp_val = fname.val();
all_values.push(temp_val);
// create delete button along with the value
demo.append('<p>'+temp_val+' <button value="'+temp_val+'" type="button" class="del-btn">Delete</button></p>');
form.reset();
});
$('#Button-reset').click(function(){
all_values = [];
demo.html('');
});
// event delegation for dynamic elements:
demo.on('click', '.del-btn', function(){
all_values.splice(all_values.indexOf($(this).val()), 1);
$(this).parent().remove();
});
JSFiddle
Simply create the delete buttons at the same time you create the table.
function loadvalues(){
var i, button;
$('#demo').empty();
for(i in all_values){
$('#demo').append(all_values[i]);
button = $('<button>',{'text':'Delete'}).click(function(){
all_values.splice(this,1);
loadvalues();
}.bind(i)).appendTo('#demo');
$('#demo').append('<br>');
}
}
Also you don't need to poll, you could simply add each one on demand with a function like this:
function addVal(){
var val = $("#fname").val(), i = all_values.length;
all_values.push(val);
$('#demo').append(val);
button = $('<button>',{'text':'Delete'}).click(function(){
all_values.splice(this,1);
loadvalues();
}.bind(i)).appendTo('#demo');
$('#demo').append('<br>');
}
I had some typos, the code works,
Check here:
http://codepen.io/anon/pen/QbvgpW

How can I get values from jQuery dialog box which has 2 text boxes? Can I store them in a JavaScript variable?

I have tried jQuery, but I am not able to get values from that dialog box.
Is there any way that I could store those values in a JavaScript variable (i.e., coming from jQuery dialog).
<div id="dialog-message2">
<center><p>
What percentage would you like to refund?</br>
<input type="text" id="per" name="per" > %
</p></center>
<center><p>
Reason: <input type="text" id="reason" name="reason" >
</p></center>
<br><center><input type="submit" id="proceed" name="proceed" value="PROCEED" style='width:60px;height:30px;background-color:#0066CC;color:#FFFAF0; -webkit-border-radius: 9px'></center>
</div>
Or is there any other method in JavaScript?
$(document).ready(function(){
$("#proceed").click(function(){
//using JQuery
var perValue = $("#per").val();
var reasonValue = $("#reason").val();
console.log(reasonValue);
console.log(perValue);
});
});
//using javascript
document.getElementById('proceed').onclick = Onclick;
function Onclick(){
var reasonValue = document.getElementById("reason").value;
var perValue = document.getElementById("per").value;
console.log(reasonValue);
console.log(perValue);
}
I have included Jquery and normal javascript based on the onlick function of the button. You can test it out on this: JsFiddle. You can check you console to see the output of the var values.
Is this what you're looking for?
var something = document.getElementById("yourIDhere").value;

Categories