Change one value uploaded from a form using jQuery - javascript

I have a form.
<form id="myForm">
<input type="text" name="e1" id="e1" value="1" />
<input type="text" name="e2" id="e2" value="2" />
<input type="text" name="e3" id="e3" value="3" />
<input type="text" name="e4" id="e4" value="4" />
<input type="text" name="e5" id="e5" value="5" />
</form>
I use the jQuery validation plugin http://jqueryvalidation.org/ to validate and submit the form.
var validator=$("#myForm").validate({
rules: {},
submitHandler: function(form) {
var data1=$(form).find(':input');
var data2=data1.serializeArray();
//Use ajax to post data2 or submit form...
}
});
Instead of submitting the exact values in the form, I would like to change one of them. For instead, the server should receive a value of "333" instead of "3" for $_POST['e3'].
I don't wish to change the value of the #e3 input on the page. I would rather not use a hidden input to do so, nor manually create my object to upload. How do I change either the data1 object or data2 object to reflect the new value for #e3?
EDIT. Live example at http://jsfiddle.net/rueL9y0p/1/ data1 and data2 values are:
Object { 0=input#e1, 1=input#e2, 2=input#e3, more...}
[Object { name="e1", value="1"}, Object { name="e2", value="2"}, Object { name="e3", value="3"}, Object { name="e4", value="4"}, Object { name="e5", value="5"}]

Simply change the value of the element just before it's submitted, and the serialized array will reflect the new value. Then after your ajax (or after you serialize the data for your ajax), you can easily change the value back to the original.
Insert your conditional logic as needed...
submitHandler: function(form) {
var original = $('#e3').val(); // original value
$('#e3').val('your new value'); // insert new value
// ajax() here // submit via ajax
$('#e3').val(original); // change the value back after the ajax is complete
}
Maybe you'll want to change the value back from within the ajax() complete callback function.
DEMO: http://jsfiddle.net/rueL9y0p/4/

Just as another solution, you could clone the form and make changes to the cloned element.
e.g.
var formClone = form.clone(),
name = formClone.find('#name');
name.val('NEW VALUE');
You would then serialize the cloned form and send that data off to the server.
JSFiddle

haim770 previously posted this as an answer, but he later deleting it. Seems good to me. Any reason why he might have deleted it?
var data1 = $('#myForm').find(':input');
var data2 = data1.serializeArray();
console.log(data1);
console.log(data2);
data2.forEach(function(i) { if (i.name === 'e3') i.value = '333' });
console.log(data2);
http://jsfiddle.net/rueL9y0p/3/

Related

how to pass values from multiple textfields with same name attributes to a variable in form of an array

I am building a form that passes a set of numbers in form of an array to a variable as seen below
var users=["1","2"];
the main purpose of this is to then make an Ajax request with these numbers and get their corresponding content in my database which I then pass to their respective divs, please see below
var users=["1","2"];
var async_request=[];
var responses=[];
for(i in users)
{
// you can push any aysnc method handler
async_request.push($.ajax({
url:'back.php', // your url
method:'post', // method GET or POST
data:{user_name: users[i]},
success: function(data){
console.log('success of ajax response')
responses.push(data);
}
}));
}
$.when.apply(null, async_request).done( function(){
// all done
console.log('all request completed')
console.log(responses);
$( '#responses' ).html(responses[1]);
$( '#responses1' ).html(responses[0]);
});
This works perfectly.
But now I want to make some adjustments to my solution specifically
Im looking to replace the method of passing the numbers to the variable users
from
var users=["1","2"]; // Im looking to replace the method
to this
var users = $('[name="tom[]"]').val(attachArray);
<input type="text" name="tom[]" value="1" /><br>
<input type="text" name="tom[]" value="2" /><br>
but I am unable to get the the ids from the two textfields and then pass to my database using my Ajax script as I did before with this
var users=["1","2"];
You mean
const arr = ["1", "2"]
$('[name^=tom]').val(function(i) {
return arr[i]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="tom[]" value="" /><br>
<input type="text" name="tom[]" value="" /><br>
or
$('[name^=tom]').each(function() {
async_request.push($.ajax({
url:'back.php',
method:'post',
data:{user_name: this.value },
You forgot to use input key value :
var users = $('input[name="tom[]"]').val();

Always returns a undefined value

I am using jQuery to send Ajax request to the server to save the values being input in the form. Below the section where I am stuck. The HTML is as
<span class="no-margin multiple Date_Off" style="margin-left: 104px;">
<input type="text" value="" /><input type="text" />
<input type="text" value="-" /><input type="text" />
<input type="text" /><input type="text" value="-" />
<input type="text" /><input type="text" /><input type="text" />
<input type="text" />
</span>
I have tried using jQuery to send the request. What I want to do is something like this
I want to save the values from the form, to the same Column_Name that the input fields have. In the multiple input fields I am not using input names. Instead I am using a classname which is identical to the Column_Name in the database.
For that, I am using $(this).parent().attr('class');. If I use this in an alert, it gives me the result without error. But if I use it in the code, it gives me undefined.
I want to append each input's value to the string to save it as a single string.
Here is what I tried so far
var input = $('input');
input.change(function () {
// Input click function...
if ($(this).parent().attr('class')
.replace(' multiple ', '')
.replace('no-margins', '') == 'Date_Off') {
// Date Time for the office work!
var value = '';
value = $(this).parent().find('input').each(function (index, ele) {
value += ele.val();
});
send_request('Date_Off', value);
// Below is the else condition, to execute only when the input is single
// Like a single string input and not like the one in image
// That's why I am using attr('name') for that.
} else {
send_request($(this).attr('name'), $(this).val());
}
});
But what it returns is always a undefined in the Query structure. Here is the function for that
function send_request(input_name, value) {
$.ajax({
url: '/ajax_requests/save_form',
data: 'input_name=' + input_name + '&form_id=' +
$('input[type=hidden]').val() + '&value=' + value,
error: function () {
$('.main-content').append(
'There was an error in request.
Please contact your website Developer to fix it.'
);
},
success: function () {
}
});
}
Image for the code execution
The input in focus was 1. Date. And the console shows the Internal Server Error. Because jQuery sent the request with input_name=undefined which is not a Column_Name.
I have created a (Mini) fiddle for that: http://jsfiddle.net/afzaal_ahmad_zeeshan/EHWqB/
Any help here?
For the fiddle that you posted, there were two errors. The first was you were calling ele.val(), but ele in this context is not a jQuery object - so you need to get the value property off of it. The second is that the jQuery each function operates on an array of objects and it's return value is that array of objects. You don't want your value, which should be a string, to be accepting that return value. Here is an updated, working fiddle
input.change(function () {
// Input click function...
var value = '';
$(this).parent().find('input').each(function (index, ele) {
value += ele.value;
});
send_request('Date_Off', value);
});
In this line you're trying to get the name of the input
send_request($(this).attr('name'), $(this).val());
I don't see a "name" attribute anywhere in your code, I think what you want is to get the class of the parent instead?
send_request($(this).parent().attr('class'), $(this).val());

jQuery: How to submit an array in a form

I have the following form. Each time the users clicks add_accommodation I want to add to an array that I will return to the end point (http://server/end/point).
<form action="http://localhost:3000/a/b/c" method="post">
<div>
<input type="hidden" id="Accommodation" name="accommodation"><div>
</div>
</form>
<div id="accommodation_component">
<div>
<label for="AccommodationType">Type:</label>
<input type="number" step="1" id="accommodationType" name="accommodation_type" value="0">
</div>
<div>
<button type="button" id="add_accommodation">Add Accommodation</button>
</div>
</div>
<script>
$( document ).ready(function() {
$('#add_accommodation').click(function() {
make_accommodation(this);
});
});
function make_accommodation(input) {
var value = {
type : $("#AccommodationType").val(),
};
var accommodation = $('#Accommodation').attr('id', 'accommodation');
accommodation.push(value);
console.log(accommodation);
}
</script>
At my end point I want the result to be and array (accommodation = [{1},{2},{3},{4}]). How can I do this?
Give the form an id, and just append a new hidden(?) input that has a name that has [] at the end of it, it will send the values as an array to the server.
HTML
<form id="myform" ...>
Javascript
function make_accommodation(){
var newInput = $("<input>",{
type:"hidden",
name:"accommodation[]",
value: {
type: $("#AccommodationType").val()
}
});
$("#myform").append(newInput);
}
Also you list the output as [1,2,3,4] but your code shows you setting the value as an object with a property type and setting it to the value of the accommodation input, i am going to assume that was a mistake. If I am mistaken just modify the value property in the code above.
Also in your code you change the id of the input, not sure why you were doing that as it serves no purpose and would have made your code error out so i removed it.
EDIT
Since you are wanting to send an array of objects, you will have to JSON.stringify the array on the client end and decode it on the server end. In this one you do not need multiple inputs, but a single one to contain the stringified data.
var accommodationData = [];
function make_accommodation(){
accommodationData.push({
type: $("#AccommodationType").val()
});
$("#accommodation").val( JSON.stringify(accommodationData) );
}
Then on the server you have to decode, not sure what server language you are using so i am showing example in PHP
$data = json_decode( $_POST['accommodation'] );
If you are using jQuery's ajax method you could simplify this by sending the array data
jQuery.ajax({
url:"yourURLhere",
type:"post"
data:{
accomodation:accommodationData
},
success:function(response){
//whatever here
}
});
Add antorher hidden field in form
<input type="hidden" name="accommodation[]"> // click1
<input type="hidden" name="accommodation[]"> // click2
...
<input type="hidden" name="accommodation[]"> // clickn
Then when you submit form on server you will have array of accommodation.
JS part :
function make_accommodation() {
$(document.createElement('input'))
.attr('type', 'hidden')
.attr('name', 'accommodation[]')
.val($("#AccommodationType").val())
.appendTo('form');
}
on server(PHP) :
print_r($_POST['accommodation']);
Since you're using jQuery you can create a function which creates another hidden field, after clicking on the button
<div id='acommodation-wrapper'></div>
<button type="button" id="add_accommodation" onclick="addAnother()">Add Accommodation</button>
<script type="text/javascript">
function addAnother(){
var accWrapper = $('#accommodation-wrapper');
var count = accWrapper.children().length;
var div = "<input type=\"hidden\" class=\"accommodation-"+count+"\" name=\"accommodation["+count+"]\"></div>";
accWrapper.append(div);
}
</script>

Pass variable value from form javascript

Say I got a HTML form like below and want to pass the values in the textfields to JS variables.
<form name="testform" action="" method="?"
<input type="text" name="testfield1"/>
<input type="text" name="testfield2"/>
</form>
I've only passed values to variables in PHP before. When doing it in javascript, do I need a method? And the main question, how is it done?
Here are a couple of examples:
Javascript:
document.getElementById('name_of_input_control_id').value;
jQuery:
$("#name_of_input_control_id").val();
Basically you are extracting the value of the input control out of the DOM using Javascript/jQuery.
the answers are all correct but you may face problems if you dont put your code into a document.ready function ... if your codeblock is above the html part you will not find any input field with the id, because in this moment it doesnt exist...
document.addEventListener('DOMContentLoaded', function() {
var input = document.getElementById('name_of_input_control_id').value;
}, false);
jQuery
jQuery(document).ready(function($){
var input = $("#name_of_input_control_id").val();
});
You don't really need a method or an action attribute if you're simply using the text fields in Javascript
Add a submit button and an onsubmit handler to the form like this,
<form name="testform" onsubmit="return processForm(this)">
<input type="text" name="testfield1"/>
<input type="text" name="testfield2"/>
<input type="submit"/>
</form>
Then in your Javascript you could have this processForm function
function processForm(form) {
var inputs = form.getElementsByTagName("input");
// parse text field values into an object
var textValues = {};
for(var x = 0; x < inputs.length; x++) {
if(inputs[x].type != "text") {
// ignore anything which is NOT a text field
continue;
}
textValues[inputs[x].name] = inputs[x].value;
}
// textValues['testfield1'] contains value of first input
// textValues['testfield2'] contains value of second input
return false; // this causes form to NOT 'refresh' the page
}
Try the following in your "submit":
var input = $("#testfield1").val();

Sending form array values trought ajax

So my php needs 2 values, operation => string and data => array. The following is the form (dynamically generated inputs) :
<form method="post" action="/operations.php">
Title: <input type="text" value="valuehere" name="data[title]">
.
.
.
Description: <textarea name="data[description]"></textarea><br>
<button class="btn janitor_edit" type="submit">Edit Media</button>
<input type="hidden" value="operateMePls" name="operation">
<input type="hidden" value="254" name="data[id]">
</form>
And now I have to create an array from all data[xyz] in the form, but I'm having trouble finding a way to do so. The closest I've come to was doing like so: link
I must store the array as key/values, no other way, so I can ajax_request = { operation: operation_input, data : input_array_data };.
Oh, and the form works as expected when submiting "normaly" trought POST.
If the form works by itself, then let jQuery take care of it converting the data into a form suitable for XHR for you.
data: $('#your_form').serialize();
I've used an object instead of an array. When you json_decode in PHP, pass "true" as your second argument, and the data will come out as an array. I think this is what you wanted. Please comment if you were looking for something different.
$(".janitor_edit").click(function () {
var data = {};
data.operation = $("input[name='operation']").val();
data.data.id = $("input[name='data\\[id\\]']").val();
data.data.title = $("input[name='data\\[title\\]']").val();
data.data.description = $("input[name='data\\[description\\]']").val();
});

Categories

Resources