Update div when typing in text field - javascript

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.

Related

Linking form and button to javascript command

I am trying to make a simple form and button work. I have linked to a JS Fiddle here View JS Fiddle here
<form>
<input type="text" class="form-control" id="search" placeholder="enter sport">
<button type="submit" id="WFFsearch">Search</button>
</form>
$('#WFFsearch').on('click', function () {
var searchInput = $('#search').text();
var url = "http://espn.go.com/" + searchInput + "/statistics";
window.open(url);
});
I want to be able to enter "nba" without the quotation marks and click the search button, then have a new window which generates the following link http://espn.go.com/nba/statistics. The first part and the last part of all the urls will be the same, it's just the middle that changes (nba, nfl, mlb). Any help would be greatly appreciated, thanks!
$('#WFFsearch').on('click', function () {
var searchInput = $('#search').val();
var url = "http://espn.go.com/" + searchInput + "/statistics";
window.open(url);
});
You need val() property, since input is in question, not text(). https://jsfiddle.net/1c93pqj0/2/
you wanna use the .val() instead of .text() as text gets the value between 2 tags <div>here is some text</div> and val gets the value <input value="some value"/>
EzPz! This is a very simple task. First of all though, since you're using jQ to establish your button's click event, you can either drop the attribute type="submit", OR (recommended), create your event on the form's submit. If it were me, I'd id the form and use the forms submit, so that you don't need any alters to your button type="submit" and enter key can still be used in search box to submit the form.
Also, you're trying to .text on an input. Input's have value. In jQuery you can get or set that value by calling .val() instead.
The code:
$('#frmGetStats').on('submit', function (e) {
e.preventDefault();
var searchInput = $('#search').val(),
url = "http://espn.go.com/" + searchInput + "/statistics",
win = window.open(url);
alert("In this sandbox, new windows don't work. \nHowever you can see the link is \n[" + url + "]");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form id="frmGetStats">
<input type="text" class="form-control" id="search" placeholder="enter sport">
<button id="WFFsearch" type="submit">Search</button>
</form>
To get the value of an input field, use .val(). .text() is for the text in a DOM element.
Clicking on the submit button submits the form by default, which reloads the page and kills the script. You need to return false from the event handler to prevent this.
$('#WFFsearch').on('click', function () {
var searchInput = $('#search').val();
var url = "http://espn.go.com/" + searchInput + "/statistics";
window.open(url);
return false;
});
DEMO

How can I filter data returned from jQuery?

jQuery code:
$(document).ready(function() {
$('#s-results').load('get_report1.php').show();
$('#search-btn').click(function(){ showValues(); });
$(function() {
$('form').bind('submit', function() { showValues(); return false; });
});
function showValues() {
$.post('get_report1.php', { name: form.name.value },
function(result) {
$('#s-results').html(result).show();
}
);
}
});
HTML:
<form name = "form">
<div>Enter name</div>
<input type="text" name="name" id="fn" />
<input type="submit" value="Search" id="search-btn" />
<div>
<input type="text" id="se2" name="search22">
</div>
</form>
<div id = "s-results" style="height:50px;">
</div>
Up to this the script is running perfectly. Now I just want to filter the returned HTML from the above function again.
For implementing this I have tried this line of code:
$(result).filter('#se2');
under the function with the result parameter, but it is not working.
So how can the returned HTML code be filtered?
You probably need find() instead of filter as you need to get the descendant whereas filter "Reduce the set of matched elements to those that match the selector or pass the function's test"
Live Demo
$(result).find('#se2');
If the #se is added in DOM then you can directly use the id selector
se = $('#se2');
I made another demo (as I am still waiting for your demo that is not working) to further elaborate how a string containing the html you have could be passed to jQuery function $() to search elements within it using find.
Live Demo
html = '<form name = "form"> \
<div>Enter name</div> \
<input type="text" name="name" id="fn" /> \
<input type="submit" value="Search" id="search-btn" /> \
<div> \
<input type="text" id="se2" name="search22" value="se2"/> \
</div> \
</form>\
<div id = "s-results" style="height:50px;"> \
</div> ';
alert($(html).find('#se2').val());
Note You can further check the code working in the example above by using find wont work by using filter over this jsfiddle example
The issue
You are successfully adding the result to #s-results:
$('#s-results').html(result).show();
And then tried to select #se2 from the added results like this, with no success:
$(result).filter('#se2');
It didn't work because you didn't get it from the dom added in the second step.
Actually, it is creating a new unattached dom with the same result variable.
The solution
To select #se2 from the added result content correctly, try the following:
$('#s-results').filter('#se2');
Or, as suggested by #zerkms, you could select it directly through:
$('#se2');
These possibilities will work, because now it is referencing something attached to dom, which will search into the same elements you added in the first step.
You can try to use ajax for this as below:
$(document).ready(function () {
$('#s-results').load('get_report1.php').show();
$('#search-btn').click(function () {
$.ajax({
type: "POST",
url: "get_report1.php",
data: {
name: $("#fn").val()
},
beforeSend: function () {
//do stuff like show loading image until you get response
},
success: function (result) {
$('#s-results').html(result).show();
},
error: function (e) {
alert("Error in ajax call " + e);
}
});
});
});
Note: When you click on search-btn each time it will call the get_report1.php file and retrieve the data base on the text-box value that you have passed. I assume that in ge_report1.php file you are using the tex-box value like: $_POST['name'] and you are fetching the data using MySQL search query.
You can use JQuery find instead of filter.
$(result).find('#se2');
Then add to your variable like this
var your_element = $('#se2');

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());

AJAX call to backend PHP file and making result appear in HTML span

I have an AJAX call to a PHP file that performs some date calculations. I can confirm that it works if I place a text field on the form and put the focus in it after the start and end dates are entered (i.e., if I enter 1/1/2014 and 12/31/2014, I get 260 if I tab over to my "result" field).
What I'm trying to do now is have the result show up in a span after the end date is entered. That way, the user doesn't have to tab over to a text field to see it. Here is my jQuery code to call the file and display the result in the span:
$(function()
{
$('#result').focusin(function(event) //'result' is the name of the span
{
var start = $('#startDate').val();
var end = $('#endDate').val();
$("#endDate").on('input',function() {
var dateRegex = /(\d{1,2}\/\d{1,2}\/\d{4})/gm;
if(dateRegex.test($("#endDate").val()) ) { //Make sure date is formatted correctly
$.ajax(
{
type: 'POST',
url: 'calcdays.php',
data:
{
startDate: start,
endDate: end
},
success: function(data)
{
$('#result').html(data);
}
}); //End ajax
} //End if
}); //End regex function
event.preventDefault();
}); //End focusin
}); //End function
And here is the form setup:
<label for="startDate">StartDate</label>
<input type="text" name="startDate" id="startDate" />
<label for="endDate">EndDate</label>
<input type="text" name="endDate" id="endDate" />
Result: <span id="result"> </span>
I'm not able to make my result appear within the span. What did I miss?
There are no focus events on spans I think. I think you meant
$('input[name="endDate"]').blur(function(event) {
But there is nowhere to blur out of endDate. You need to define, what does "end date is entered" mean. User press enter key? Or tab button and blurs somewhere? Or you can use keyup to check value of current end date
$('input[name="endDate"]').keyup(function(event) {
Anyway you should remove focusein part, you just bind something to event, which happens with enddate input, you can bind it right after document ready.

How to make simplier the jquery code

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>

Categories

Resources