Adding new text box using javascript - javascript

I have a webpage. There is a button called add. When this add button is clicked then 1 text box must be added. This should happen at client side only.
I want to allow the user to add at most 10 text boxes.
How can I achieve it using javascript?
example:
only 1 text box is displayed
user click add >
2 text boxes displayed
user clicks add >
I also wants to provide a button called "remove" by which the user can remove the extra text box
Can anyone provide me a javascript code for this??

Untested, but this should work (assuming an element with the right id exists);
var add_input = function () {
var count = 0;
return function add_input() {
count++;
if (count >= 10) {
return false;
}
var input = document.createElement('input');
input.name = 'generated_input';
document.getElementbyId('inputs_contained').appendChild(input);
}
}();
add_input();
add_input();
add_input();

A solution using the jQuery framework:
<form>
<ul class="addedfields">
<li><input type="text" name="field[]" class="textbox" />
<input type="button" class="removebutton" value="remove"/></li>
</ul>
<input type="button" class="addbutton" value="add"/>
</form>
The jQuery script code:
$(function(){
$(".addbutton").click(){
if(".addedfields").length < 10){
$(".addedfields").append(
'<li><input type="text" name="field[]" class="textbox" />' +
'<input type="button" class="removebutton" value="remove"/></li>'
);
}
}
// live event will automatically be attached to every new remove button
$(".removebutton").live("click",function(){
$(this).parent().remove();
});
});
Note: I did not test the code.
Edit: changed faulty quotation marks

I hope you are using jQuery.
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript"><!--
$(document).ready(function(){
var counter = 2;
$("#add").click(function () {
if(counter==11){
alert("Too many boxes");
return false;
}
$("#textBoxes").html($("#textBoxes").html() + "<div id='d"+counter+"' ><label for='t2'> Textbox "+counter+"</label><input type='textbox' id='t"+counter+"' > </div>\n");
++counter;
});
$("#remove").click(function () {
if(counter==1){
alert("Can u see any boxes");
return false;
}
--counter;
$("#d"+counter).remove();
});
});
// --></script>
</head><body>
<div id='textBoxes'>
<div id='d1' ><label for="t1"> Textbox 1</label><input type='textbox' id='t1' ></div>
</div>
<input type='button' value='add' id='add'>
<input type='button' value='remove' id='remove'>

Related

Show element in JavaScript by onkeypress function

I'm trying to show save button only if input gets value,
The issue is if i use append for each input i get 1 button printed, what I'm looking for is regardless of input length get the button only once.
The important is input not be empty that's all.
Code
<input class="text_dec form-control" type="text" onkeypress="myFunction()" name="text_dec[]" id="'+ textFieldsCount.toString() +'">
function myFunction() {
$('#moreless').append("button here");
}
any idea?
Instead of keypress, use keyup, this will call the listener just when the key is released, so you will have the correct length of the input value. With that, you can check if the button must be displayed or not.
Also, I would have another check to make sure that input have some value on it to save when clicked.
Like below, take a look:
$(function(){
$('.myInput').on('keyup', function(){
var btnElem = $('.myButton');
var charLength = this.value.length;
if (charLength > 0){
btnElem.show();
}else {
btnElem.hide();
}
});
$(".myButton").on("click", function(){
if ($('.myInput').val().trim().length < 1){
alert("Input is empty")
return;
}
//Do your code
});
});
.myButton {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input class="myInput" type="text" value="">
<input class="myButton" type="button" value="Save Button" />
</body>
EDIT
Now, if you really need to make as you were doing before (I don't consider it a best practice and also recommend you to rethink if you really wanna go through this) here goes a code that will help you. Click to show.
Here I added the functions and created the button element (if necessary) then append it to DOM just when the input have some value length.
function myFunction(input){
var btnElem = $(".mySaveButton")[0];
if (!btnElem){
btnElem = document.createElement("button");
btnElem.textContent = "Save Button";
btnElem.onclick = btnClicked;
btnElem.className = "mySaveButton";
}
var charLength = input.value.length;
if (charLength > 0){
document.body.append(btnElem);
}else {
btnElem.remove();
}
};
function btnClicked(){
if ($('.myInput').val().trim().length < 1){
alert("Input is empty")
return;
}
//Do your code
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input class="myInput" type="text" value="" onkeyup="myFunction(this)">
</body>
So I think you just want a button to show to the user once they type something in the text box. If that's the case, then you don't really want to append a button every time they press a key in the box.
Instead I'd make a button and set its css to display none and then when they keydown in the text box change the button's css to display block.
Something like this: http://jsfiddle.net/wug1bmse/10/
<body>
<input type="text">
<input class="myButton" type="button" value="button text" />
</body>
.myButton {
display: none;
}
$(function(){
$('input').on('keypress',function(){
var htmlElement= $('.myButton');
htmlElement.css('display', 'block');
});
});
Hiding the element with a class might be easier:
.btn-hidden {
display: none;
}
<input id="save-button" class="btn-hidden" type="button" value="save" />
function showSave() {
$('#save-button').removeClass('btn-hidden');
}
function hideSave() {
$('#save-button').addClass('btn-hidden');
}

Add Radio buttons to Html form using Javascript or Jquery

In my HTML code I have
<form id="approve">
<input name="myDate" id="monthYearPicker" />
<button type="button"onclick="monthlytimesheets()">Submit</button>
</form>
In my Javascript file I have the following:-
function monthlytimesheets() {
$.post('http://localhost:8000/timer/monthly_timesheet/',
function(returnedData) {
for(i=0;i<returnedData.length;i++) {
for(j=i+1;j<returnedData.length;j++) {
if(returnedData[i]['id']==returnedData[j]['id']) {
returnedData.splice(j,1)
}
}
}
});
Now i want my returnedData[i]['full_name'] rendered on html page as radio buttons. How can i do that. How do you dynamically create radio buttons from JS? Also can i assign values to these radio buttons?
you can create radio buttons easily using jquery as you want. I wrote a code to show how to create radio button dynamically. automatically and when a button clicked.change the inside conditions as your needs. try below code.
<html>
<head></head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<body>
<!-- Example one , add radio button using jquery automatically-->
<h1>Example one , add radio button using jquery automatically</h1>
<form id="approve">
<input name="myDate" id="monthYearPicker" />
<div class="lastone"></div>
</form>
<br><br><hr>
<!-- Example two, add radio button using jquery when button click-->
<h1>Example two, add radio button using jquery when button click-</h1>
<form id="approveone">
<input name="myDate" id="monthYearPicker" />
<div class="lasttwo"></div>
<input type="button" id="addradio" value="submit">
</form>
</body>
<script type="text/javascript">
$(document).ready(function(){
for(var i=0;i<5;i++)
{
var labelname = "radio button"+i;
var value = i;
var create = $('<input type="radio" value="'+value+'"><label>'+labelname+'</label><br>');
$(".lastone").append(create);
}
});
$(document).ready(function(){
$("#addradio").click(function(){
for(var i=0;i<9;i++)
{
var labelname = "radio button"+i;
var value = i;
var create = $('<input type="radio" value="'+value+'"><label>'+labelname+'</label><br>');
$(".lasttwo").append(create);
}
});
});
</script>
</html>
You can create elements dynamically like this
var content = document.createElement('div');
var newElement = document.createElement('input');
newElement.setAttribute('type', 'radio');
newElement.value = "Your value"; ///Here you can assigned value to the radio button
content.appendChild(newElement);
Create a function that returns a radio element. Similar question was already asked.
It can be found here: How do you dynamically create a radio button in Javascript that works in all browsers?
function createRadioElement(name, checked) {
var radioHtml = '<input type="radio" name="' + name + '"';
if ( checked ) {
radioHtml += ' checked="checked"';
}
radioHtml += '/>';
var radioFragment = document.createElement('div');
radioFragment.innerHTML = radioHtml;
return radioFragment.firstChild;
}
Note that this is the snipped from the answer of the posted link, published by Prestaul.
Would have postet it as comment, but need 50rep to comment...
function monthlytimesheets()
{
var name = $('#monthYearPicker').val();
$('#approve').append('<input type="radio" />'+name);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form id="approve">
<input name="myDate" id="monthYearPicker" />
<button type="button"onclick="monthlytimesheets()">Submit</button>
</form>

Pass a value from button to input value

I am trying to pass a value from a button to an input value with Javascript.
What i have right now is this
this inside a javascript file
var test2 = 5;
appendeddatahtml = '<div class="test1"><button id="btn" type="button" value="' + test2 + '">This is it!</button></div>';
$("#test1").append(appendeddatahtml);
And this is the form above the script
<input type="text" name="latlon" id="latlon" style="display: none; " value="" />
First i tried to make an alert with this code
$(document).ready(function() {
$("#btn").click(function() {
alert("The button was clicked.");
});
});
But it didn't alerted anything.
Is there any way to pass the value from the button to the input value?
Since you are adding it dynamically you need event delegation here. So just add click as below:
$(document).on('click',"#btn",function(){
alert("The button was clicked.");
});
DEMO Here
It seems you have created the button dynamically via code during runtime and for such elements you need to use live or on events
http://api.jquery.com/on/
this one will help
example:
$(document).ready(function() {
$(document).on('click', "#btn", function() {
alert('here');
});
});
working here just remove $(document).ready()
var test2 = 5 ;
appendeddatahtml = '<div class="test1"><button id="btn" type="button" value="'+test2+'">This is it!</button></div>';
$("#test1").append(appendeddatahtml);
$("#btn").click(function(){
alert("The button was clicked.");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="latlon" id="latlon" style="display: none; " value="" />
<div id="test1"></div>
You have not created the element first.
You forgot $();
var test2 = 5 ;
appendeddatahtml = $('<div class="test1"><button id="btn" type="button" value="'+test2+'">This is it!</button></div>');
$("#test1").append(appendeddatahtml);
link to a working example of what you wanted is here
html code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="latlon" id="latlon" style="display: block; " value="" />
<div id="test1">
</div>
javascript code
$(document).ready(function() {
var test2 = 5 ;
var appendeddatahtml = '<div class="test1"><button id="btn" type="button" value="'+test2+'">This is it!</button></div>';
$("#test1").append(appendeddatahtml);
$("#btn").click(function(){
alert("The button was clicked. "+this.value);
document.getElementById('latlon').value = this.value;
});
});

delete dynamically created textbox

I have the following code which I use to add text-boxes dynamically on click of button. It works.
<div id="forms" name="forms">
<input name="winner[]" type="text" id="tag" size="20"/><br/>
</div>
<input type="button" name="addmore" id="addmore" value="Add More Winners" onclick="addForm()"/>
The javascript for the above code is:
function addForm() {
$("#forms").append(
"<input type ='text' class='winner' name='winner[]'><br/>");
$(".winner").autocomplete("autocomplete.php", {
selectFirst: true
});
}
I am using auto complete to get data from database in the text-box
What I want is - suppose if a user clicks on add more winner button but does not want to add any data in the textbox, I should give him a button to delete the extra text-box.
How should the JavaScript be written for this?
Do see my above code
var i=0;
function addForm() {
i++;
$("#forms").append(
"<input type ='text' id='input_'"+i+" class='winner' name='winner[]'><button onclick='delete('"+i+"')' id='button_'"+i+">delete</button><br/>");
$(".winner").autocomplete("autocomplete.php", {
selectFirst: true
});
function delete(i)
{
$("#input_"+i).remove();
$("#button_"+i).remove();
}
simply use a counter to set an ID to inputs and buttons and send that counter to delete function;
Simply use the code below :
$("#forms").append("<p><input type ='text' class='winner' name='winner[]' ><button onclick='$(this).parent().remove()'>delete</button></p>");
Try this function.
function removeElement()
{
if(intTextBox != 0)
{
var contentID = document.getElementById('content');
contentID.removeChild(document.getElementById('strText'+intTextBox));
intTextBox = intTextBox-1;
}
}
Try adding a remove button while adding a text box dynamically to remove the text box if necessary
Here is the html code
<div id="forms" name="forms">
<input name="winner[]" type="text" id="tag" size="20"/><br/>
</div>
<input type="button" name="addmore" id="addmore" value="Add More Winners" />
Here is the jQuery code
$('#addmore').click(function () {
$('#forms').append('<input type ="text" class="winner" name="winner[]"><input type="button" onclick="$(this).prev().remove();$(this).remove();">');
});
Here is the demo

check inputfields on pageload and manipulate with jquery

When I press ADD, I show the hidden #box, I hide the ADD button and show the REMOVE button.
html:
<input type="button" id="add" value="ADD">
<input type="button" class="no-display" id="remove" value="REMOVE">
<div class="no-display" id="box">
<input id="a" value="" type="text" />
<input id="b" value="" type="text" />
<input id="c" value="" type="text" />
</div>
jquery:
$('#add,#remove').click(function () {
$('#add').toggle();
$('#remove').toggle();
$('#box').slideToggle("fast");
});
see working DEMO
Now, I want to check if the input fields #a or #b or #c have a value. If they have a value, on pageload I want to show #box, hide the #add button and show the #remove button.
What is the best way to do this?
you can see a DEMO here (not finished)
using filter() to get the count of the input that has value on it... if count is greater that 0 ..means atleast one input is not empty so.. hide add, show remove buttons and the container
try this
$('#add,#remove').click(function () {
$('#add').toggle();
$('#remove').toggle();
$('#box').slideToggle("fast");
});
var count = $('#a,#b,#c').filter(function () {
return $(this).val().length > 0;
}).length;
if (count > 0) {
$('#box').show();
$('#add').hide();
$('#remove').show();
}
updated as per comment
var count = $('#a,#b,#c').filter(function () {
return this.value.length > 0; //faster
}).length;
working fiddle
Try this: Move toggle code to a function. Bind it to the click. Call it on load if any of the inputs have a value.
$(function () {
var toggleBox = function () {
$('#add').toggle();
$('#remove').toggle();
$('#box').slideToggle("fast");
};
$('#add,#remove').click(toggleBox);
if(!!$("#a, #b, #c").filter(function() {return this.value;}).length) {
toggleBox();
}
});

Categories

Resources