Why isn't the value going to the console? - javascript

This is a stupid question but I am getting frustrated and hoping for some help. Why won't my values output to the console after submitting? Anyone notice issues?
var todos = "";
// user clicked on the add button in the to-do field add that text into the to-do text
$('#add-todo').on('click', function(event) {
event.preventDefault();
//values per text box
todos = $("#todo-input").val().trim();
//test values from textbox
console.log(todos);
HTML
<div class ="col-4">
<form role = "form">
<div class = "form-group row">
<div class = "To-Do-List">
<label for="todo-input">Add Your To Do List Here:</label>
</div>
<input class="form-control" id="todo-input" type = "text">
<tbody id = "table_body">
</tbody>
</div>
</form>
</div>
<div class="button">
<button class ="btn btn-danger" id="add-todo" type="submit">Add</button>
</div>

You only need close whit "})"
var todos = "";
// user clicked on the add button in the to-do field add that text into the to-do text
$('#add-todo').on('click', function(event) {
event.preventDefault();
//values per text box
todos = $("#todo-input").val().trim();
//test values from textbox
console.log(todos);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class ="col-4">
<form role = "form">
<div class = "form-group row">
<div class = "To-Do-List">
<label for="todo-input">Add Your To Do List Here:</label>
</div>
<input class="form-control" id="todo-input" type = "text">
<tbody id = "table_body">
</tbody>
</div>
</form>
</div>
<div class="button">
<button class ="btn btn-danger" id="add-todo" type="submit">Add</button></div>

Related

Putting values from Textboxes into an array

Good Day,
I have created a simple form with three boxes to capture text data. I also have a button that duplicates the form to facilitate multiple entries. I want to be able to take that data and place into 3 arrays, one for each text box.
The code is below:
$(document).ready(function()
{
$("#add").click(function()
{
addThis = "<div class='row mb-3'><div class='col-12'><input type='text' name='fname[]' id='fname' class='form-control' placeholder='First Name'></div></div><div class='row mb-3'><div class='col-12'><input type='text' name='mname[]' id='mname' class='form-control' placeholder='Middle Name'></div></div><div class='row mb-3'><div class='col-12'><input type='text' name='lname[]' id='lname' class='form-control' placeholder='Last Name'></div></div>";
$("#form1").append(addThis);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card" id="form2">
<div class="card-body">
<form action="" id="form1" class="card-body">
<div class="row mb-3">
<div class="col-12">
<input type="text" name="fname[]" id="fname" class="form-control" placeholder="First Name">
</div>
</div>
<div class="row mb-3">
<div class="col-12">
<input type="text" name="mname[]" id="mname" class="form-control" placeholder="Middle Name">
</div>
</div>
<div class="row mb-3">
<div class="col-12">
<input type="text" name="lname[]" id="lname" class="form-control" placeholder="Last Name">
</div>
</div>
</form>
<form action="">
<div class="d-grid gap-2">
<div class="btn-group" role="group">
<button type="button" class="btn btn-primary" id="add">Add Another</button>
<button type="button" name="test" class="btn btn-success">TEST</button>
</div>
</div>
</form>
</div>
I want to eventually submit the data into the table, looping through the arrays for each instance of the form.
Could some one point me in the right direction please?
Heres a possible solution using fieldsets to group your name inputs.
See comments in jQuery JS so you know whats happening...
// our form as const object
const form = $('#form');
// on form submit pass event
$(form).on('submit', function(e) {
// stop event default behaviour
e.preventDefault();
// set entry as serialized array
let entry_arr_obj = $(this).serializeArray();
// set empty object for formatted entry data
let formatted_entry_obj = {};
// for each entry array obj values as key => object
$.each(entry_arr_obj, function(k, obj) {
// split object field name by underscore to create name_fieldset array containing fieldset id and name key
let name_fieldset = obj.name.split('_');
// set the set id from name_fieldset array
let fieldset = parseInt(name_fieldset[1]);
// set name key from name_fieldset array
let name = name_fieldset[0];
// if formatted_entry_obj does not have own property matching current fieldset id
if(!formatted_entry_obj.hasOwnProperty(fieldset)) {
// add fieldset id and empty object to formatted_entry_obj
formatted_entry_obj[fieldset] = {};
}
// add field name and field value to formatted_entry_obj current fieldset object
formatted_entry_obj[fieldset][name] = obj.value;
});
// log our entry object
console.log(formatted_entry_obj);
});
// on form add field set
$(form).on('click', '.add', function(e) {
// get all our fieldsets
let fieldsets = $('fieldset',form);
// last fieldset obj and id
let last_fieldset = fieldsets[fieldsets.length-1];
let last_fieldset_id = parseInt($(last_fieldset).data('set'));
// create new fieldset id
let new_fieldset_id = last_fieldset_id + 1;
// clone last fieldset and filter attributes
$(last_fieldset).clone().filter(function() {
// update data set attribute with new fieldset id
$(this).attr(
'data-set',
new_fieldset_id
// now filter children elements (cols)
).children().filter(function() {
// now filter children elements (inputs)
$(this).children().filter(function() {
// get child element name attr
let name_attr = $(this).attr('name');
// if we have name attr
if(name_attr) {
// explode the name attr value via underscore
let name_fieldset = name_attr.split('_');
// return updated name attribute with new fieldset name and empty value
return $(this).attr(
'name',
name_fieldset[0] + '_' + new_fieldset_id
).val(null);
}
// else return child element
return $(this);
});
// return child element
return $(this);
});
// return all of cloned elem
return $(this);
// then insert after last field set
}).insertAfter(last_fieldset);
});
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.2/dist/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container py-3">
<form id="form">
<fieldset data-set="1" class="form-row mb-3">
<div class="col-sm-4">
<input type="text" name="fname_1" placeholder="First Name" class="form-control form-control-sm" />
</div>
<div class="col-sm-4">
<input type="text" name="mname_1" placeholder="Middle Name" class="form-control form-control-sm" />
</div>
<div class="col-sm-4">
<input type="text" name="lname_1" placeholder="Last Name" class="form-control form-control-sm" />
</div>
</fieldset>
<button type="button" class="add btn btn-sm btn-primary btn-block">Add Fieldset</button>
<button type="submit" class="btn btn-sm btn-success btn-block">Submit</button>
</form>
</div>

How do I insert Data Into database with many Input which has same name?

hello friends I have a form field in which I want to insert data which has four field which are customer_id , field_name1 ,field_name2, field_name3 ,
The question is I want to insert data which has many inputs but same input name like field_name1 field_name2 field_name3 , firstly there is no input but when I click on a button add partner details then these inputs shows by javascript .
like field_name1,field_name2,field_name3 ten times can repeat , I want to insert data in database according to there numbers with same customer_id , but different field name , below is my code , hope you understand it .
here is my code
<?php
$conn=mysqli_connect("localhost","root","","satya");
if(isset($_POST['submit'])){
$customer_id=$_POST['customer_id'];
for ($ix=0; $ix<count($_POST['field_name1']); $ix++)
{
$field_data = array(
'field_name1' => $_POST['field_name1'][$ix],
'field_name2' => $_POST['field_name2'][$ix],
'field_name3' => $_POST['field_name3'][$ix],
);
$sql="INSERT INTO customer(customer_id,details1,details2,details3) VALUES('$customer_id','$field_name1','$field_name1','$field_name1')";
$result=mysqli_query($conn,$sql);
if($result){
echo "data has been inserted";
}
else{
echo "data could not be inserted";
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<form action="" method="post">
<div class="form-group">
<div class="row" style="margin-top: 20px">
<div class="col-md-4" ></div>
<div class="col-md-4">
<label for="customer_id">Customer ID </label>
<input type="text" class="form-control" name="customer_id" placeholder="customer_id">
</div>
<div class="col-md-4"></div>
</div>
<div class="row" style="margin-top: 20px;">
<div class="col-md-3">
<label for="details1">details1 </label>
</div>
<div class="col-md-3">
<label for="details2">details2</label>
</div>
<div class="col-md-3">
<label for="details3">details3</label>
</div>
<div class="col-md-3">
<div>
Add Partner Details
</div>
</div>
<div class="partner_wrapper" >
</div>
</div>
<div class="col-md-4"></div>
<div class="col-md-4">
<button type="submit" class="btn btn-primary" name="submit">Submit</button>
</div>
<div class="col-md-4"></div>
</form>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
</html>
<script>
$(document).ready(function(){
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_partner'); //Add button selector
var wrapper = $('.partner_wrapper'); //Input field wrapper
var fieldHTML = '<span class="row"><div class="col-md-3"><input type="text" class="form-control" name="field_name1[]" value=""/></div><div class="col-md-3"><input type="text" class="form-control" name="field_name2[]" value=""/></div><div class="col-md-3"><input type="text" class="form-control" name="field_name3[]" value=""/></div><button type="button" href="javascript:void(0);" class="remove_button btn btn-primary" title="Remove field">Remove</button></span>'; //New input field html
var x = 1; //Initial field counter is 1
$(addButton).click(function(){ //Once add button is clicked
if(x < maxField){ //Check maximum number of input fields
x++; //Increment field counter
$(wrapper).append(fieldHTML); // Add field html
}
});
$(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
e.preventDefault();
$(this).parent('span').remove(); //Remove field html
x--; //Decrement field counter
});
});
</script>
Give the repeating fields array-style names:
<input type="text" name="field_name1[]">
PHP will collect the inputs into arrays, so $_POST['field_name1'] will be an array. Then you can loop over them:
foreach ($_POST['field_name1'] AS $index => $field1) {
$field2 = $_POST['field_name2'][$index];
$field3 = $_POST['field_name3'][$index];
// now you can insert all these values into the DB
}

Firebase Chat change reference with javascript

I am trying out how to incorporate firebase with angular in such a way that the user is able to change the "Channel" of the chat via selecting from a dropdownlist.
This is the code that I have at the moment:
Note: The channel attribute is defined in another portion of code, and the entire page is loaded only once.
app.controller('mychat', function($scope, $firebaseArray) {
var d = new Date();
var today = d.getDate()+d.getMonth()+d.getYear();
var txt = document.getElementById('txtFBMsgs'); //store id of textbox
//Query
var ref = firebase.database().ref().child(channel)
$scope.fbmessages = $firebaseArray(ref);
$scope.send = function() {
if (txt.value != ""){ //check if textbox contains any message
$scope.fbmessages.$add({
sender: sender,
message: $scope.messageText,
date: Date.now()
})
txt.value = ""; //reset value of textbox
}
}
})
and here is my html portion:
<div class="card mb-1 col-md-3" ng-controller="mychat" id="myDiv">
<div class="card-body" style="overflow-x: hidden; overflow-y:scroll; min-height:60vh; max-height:64vh;">
<div>
<p ng-repeat="m in fbmessages"> {{m.date | date:'short'}} - {{m.sender}}: <br> {{m.message}}</p>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-9">
<input type="text" id = "txtFBMsgs" class="form-control" placeholder="Message here..." ng-model="messageText" onkeydown = "if (event.keyCode == 13) document.getElementById('sendBtn').click()">
</div>
<div class="form-group col-md-3">
<button type="submit" class="btn btn-primary btn-block" id="sendBtn" ng-click="send()">Send</button>
</div>
</div>
basically, it is a div that displays the chat messages, and an input box which is able to send the message to firebase.
Can I change the 'Channel' dynamically via javascript, such as on an onchange in a DDL?

put data on textbox dynamically not working

I am not able to enter the data to the previous page using ng-model. I moved to the next page after filling some data in textbox,after come to same page i want my data to be entered same as i entered previously, i write the code but its not working please tell me what i am doing wrong and thanks in advance
js code:-
$scope.notesPage = function() {
$rootScope.data = {
Name: $scope.prospectName,
};
$location.path('/prospectNotes');
};
$scope.addProspect = function() {
$rootScope.data.ProspectNotes = $scope.notes;
$scope.ProspectNotes = "";
};
function fillFormData() {
$scope.prospectName = $rootScope.data.Name;
}
$scope.addProspectForm = function() {
$location.path('/create');
fillFormData();
}
first html page
<div class = "container" id = "form-container">
<div class = "form-group">
<label for = "prospectName"> Prospect Name:
<img src = "images/required.gif" alt = "Required" class = "required-star">
</label>
<input type = "text" id = "prospectName" name = "prospectName" ng-model = "prospectName"
class = "form-control" required>
</div>
<div class = "form-group">
<button type="submit" class="col-sm-2 btn btn-primary" ng-click="notesPage()"
style="margin-left:10px;"> Next </button>
</div>
</div>
second html page
<div class = "container" id = "form-container">
<div class = "form-group">
<label for = "notes"> Notes for Prospect {{data.Name}}</label>
<textarea rows="20" id = "notes" name = "notes" ng-model = "notes" class = "form-control"></textarea>
</div>
<div class = "form-group">
<input type="button" id="cancel-button" value="Back" class="col-sm-2 btn btn-primary"
ng-click="addProspectForm()">
<button type="submit" class="col-sm-2 btn btn-primary" ng-click="addProspect()"
style="margin-left:10px;"> Add </button>
</div>
</div>

How do I change the input name in jQuery

This is what I am currently trying to achieve:
I am trying to clone a form and change the input name. How would I pull this off.
JS:
$(document).ready(function() {
var counter = 0;
var MAX_FIELDS = 3;
var MIN_FIELDS = 1;
var form = $('.force-group');
$('#add').on('click', function(e) {
if (counter < MAX_FIELDS) {
//$(".form-group").clone().appendTo("#forceForm");
$.each(form, function(i) {
var clone = $('.force-group').first().clone();
clone.children().val("");
$(this).parent().append(clone);
if (counter == 0) {
$("b:eq(1)").html("<b> Force 2</b>");
};
if (counter == 1) {
$("b:eq(3)").html("<b> Force 3</b>");
};
if (counter == 2) {
$("b:eq(5)").html("<b> Force 4</b>");
};
});
counter++;
};
});
html:
<#import "template.ftl" as layout />
<#layout.template title="Force" js="/js/force.js" css="/css/force.css">
<h3 class = "text-center">Total Force</h3>
<hr>
<div class="col-md-6 col-md-offset-3 col-xs-8 col-xs-offset-2">
<div class="force-selector input_fields_wrap">
<a id = 'add' href="#" class="btn btn-primary col-md-5">Add Force</a>
<a id = 'remove' href="#" class="btn btn-warning col-md-5 col-md-offset-2">Remove Force</a>
</div>
</div>
<div class="col-md-6 col-md-offset-">
<div class="col-xs-12">
<div class = "well" id="force-input">
<form id = "forceForm" class = "form-horizontal" method = "POST" autocomplete="off">
<fieldset>
<h4 class="text-center" id="form-title"><strong>Input</strong></h4>
<div class="form-group force-group">
<label class = "control-label col-md-2"><b>Force 1</b></label>
<label class = "control-label col-md-2">Magnitude</label>
<div class = "col-md-3 force-info">
<input type = "text" class="form-control" name="0force" autocomplete="off">
</div>
<label class = "control-label col-md-2">Angle</label>
<div class = "col-md-3 force-info">
<input type = "text" class="form-control" name="0angle" autocomplete="off">
</div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
<div class = "col-md-5">
<table id = "forceChart" class="table table-striped table-hover">
<thead>
<tr class="table">
<th class="head-pad">Total Force</th>
</tr>
</thead>
<tbody>
<tr class="table">
<td class="pad">Net Force:</td>
</tr>
</tbody>
</thead>
<tbody>
<tr class="table">
<td class="pad">Direction:</td>
</tr>
</tbody>
<tfoot></tfoot>
</table>
</div>
<div class = "col-md-4 col-md-offset-4 col-xs-6 col-xs-offset-3">
<div class="form-group">
<div class = "col-md-6 col-xs-offset-3">
<input id = "calculate" class = "btn btn-success btn-block" type="submit" value="Calculate!">
</div>
</div>
</div>
This is the jsfiddle link right here:
Click here for the link.
PS: I am using a templater so the jsfiddle will look kinda bad.
I am new to jQuery and I have been searching around a solution but I seem to get stuck with it.
I tried using the .last() with the attr edit but that seems not to do anything.
To change an input name just use attr() method
$('input').attr('name', 'yourNewname');
and I remarque that you have input without Id so you should use one of those methods:
1/ give each input an Id for example #input1 #input2
$('#input1').attr('name', 'yourNewname1'); // change the name of first input
$('#input2').attr('name', 'yourNewname2'); // change the name of first input
or
you can use eq()
$('input').eq(0).attr('name', 'yourNewname1'); // change the name of first input
$('input').eq(1).attr('name', 'yourNewname2'); // change the name of first input
To change any attribute including name you can do this
$('#myInputFieldId').attr('name','new_name')
Hope it helps
Try this: $('input[name="0angle"]').attr('name', 'new-name');

Categories

Resources