Retrieving added jquery rows - javascript

I have a problem retrieving all the data inside the rows added by the user. I tried using my variable reclist to retrieve the records but it give me blanks.
The source code is as follows:
<script type="text/javascript">
$(document).ready(function(){
$('#btnAdd').live('click',function(){
var name = $('#txtName').val();
var name2 = $('#txtName2').val();
$("#tbNames tr:last").after("<tr><td>" + name + "</td><td>" + name2 + "</td><td><img src='delete.gif' class='delete' height='15' /></td></tr>");
});
$('#tbNames td img.delete').live('click',function(){
$(this).parent().parent().remove();
});
});
</script>
<input id="txtName" type="text" />
<input id="txtName2" type="text" />
<input id="btnAdd" type="button" value="Add" />
<table id="tbNames" >
<tr>
<td><b>Name</b></td>
<td><b>Name2</b></td>
<td><b>Delete</b></td>
</tr>
<tr>
<td>Bingo</td>
<td>Tingo</td>
<td><img src="Delete.gif" height="15" class="delete" /></td>
</tr>
</table>
<script type="text/javascript">
$(document).ready(function() {
$("#submit_app").button();
$("#submit_app").click(function() {
var reclist = $("#txtName").val();
console.log(reclist);
});
});
</script>
<input id="submit_app" type="button" style="height: 35px; width: 225px" value="Add New User" />
Please advise if I have miss any coding.

Try following code. Check this demo on jsFiddle.net. This will give you all the values inside td of your table.
$(document).ready(function() {
$('#btnAdd').live('click', function() {
var name = $('#txtName').val();
var name2 = $('#txtName2').val();
$("#tbNames tr:last").after("<tr><td>" + name + "</td><td>" + name2 + "</td><td><img src='delete.gif' class='delete' height='15' /></td></tr>");
});
$('#tbNames td img.delete').live('click', function() {
$(this).parent().parent().remove();
});
//$("#submit_app").button(); //Commented this line
$("#submit_app").click(function() {
var skipFirstRow = 0; //Skip first row
$("#tbNames tr").each(function() {
if (skipFirstRow++ == 0) return;
var skipLastColumn = 0;
$(this).children("td").each(function() {
if (skipLastColumn++ == 2) return;
alert($(this).html());
});
});
var reclist = $("#txtName").val();
console.log(reclist);
});
});
EDIT
Check this fiddle. In this you will get the values in two arrays.

$("#txtName") refers to the text box you declared in
<input id="txtName" type="text" />
Since you want to retrieve all the data that you have inserted into the table, you should be using $("td", "#tbNames") and retrieving their .text()
$("td", "#tbNames").each(function() {
console.log($(this).text());
});

You need to bind click event as live. Since normal bind will only bind events to element found on page rendering first time
Here is corrected part:
<script type="text/javascript">
$(document).ready(function() {
$("#submit_app").button();
$("#submit_app").live('click', function() {
var reclist = $("#txtName").val();
console.log(reclist);
});
});
</script>

You're submit button was't getting triggered
http://jsfiddle.net/gBHh2/

Related

jQuery how to use a remove elem to remove two text boxes

I'm writing a script that is used in order to add/remove text boxes on a form. The idea is that you input two data pieces, which each require a text box. I would like to remove both boxes with one "remove" button, but I'm not quite an expert in jQuery yet. Thank you for your help!
HTML/Script:
<form class="smart-green" method="POST" role="form" class="my-form" role="form" method="POST" >
<table class="materialstab" style="border:1px solid;" cellpadding="5">
<tr><td><p class="text-box"><label for="materials">Materials</label></p></td>
<td><p class="text-box"><label for="url">URL</label><a class="add-box" href="#">Add Material</a></p></td></tr>
</table>
<script type="text/javascript">
jQuery(document).ready(function() {
$('.smart-green .add-box').click(function() { //add box on click
var n = $('.text-box').length + 1;
var box_html = $('<tr><td><p class="text-box"><input class="materials" type="text" name="materials'+ n +'" value="" id="materials' + n + '" />Remove/*ideally I would remove this remove <a> element*/</p></td><td><p class="text-box"> <input type="text" name="url' + n + '" value="" id="url' + n + '" />Remove/*this <a> would delete both text boxes*/</p></td></tr>'); // HTML for boxes
box_html.hide();
$('.smart-green .materialstab tr:last').after(box_html);
box_html.fadeIn('slow');
return false;
});
$('.smart-green').on('click', '.remove-box', function(){ //remove box
$(this).parent().css( 'background-color', '#FF6C6C' );
$(this).parent().fadeOut("slow", function() {
$(this).remove();
$('.box-number').each(function(index){
$(this).text( index + 1 );
});
});
return false;
});
});
</script>
I'm using jQuery 3.1.1 if that helps at all
Just do it like this (cleaned up and modified jQuery):
jQuery(document).ready(function() {
$('.smart-green .add-box').click(function() { //add box on click
var n = $('.text-box').length + 1;
var box_html = $('<tr><td><p class="text-box"><input class="materials" type="text" name="materials'+ n +'" value="" id="materials' + n + '" /></p></td><td><p class="text-box"> <input type="text" name="url' + n + '" value="" id="url' + n + '" />Remove</p></td></tr>'); // HTML for boxes
box_html.hide();
$('.smart-green .materialstab tr:last').after(box_html);
box_html.fadeIn('slow');
return false;
});
$('.smart-green').on('click', '.remove-box', function(){ //remove box
$(this).parent().css( 'background-color', '#FF6C6C' );
$(this).parent().fadeOut("slow", function() {
$(this).parents('tr').remove();
$('.box-number').each(function(index){
$(this).text( index + 1 );
});
});
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="smart-green" method="POST" role="form" class="my-form" role="form" method="POST" >
<table class="materialstab" style="border:1px solid;" cellpadding="5">
<tr><td><p class="text-box"><label for="materials">Materials</label></p></td>
<td><p class="text-box"><label for="url">URL</label><a class="add-box" href="#">Add Material</a></p></td></tr>
</table></form>
Generally, you should surround whatever it is you want to hide with a div - we'll call the id of this div hide_div
When I have a button click event to hide something I use this code
$('#id_of_remove_button').on('click',function() {
$('#hide_div').css('display','none');
});
This way if you need to display it again, you can just do .css('display','initial');
Also surrounding it in a div is nice because you only have to hide one element and not one by one.
If you actually want to remove the HTML completely:
$('#id_of_remove_button').on('click',function() {
$('#hide_div').html(); // removes everything inside the div
});

Remove input field with span

I written this code for creating new input fields, and i need to somehow modify it so i can remove the fields. I tought about adding var counter to mySpan and then i make$(#removeBox).click(function() and there i can get an id of the input field i need to delete. But i cannot make span clickable, and when I try to do it with like this <a class="deleteBox' + counter'"><span class="glyphicon glyphicon-remove"></span></a> It says that I am missing ). I know there are some solutions on this problem here, but i wanted to make mine work.
var counter = 2;
$("#addTextField").click(function() {
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'textboxdiv'+counter);
newTextBoxDiv.after().html('<input type="text" name="textbox' + counter + '" placeholder="Category" /><span id="mySpan" class="glyphicon glyphicon-remove"></span>');
newTextBoxDiv.appendTo("#textboxgroup");
counter++;
});
try like this: The trick is to remove the element you clicked on which you can get with $(this) inside the click
var counter = 0;
$("#addTextField").on('click', function() {
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'textboxdiv'+counter);
newTextBoxDiv.after().html('<div class="wrapper">' + counter + '<input type="text" name="textbox' + counter + '" placeholder="Category" /><span class="glyphicon glyphicon-remove">remove</span></div>');
newTextBoxDiv.appendTo("#textboxgroup");
counter++;
});
$('body').on('click', '.glyphicon-remove', function(){
$(this).closest('.wrapper').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="addTextField">click to add</div>
<div id="textboxgroup"></div>
In your code you added an ID <span id="mySpan" on every click which is bad cause an ID should always be unique. So if you add it more than once it is not unique anymore. Better use classes instead...
try this:
var counter = 0;
$('#add').click(function() {
$('#target').append('<span>New Input: <input type="text"><button id="remove' + counter + '">Remove</button><br></span>');
$('#remove' + counter).click(function() {
$(this).parent().html('');
counter--;
});
counter++;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<button id="add">Add</button>
<div id="target"></div>

Display one text field on click from a set number of text fields

I have a form where users have 10 text fields. But initially only 1 text field is shown. If the user needs to enter more data they can click on the add one button and then displays the next text field from the maximum of 10.
like so:
Im working with angular.js so I thought about using ng-show to hide & show fields.
<div class="form-group">
<input type="text" class="form-control" name="pointOne" ng-show="pointOne">
<input type="text" class="form-control" name="pointTwo" ng-show="pointTwo">
<input type="text" class="form-control" name="pointThree" ng-show="pointThree">
<span><button ng-click="addOne()">Add One</button></span>
</div>
I am unable to figure out the most effective way to doing this. Any hints, help or suggestions would be great.
Haven't tested it but this is how I would do it:
<div class="form-group" >
<input ng-repeat="i in getNumber(number)" type="text" class="form-control" name="point{{i}}" ng-show="$index<=counter">
<span><button ng-click="addOne()">Add One</button></span>
</div>
And in your controller just add something like this:
$scope.number = 10;
$scope.getNumber = function(num) {
return new Array(num);
}
$scope.counter=0;
$scope.addOne= function() {
$scope.counter++;
}
You could easily add elements to the DOM:
function createPetField() {
var input = document.createElement('input');
input.type = 'text';
input.name = 'pet[]';
return input;
}
var form = document.getElementById('myForm');
document.getElementById('addPet').addEventListener('click', function(e) {
form.appendChild(createPetField());
});
To go the Angular route, I'd suggest using ng-repeat. Here's a fiddle that might not be exactly what you're looking for, but it shows how to use ng-repeat and you can modify as needed:
Fiddle: https://jsfiddle.net/jvsnao97/5/
<body ng-app="myApp" ng-controller="myController">
<button ng-click="add_input()">Add Input</button>
<br/><br/>
<input type="text" class="form-control" ng-repeat="x in random_array" name="point{{$index}}">
</body>
var app = angular.module("myApp", []);
app.controller("myController", ["$scope", function($scope) {
$scope.random_array = [0]
$scope.add_input = function() {
var i = $scope.random_array.length
$scope.random_array.push(i)
}
}]);
When you want a new <input>, you simply push a new element to $scope.random_array.
Probably good way is to make array of input fields and then ng-repeat them. When user clicks on AddOne, then just push input field in array, and it will be there.
<html>
<head>
<title>jQuery add / remove textbox</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<style type="text/css">
div{
padding:8px;
}
</style>
</head>
<body>
<h1>jQuery add / remove textbox example</h1>
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
if(counter>10){
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Textbox #'+ counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
$("#getButtonValue").click(function () {
var msg = '';
for(i=1; i<counter; i++){
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
</script>
</head><body>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Textbox #1 : </label><input type='textbox' id='textbox1' >
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<input type='button' value='Get TextBox Value' id='getButtonValue'>
</body>
</html>
JQuery can be used to add inputs in your addOne() method.
Like so:
var maxInputs = 10;
var currentInput = 0;
function addOne() {
currentInput++;
if (currentInput > maxInputs) {
currentInput = maxInputs;
return;
}
var name = "point" + currentInput;
var $input = $("<input type='text' class='form-control' name='" + name + "' ng-show='" + name + "'>");
$(".form-group").append($input);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<span><button onclick="addOne()">Add One</button></span>
</div>

How to add a new textfield on clicking a button?

I'm trying to insert certain sentences to MySQL database using PHP. But the design of the field is such a way that it shows only one field and a [add] button to insert a new textfield. So depending on the user needs, the number of textfields varies.
<div class="row">
<h5>LEARNING GOALS</h5>
<div style="display:table; width:100%;">
<div style="display:table-row;">
<div style="display:table-cell;">
<input class="text-field" name="goal" type="text" placeholder="Goals*" style="width:100%">
</div>
<div style="display:table-cell; vertical-align:middle;width:65px;">
<input class="add-field-btn" type="button" value="+" style="width:65px;"></div>
</div>
</div>
</div>
How can I add a new textfiled and assign name value and when I click on the submit button, to save all the textfield values into the database?
<html>
<head>
<title>jQuery add / remove</title>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>
<style type="text/css">
div{
padding:8px;
}
</style>
</head>
<body>
<h1>jQuery add / remove </h1>
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
if(counter>10){
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Textbox #'+ counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
$("#getButtonValue").click(function () {
var msg = '';
for(i=1; i<counter; i++){
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
</script>
</head><body>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Textbox #1 : </label><input type='textbox' id='textbox1' >
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<input type='button' value='Get TextBox Value' id='getButtonValue'>
</body>
</html>
First of all use your text field name as a array so when user will add new text field you can get all of them in just one post variable and you can store them in different row or as you want.
Now on click on you button append text field with same name as
your first field code:<input class="text-field" name="goal[]" type="text" placeholder="Goals*" style="width:100%">
Javascript code: $('#yourselector').append('<input class="text-field" name="goal[]" type="text" placeholder="Goals*" style="width:100%">');
It the server end you can get all the posted values in $_POST['goal'] which will be a array;
Demo Check this fiddle.
document.getElementById('#whereToAppend').append('<input type="text" name="WhateverYouwant"/>');
document.getElementsByTagName('body')[0].appendChild('<input type="text"/>');
If you want dynamic names, set a class name or id to the input. And make use of setAttribute in javascript to set the name
One solution would be to try and serialize all the inputs and save them to the database. You just send them by submitting the form then in PHP do something like:
$inputs = serialize($_GET); // $inputs = serialize($_POST);
mysql_query('INSERT INTO `table` SET inputs = "'.$inputs.'"'); // try to validate the variable before
This would be nice given the fact that you have variable number of fields.
When you select them use deserialize to recreate the data:
$r = mysql_query('SELECT inputs FROM `table`');
...
$data = deserialize($row['inputs']);
Another option would be to get all the inputs with JavaScript or jQuery and pass them via AJAX.
var _data = [];
$('input.text-field').each(function(i, e) {
_data.push($(e).val());
});
$.post('file.php', { d : JSON.stringify(_data)}, function(e){
alert(e);
})
PHP:
$d = json_decode($_POST['d']);
foreach($d as $k => $v) {
// value of the input no. $k is $v
}
You can use #Nickunj's jQuery code for appending the new input.

Cannot use show/hide

My issue: When I add another text input, I cannot show/hide it.
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.1.0.min.js"></script>
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
<script>
$(document).ready(function(){
$(".slidingDiv").hide();
$(".show_hide").show();
$('.show_hide').click(function(){
$(".slidingDiv").slideToggle();
});
$(".slidingDiv1").hide();
$(".show_hide1").show();
$('.show_hide1').click(function(){
$(".slidingDiv1").slideToggle();
});
});
var counter = 1;
var limit = 3;
function addInput(divName){
mainCanvasDiv = document.createElement("div");
mainCanvasDiv.className = "slidingDiv1";
mainCanvasDiv.style.display = "none";
var newdiv = document.createElement('div');
newdiv.id = "dynamicInput" + counter;
newdiv.innerHTML = "<a href='#' class='show_hide1'>Show/hide</a>";
mainCanvasDiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='dynamicInput" + counter +"1'><br><input type='text' name='dynamicInput" + counter +"2'>";
document.getElementById(divName).appendChild(newdiv).appendChild(mainCanvasDiv);
counter++;
}
$(document).ready(function(){
$('#sortable').sortable({
update: function(event, ui) {
var newOrder = $(this).sortable('toArray').toString();
document.getElementById('sort').value = newOrder;
}
});
});
</script>
</head>
<body>
<form action="lost.php" method="POST">
<div id="sortable">
<div id="dynamicInput">
Show/hide
<div class="slidingDiv">
<input type="text" name="myInputs[]">
</div>
</div>
</div>
<input type="button" value="Add another text input" onClick="addInput('sortable');"><br />
<input type="hidden" name="sort" id="sort" value="">
<input type=submit value="GO!">
</form>
</body>
</html>
Any advice?
Update:
I have changed
$('.show_hide1').click(function(){
to
$('.show_hide1').on("click", "div a.show_hide1", function(){
Maybe I am doing something wrong, I am not strong in JS.
Fixed: http://jsfiddle.net/Yhp3c/
You need to use live instead of click as live also targets future (read: DOM scripted) elements.
Edit: As stated in comments: Use on instead of live.
Replace your click events for:
$("#sortable").on("click","div a.show_hide", function() {
$(".slidingDiv").slideToggle();
});
$("#sortable").on("click","div a.show_hide1", function() {
$(".slidingDiv1").slideToggle();
});

Categories