How to merge items in an array on a form submit? - javascript

This form has a text input for each day of the week, as well as an "Add Another" button to create more inputs under each day. The submissions go through but only the first value that's entered into the input gets posted to the Spreadsheet's cell.
So for example, if the user has multiple entries entered in for SUNDAY_NOTES, like so:
SUNDAY_NOTES = "Late."
SUNDAY_NOTES = "This thing."
SUNDAY_NOTES = "Something."
... then only "Late" ends up in the spreadsheet's cell with my current code. Ideally, I'd like to have a comma-separated or linebreak-separated string in the cell: ("Late., This thing., Something."). I'm using the following code (which I copied) to post the submissions to a Google Spreadsheet.
<form method="post" id="timesheet" >
<input type="text" name="SUNDAY_NOTES">
<input type="text" name="SUNDAY_NOTES">
// user can click a button to keep adding more SUNDAY_NOTES fields
<input type="text" name="MONDAY_NOTES">
// and so forth
<input type="submit" id="submit" />
</form>
<script>
var $form = $('form#timesheet'),
url = 'https://script.google.com/macros/s/abcd123456789/exec'
$('#submit').on('click', function(e) {
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
data: $form.serializeArray()
}).success(
console.log('success')
);
})
</script>
(This question doesn't accurately describe the use-case of my form, I just overly-simplified it for posting purposes)

to have an array of inputs values with same name, add [] after the name like : name="SUNDAY_NOTES[]" ,
so replace <input type="text" name="SUNDAY_NOTES"> with <input type="text" name="SUNDAY_NOTES[]">
then join the array values with a comma with
data : $form.serializeArray().map((e) => { return e.value}).join(',')
$form.serializeArray() will have an array of objects, that's why it's useful to use .map() to retun an array of values to be able to join them.
$(document).ready(function() {
var $form = $('form#timesheet');
$form.submit(function(e) {
e.preventDefault();
var myValues = $form.serializeArray().map((e) => {
return e.value
}).join(',');
console.log(myValues);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="timesheet">
<input type="text" name="SUNDAY_NOTES[]">
<input type="text" name="SUNDAY_NOTES[]"> // user can click a button to keep adding more SUNDAY_NOTES fields
<input type="text" name="MONDAY_NOTES[]"> // and so forth
<input type="submit" id="submit" />
</form>
EDIT :
in order to keep the structure as is ( key, value pairs ), create a function group that loops through an array and add the values to the key
function group(arr){
var tempArr = [];
arr.forEach(function(e){
if(!tempArr[e.name]) tempArr[e.name] = e.value
else tempArr[e.name] += ',' + e.value
});
return tempArr;
}
$('#submit').on('click', function(e) {
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
data: group($form.serializeArray())
// rest of your code
here's a fiddle : https://jsfiddle.net/cwgL6L0L/29/ ( check the console )

Related

Dynamically pass in values to the data object

Currently, I get the value of an id and pass it in my data object to be sent to the server.
const field_value = $('#id_field').val();
const scores_value = $('#id_scores').val();
$.ajax({
data: {'Fields':field_value, 'Scores': scores_value},
});
I want to achieve this dynamically in case I add more forms so it can automatically update without me having to change any code.
I tried using the jquery each method to access the class.
$(".class").each(function() {
const get_updated_value = $(this).val();
});
This dynamically gets the values, but I am having trouble passing the returned values to the data object.
If each element with '.class' has still an own id you could take these id's as the keys of the data object:
var updated_values = {};
$(".class").each(function() {
updated_values[$(this).attr('id')] = $(this).val();
});
$.ajax({
data: updated_values,
});
Working example:
function update() {
var updated_values = {};
$(".input").each(function() {
updated_values[$(this).attr('id')] = $(this).val();
});
console.log(updated_values);
}
input {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input type="text" placeholder="My task" id="field" class="input">
<input type="text" placeholder="My date" id="scores" class="input">
<input type="text" placeholder="My time" id="something_new" class="input">
<input type="button" value="Update" onclick=update() id="save">
</div>

How to submit single form via AJAX when you have multiple forms from PHP loop

I am trying to submit a form on keyup, sort of a keylogger effect. Here is my attempt -
php loop form -
<form method="post" id="'.$vid.'" class="note-form">
<textarea id="'.$vid.'" name="quicknote" value="'.$quick_note.'" placeholder="add a quick note" class="quicknote">'.$quick_note.'</textarea>
<input type="hidden" name="tac" value="'.$vid.'"/>
</form>
$vid is the unique id for each form that im passing from the DB.
JS file -
// Capture keyup from textarea to submit form
$('.quicknote').bind('keyup', function() {
var id = this.id;
var formID = "#"+id;
$(formID).delay(200).submit();
});
$(formID).submit(function(e) {
var url = "ready-data/submit-note.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function(data) {
// Do something
}
});
e.preventDefault();
});
I use the same ID for the form and the inputs but the form isnt submitting. I can submit if I use the form class note-form but it submits all forms. I cant make formID a global variable to pass to the ajax function also. What is the correct way to do this?
Your form id and textarea id are same that's why its causing problem . Instead you can use
$(this).closest('form') this will get closest form from textarea then you can submit only that form.
Demo Code :
$('.quicknote').bind('keyup', function() {
var selector = $(this).closest('form') //get closest form
$(selector).delay(200).submit(); //submit that.
});
$("form").submit(function(e) {
console.log("data to send --> " + $(this).serialize())
var url = "ready-data/submit-note.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function(data) {
// Do something
}
});
e.preventDefault();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" class="note-form">
<textarea id="1" name="quicknote" value="somethings..." placeholder="add a quick note" class="quicknote">somethings..</textarea>
<input type="hidden" name="tac" value="1" />
</form>
<form method="post" class="note-form">
<textarea id="2" name="quicknote" value="somethings" placeholder="add a quick note" class="quicknote">somethings...</textarea>
<input type="hidden" name="tac" value="2" />
</form>

easy loop through json api array jquery

This jquery code is displaying json data inside span html input elements. But i failed to implement for loop to display array objects of movie genres.
Right now it's just 0 index of array but i wanna display all..
$("#txt-movie-genres").val(json.genres[0].name)
$(document).ready(function() {
var url = 'http://api.themoviedb.org/3/',
mode = 'movie/',
movie_id,
key = '?api_key=e9dfeccf734a61b9a52d9d7660f0d0a1';
$('button').click(function() {
var input = $('#movie').val(),
movie_id = encodeURI(input);
$.ajax({
type: 'GET',
url: url + mode + movie_id + key,
async: false,
jsonpCallback: 'testing',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
// grab the span elements by ID and replace their text with the json text
// $("#movie-title").text(json.title);
$("#txt-movie-title").val(json.title)
$("#txt-movie-genres").val(json.genres[0].name)
console.dir(json);
},
error: function(e) {
console.log(e.message);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="movie" type="text" /><button>Search</button>
<h1>Movie info:</h1>
<p>Movie title: <span id="span-movie-title"></span> </p>
<div class="input-group">
<input id="txt-movie-title" name="title" type="text" />
<div class="input-group-addon">
Movie Name
</div>
</div>
<div class="input-group">
<input id="txt-movie-genres" name="genres" type="text" />
<div class="input-group-addon">
Movie Genre
</div>
</div>
Something like:
$("#txt-movie-genres").val(json.genres.map(g => g.name).join(",");
Which will create an array of names and then join them into a comma delimited string.
You could covert json.genres arrays to array of genres names using .map() methidand then join them to comma separated string using join():
var names = $.map(json.genres, function() { return this.name }).join(",");

hold the value from form through keyup

I have an input field through which i am getting the value that user enters, although i am able to display it but instead of displaying it, i wish to store the user entry in a variable and then use it to get data from database. Below is the code that i have so far (#JSFiddle)
<form action="save.php" method="post">
<input type="text" value="" id="test">
<p></p>
<input type="text" value="">
<button type="button">submit</button>
</form>
<script>
$( "input" )
.keyup(function() {
var value = $( this ).val();
$( "p" ).text( value );
})
.keyup();
</script>
E.g: if a user enters 12 in input box and then click enter button, then 12 should get stored in a variable, but the whole form should not get submitted after every value of input field is filled then only the form should get submitted
$idd=12;
and then i wish to run a query as
$sql=" SELECT * from menu where id = '".$idd."' ";
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_assoc($result))
{
/*
*
* code to display data
*
*/
}
}
and the result that i need to display will come from the code running inside while loop
Can anyone please tell how to obtain the result
With this code, you store the result to a variable declared before the keyup event.
<input type="text" value="some text">
<p></p>
<script>
var inputValue;
$( "input" )
.keyup(function() {
inputValue = $(this).val();
})
.keyup();
</script>
Than you could do your AJAX call.
EDIT
Here's the code that only respond to the "enter" keycode
var value;
$('input').on('keyup', function(ev) {
if(ev.keyCode == 13) {
value = $(this).val();
}
});
You can do by two ways
<input type="text" value="some text" id="input_id" name="input_name">
<input type="submit" name="submit">
With jquery/ajax
$('#input_id').on('keyup', function() {
var field_value = $("#input_id").val();
jQuery.ajax({
type: 'post',
url: 'path_to_the_file',
data: { fieldValue: field_value },
success: function(successData) {
//do whatever want on success
}
});
});
Or without jquery/ajax On same page
if(isset($_POST['submit']))
{
$my_value = $_POST['input_name'];
//Execute your query
}
you can use ajax to post value of input box and get the result like this
<form action="save.php" method="post">
<input type="text" value="" id="test">
<p></p>
<input type="text" value="">
<button type="button" id="btnsubmit">submit</button>
</form>
<script>
var value
$("input").keyup(function () {
value = $(this).val();
})
$('#btnSubmit').click(function(){
$.ajax({
type: "POST",
url: "url_of_php_page",
data: {id: value},
success: function (html)
{
$("p").text(html);
}
});
});
</script>

jquery code to change the parameters submitted by a form

In a web form in a PHP program, the form is a regular HTML form.
Now, the form has 3 separate text boxes. Let their IDs/names be box1, box2 and box3 respectively
What I want to happen is, when the form gets posted --
The following text gets posted--> box1 + box2+ box3 contents, separated by commas.
I wish to do this using JQuery- I looked up JQuery "submit" function but could not find any direct way to replace the parameters-- how can I implement the above?
You could do this :
$('#yourForm').submit(function(e){
var form = $(this)
//Do you validation
if(isValid){
var mergedInput = $('<input/>');
var inputToMerge = ['#box1','#box2','#box3'];
var valueToMerge = $.map(inputToMerge, function(selector){
val = $(selector).val()
$(selector).remove()
return val;
})
mergedInput.val(valueToMerge.join(','));
mergedInput.prop('name', 'mergedInput')
mergedInput.appendTo(form);
}else{
return false;
}
})
Basicly, it is merging your input into one accessible via php with ['mergedInput'].
i think you can do this easily using ajax .. Kindly check Change contents of submitted form on submit
if you want to do this without ajax, you may have to use hidden fields .. Kindly check jquery-add-additional-parameters-on-submit-not-ajax
You can use AJAX to solve your problem
Your HTML
<form onsubmit="return sendBoxes()">
<input type="text" id="box1">
<input type="text" id="box1">
<input type="text" id="box1">
<input type="submit">
</form>
And JS
function sendBoxes(){
var values = "'"+$('#box1').val()+"'"+$('#box2').val()+"'"+$('#box3').val()+"'";
jQuery.ajax({
url: "ajax_ajax.php",
data: "boxes="+values,
cache: false,
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error.\n" + textStatus + " " + errorThrown);
}
});
return false;
}
HTML
<input id="box1" type="text" />
<input id="box2" type="text" />
<input id="box3" type="text" />
<input id="submit_button" type="submit" />
JS
function submit(){
$.ajax({
type: "POST",
url: "someurl.php",
data:{'boxes':$('#box1').val()+","+$('#box2').val()+","+$('#box3').val()}
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
$("#submit_button").click(function(e) {
submit();
e.preventDefault();
return false;
});
This would check whether submit button is clicked and sends three box values separated by comma

Categories

Resources