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());
Related
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();
I have a textfield:
Voornaam: <h3 class="title1">Kevin</h3>
<input type="text" id="myTextField1" />
<input type="submit" id="byBtn" value="Change" onclick="change1()"/><br/>
I can set a value of this using this function:
function change1(){
var myNewTitle = document.getElementById('myTextField1').value;
if( myNewTitle.length==0 ){
alert('Write Some real Text please.');
return;
}
var titles = document.getElementsByClassName('title1');
Array.prototype.forEach.call(titles,title => {
title.innerHTML = myNewTitle;
});
}
Now in my other page, I want to use the value. I know I can for example pass a value from one page to another like this:
<a href='convert.php?var=data'>converteren.</a>
And then for example show it by doing this in the other page:
echo $_GET['var'];
But I cant really seem to figure out how to use the value which I've set using my textfield.
So my goal for now is to display the value I've set using my textfield in the other page using the method I just described.
Basically all I want to happen is for my textfield to change the value inside here aswell:
<a href='convert.php?var=data'>converteren.</a>
So where data is the value, I want it to become what I've put in the textfield.
Could anybody provide me with an example?
I've altered a bit your javascript code to make the link as you want.
To explain the answer, i've added document.getElementById("myLink").href="convert.php?var=" + myNewTitle ; which updates your a href while your function runs and is not empty.
function change1(){
var myNewTitle = document.getElementById('myTextField1').value;
if( myNewTitle.length==0 ){
alert('Write Some real Text please.');
return;
}
document.getElementById("myLink").href="convert.php?var=" + myNewTitle ;
var titles = document.getElementsByClassName('title1');
Array.prototype.forEach.call(titles,title => {
title.innerHTML = myNewTitle;
});
}
<a id="myLink" href='#'>converteren.</a>
Wrap your inputs inside a form element.
In the action attribute, specify the destination url.
In the method attribute, choose between GET and POST.
For example:
<form method="GET" action="convert.php">
<input type="text" id="myTextField1" />
<input type="submit" id="byBtn" value="Change" onclick="change1()"/>
</form>
Clicking the submit button will call "convert.php?myTextField1={value}".
I want to update a div while changing the value of a input field.
Eg.
<form>
<input type="text" name="test"><!--Eg. 5+5-->
</form>
<div id="SomeId">
<img src=loading.gif>
</div>
So when you changed the value of the input field, it updated the div SomeId, with a external file Eg. calculate.php?test=5+5
So how can I listen on updating a input field?
<input type="text" onkeypress="doSomething(this.value);"> will send the entire value of the input element to the function after every key press.
Note that best practice is to bind the function on page load using JavaScript, and not with onkeypress but doing the latter gives a one-line example.
Here's a doSomething function for testing:
function doSomething(what) {
console.log(what);
}
Edited to add: If you don't want to process every keystroke, use the onchange event:
<input type="text" onchange="doSomething(this.value);">
Another edit:
var timerHandle = false; // global!
function setTimer(what) {
console.log("Captured keys: " + what);
if (timerHandle) clearTimeout(timerHandle);
timerHandle = setTimeout(sendItOff,1000); // delay is in milliseconds
}
function sendItOff() {
what = document.getElementById("test").value;
console.log("Sending " + what);
}
The input element now has to have an ID:
<input type="text" name="test" id="test" onkeypress="setTimer(this.value);">
This uses a one second (1000 ms) timer. That is very short.
In the focusout of the text field, Call java script function that should call ajax call to that calculate.php.
Return response from php file and update that in particular div Id.
function onfocusoutupdatevalue(){
$.ajax({
type: "POST",
url: "calculate.php",
data: { value: "5+5" }
}).done(function( ans ) {
$("#SomeId").val(ans)
});
}
You need to add jQuery lib file.
I have a survey. On button click need it to validate certain fields required/store locally/ go to confirmation page(to prevent user from resubmitting). Only 'FirstName''Hostipal' required atm.
Problem is when all required fields are filled, it fails to go to confirmation.html. If i leave 1 required field open, It doesnt validate and goes to confirmation. If all 'required' syntax is taken out, It doesnt go to confirmation
<label>First Name*:</label> <input required title="Name is required" id="FirstName" name="MainName" type="text"/>
In all cases, It still stores to local storage however. Any input on validating required fields would be appreciated. Hopefully can put it in my clicked() function.
<button type="submit" value="Save" id="Save" >Submit Form</button>
function
$( document ).ready(function() {
$('#Save').click(function (e) {
if (confirm('Are you sure you want to submit? You will not be able to go back.')) {
var person = $("#FirstName").val() + "." + $('#LastName').val();
$('input, select, textarea').each(function () {
var value = $(this).val(),
name = $(this).attr('name');
localStorage[person + "." + name] = value;
window.location.href = "Confirmation.html";
console.log('stored key: ' + name + ' stored value: ' + value);
});
}
});
});
If the above doesn't show my problem, here is the whole: http://jsfiddle.net/smZHe/1/
each helper method in jquery executes the function we pass to it once for each item in the initial array. You are trying to execute below statement multiple times (once for each input, select, textarea).
window.location.href = "Confirmation.html";
You can use a variable instead as flag to mark validation failure. In the end, you can check variable and navigate conditionally.
Aim is to detect if after page load input values are changed.
Input fields (19 fields) for example
<input type="text" name="date_day1" id="date_day1" value=" >
<input type="text" name="date_month1" id="date_month1" value=" >
<input type="text" name="date_year1" id="date_year1" value=" >
<input type="text" name="amount1" id="amount1" value=" >
Then hidden input field like this
<input type="text" name="is_row_changed1" id="is_row_changed1" value="">
<script>
$("#date_day1").on("change", function () {
document.getElementById('is_row_changed1').value = 1;
});
$("#date_month1").on("change", function () {
document.getElementById('is_row_changed1').value = 1;
});
</script>
If in any of input fields (19 fields) value is changed, then I need to reflect it in this hidden input field (I decided to set the hidden input field value to 1).
After that ajax with php where I check if the hidden input field value is 1. If 1, then update mysql. Aim is to reduce usage of server resources.
Question
Javascript code for the hidden input field would be long. May be some way (code) to make is shorter (simplier)?
Add a row_changed class to each input then you can target them all with one call:
$(".row_changed").on("change", function () {
document.getElementById('is_row_changed1').value = 1;
});
(you can also simplify it even more with QuickSilver's comment.)
You could use JQuery selectors in order to set the same "input changed" callback for all input elements declared in your HTML code:
var anyFieldChanged = false; //Global variable
function changedCallBack()
{
anyFieldChanged = true;
alert('Fields changed');
}
allInputs = $('input');
allInputs.each(function() { this.onchange = yourCallBack(); });
I don't know if it's just in your example code, but you have several elements with the same ID, which is not valid. Each ID should be unique (which is the purpose of any ID). You can either add a class to each input you want to track and select on that like Shawn said or if you want to track every input except the hidden on the page you can use
$("input:[type!=hidden]").on("change", function () {
document.getElementById('is_row_changed1').value = 1;
});
Use like this.
<script>
$("#date_day1").on("change", function () {
$('#is_row_changed1').val(1);
});
$("#date_month1").on("change", function () {
$('#is_row_changed1').val(1);
});
// etc
</script>