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>
Related
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 )
So, let's say I have an HTML form like this:
<form id="myForm">
<input type="text" name="dummy">
<input type="text" name="people[0][first_name]" value="John">
<input type="text" name="people[0][last_name]" value="Doe">
<input type="text" name="people[1][first_name]" value="Jane">
<input type="text" name="people[1][last_name]" value="Smith">
</form>
And I want to get a JavaScript array that matches the values of real. For example:
// If there was a sweet function for this...
var people = getFormDataByInputName( 'people' );
// Value of `people` is...
// [
// {
// 'first_name' : 'John',
// 'last_name' : 'Doe'
// },
// {
// 'first_name' : 'Jane',
// 'last_name' : 'Smith'
// }
// ]
Is there any easy way of doing that for just a specific form item (in this case, people)? Or would I have to serialize the entire form an then just extract the element I want?
I also thought of potentially using the following approach:
var formData = new FormData( document.querySelector( '#myForm' ) );
var people = formData.get( 'people' );
But that doesn't appear to work; people is just null after that.
You could do this with plain js using reduce method and return each person is one object.
const form = document.querySelectorAll('#myForm input');
const data = [...form].reduce(function(r, e) {
const [i, prop] = e.name.split(/\[(.*?)\]/g).slice(1).filter(Boolean)
if (!r[i]) r[i] = {}
r[i][prop] = e.value
return r;
}, [])
console.log(data)
<form id="myForm">
<input type="text" name="dummy">
<input type="text" name="people[0][first_name]" value="John">
<input type="text" name="people[0][last_name]" value="Doe">
<input type="text" name="people[1][first_name]" value="Jane">
<input type="text" name="people[1][last_name]" value="Smith">
</form>
function getObject(name, key) {
if(key.includes(name)) {
var splitStr = key.split(/\[|\]/g);
return {
index: splitStr[1],
key: splitStr[3],
}
}
return null;
}
function getFormDataByInputName(name) {
var formData = new FormData( document.querySelector('#myForm'));
var results = [];
for (var key of formData.keys()) {
var obj = getObject(name, key);
if (obj) {
if (results[obj.index]) results[obj.index][obj.key] = formData.get(key);
else results[obj.index] = { [obj.key]: formData.get(key) };
}
}
return results;
}
var people = getFormDataByInputName('people');
console.log(people);
<form id="myForm">
<input type="text" name="dummy">
<input type="text" name="people[0][first_name]" value="John">
<input type="text" name="people[0][last_name]" value="Doe">
<input type="text" name="people[1][first_name]" value="Jane">
<input type="text" name="people[1][last_name]" value="Smith">
</form>
Your code won't work because to HTML/JS name is just a string that it sends to the server when the form is submitted (the name in the name/value pairs). You might think it is arrays, but HTML/JS doesn't.
So no one-liner to get the job done. Try this: In your HTML, add <div class="name"> ...
(UPDATE: thanks for the idea, #Nenad, I've never tried one of these snippets)
var people = [];
$('.name').each(function() {
people.push({
first_name: $('input:nth-child(1)', this).val(),
last_name: $('input:nth-child(2)', this).val()
});
});
console.log(people);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<input type="text" name="dummy">
<div class="name">
<input type="text" value="John">
<input type="text" value="Doe">
</div>
<div class="name">
<input type="text" value="Jane">
<input type="text" value="Smith">
</div>
</form>
Use CSS attribute prefix selector, such as
form.querySelectorAll('[name^="people[]"]')
You can use a for-loop to get all peoples, as such
const MAX_PEOPLES = 2;
const list = [];
for (i = 0; i <= MAX_PEOPLES; i++) {
const eles = form.querySelectorAll(`[name^="people[${i}]`);
if (eles.length !== 2)
break;
list.push({
first_name: eles[0].value,
last_name: eles[1].value
});
}
that yields
[
{
"first_name":"John",
"last_name":"Doe"
},
{
"first_name":"Jane",
"last_name":"Smith"
}
]
I want to search the House Name from all the input the user provided.
so if the user details are as:
[{"houseName":"man","houseType":"villa","houseFloors":"seven","houselocation":"Seattle"},{"houseName":"band","houseType":"small","houseFloors":"two","houselocation":"washington DC"}]
If i provide search as man ,it should give me as:
[{"houseName":"man","houseType":"villa","houseFloors":"seven","houselocation":"Seattle"}]
The code is as :
<html>
<head>
<title>JavaScript</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label>House Name
<input type='text' name='houseName' id='houseName' placeholder="House Name">
</label>
<br>
<br>
<label>House type
<input type='text' name='houseType' id='houseType' placeholder="House type">
</label>
<br>
<br>
<label>House Floors:
<input type='text' name='houseFloors' id='houseFloors' placeholder="House Floors">
</label>
<br>
<br>
<label>House Location:
<input type='text' name='houselocation' id='houselocation' placeholder="House Location">
</label>
<br>
<br>
<div>
<label>search:
<input type="text" name="search" id="search-input" placeholder="search">
<input type="submit">
</div>
<button type="button" id="add">Add Details</button>
<button type="button" id="print">Show</button>
<pre></pre>
<script>
var list = [],
$ins = $('#houseName, #houseType, #houseFloors, #houselocation'),
var counter = {
houseName: {},
houseType: {},
houseFloors: {},
houselocation: {}
};
$('#add').click(function() {
var obj = {},
valid = true;
$ins.each(function() {
var val = this.value;
if (val) {
obj[this.id] = val;
} else {
alert(" Cannot be blank");
return false;
}
});
if (valid) {
list.push(obj);
$ins.val('');
}
});
$('#print').click(function() {
$('pre').text(JSON.stringify(list) + '\n\n');
})
var keyword = $('#search-input').val();
var filteredList = list.filter(function(user){
return user.houseName === 'man'; // Or u can use indexOf if u want check if the keyword is contained
});
</script>
</body>
</html>
You may use Array.prototype.filter.
In ur case it will look like
var filteredList = list.filter(function(user){
return user.houseName === 'man'; // Or u can use indexOf if u want check if the keyword is contained
});
If u would like to search it with an input box, there will be a little bit more work to do:
//The follow code should be executed when u are going to do the 'search' action
//It could be an click on a button, or just in a listener which is triggered when the search box fires 'change' events
//First u need to get the keyword from the search input box:
var keyword = $('#search-input').val();
//maybe do some value check
//if (keyword === '') return;
//then get the filtered List
var filteredList = list.filter(function(user){
return user.houseName === keyword;
});
//Finally update the UI based on the filtered List
//Maybe jQuery's DOM functions could be helpful
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>
<html>
<head></head>
<body>
<form name="abc" action="#" method="post">
Name: <input type="text" name="name"><br>
Age : <input type="text" age="name"><br>
<input type="submit"><br>
</form>
</body>
</html>
Can any one write this HTML code in such a way that when I will submit this form the the form data will be submitted in JSON format .
A pure JavaScript solution would be:
var form = document.getElementsByTagName('form')[0];
form.addEventListener('submit',function(event){
event.preventDefault();
var data = {
"name":this.name.value,
"age":this.age.value
};
console.log(data);
});
Try substituting name="age" for age="name" at second input type="text" , utilizing .serializeArray() , $.post()
$("form").submit(function(e) {
e.preventDefault();
var data = $(this).serializeArray();
console.log(data);
// $.post("/path/to/server", data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<form name="abc" action="#" method="post">
Name:
<input type="text" name="name">
<br>Age :
<input type="text" name="age">
<br>
<input type="submit">
<br>
</form>
check this function
var formDataToObject = function (formElm) {
var formObj = new FormData(formElm),
result = {},
values = formObj.values(),
keys = formObj.keys(),
key;
while (!(key = keys.next()).done) {
result[key.value] = values.next().value;
}
return result;
};
Two notes here:
1) No support for multiple select options, it will return the last selected option!!
2) The loop breaks when the next() return object with done equals to true,
but this object also contains the key for the last element in the form
which is in most cases the Submit Button, so if you don't have one in the form the last element will be excluded, easy to fix.