Using jQuery .change() to change values in a <p> element - php

I have a select element with a few options for currencies, and then a <p> element at the bottom that currently prints the current exchange rate for USD to another currency. What I'm trying to do, is upon .change() of the select element value, I want to insert the value of the select element into a PHP script, and then re-.load() the <p> element.
How can I pass a value from jQuery .val() to a PHP script?

You might want something like:
$('select').change(function() {
$('p').load('/path/to/script.php?myVar=' + $(this).val());
});
Of course, you might want to use more specific selectors.

Use Ajax. Here's an example of how to do this with JQuery:
$('#selectElement').change(function(){
var currentSelection = $('#selectElement').attr('value');
$.get('yourScript.php?selection=' + currentSelection, function(data){
$('#pElement').html(data);
})
});
Or something like that. Not tested.

jQuery('#mySelect').change(function(){
jQuery.ajax({
url:'myPhpFile.php'
type:'get'
data:{currencyId:jQuery(this).val()},
success:function(data)
{
jQuery('#myDiv').html(data);
}
});
});

Related

Grab the name of an element with jquery

I have a series of Form Elements each with different names, I'll post one as an example. I cannot hard code the name into Jquery because unless I inspect the element, I won't know the name.
With that aside heres the element:
<label class="checkbox">
<input type="checkbox"
name="aisis_options[package_Aisis-Related-Posts-Package-master]"
value="package_Aisis-Related-Posts-Package-master" checked="" />
Aisis-Related-Posts-Package-master
(Disable)
</label>
The catch is to do this:
Grab the name of this element - upon clicking disable - and do two things, one - if the element is checked, which in this case it's not, unchecked it, two pass the name to a php variable, which then can do processing.
How would I do this? Jquery is not my strong area.
Here is a example without knowing more of your code:
$(function () {
$('input:checkbox').click(function () {
$(this).prop('disabled', true);
var iName = this.name;
$.ajax({
url: "file.php",
data: {
'inputname': iName
},
success: function (data) {
alert(data.returned_val);
}
})
})
})
Demo here
If you want to reach the input via name directly you need to use double backslasshes to escape the square brackets and reach that input via name. Use:
$('input[name=aisis_options\\[package_Aisis-Related-Posts-Package-master\\]]')
You can add an onchange with checkbox
onchange="f(this);"
in js f() function you can use this.name to get the name, this.value to get value etc and do whatever you want.
To check/unckeck, you can use $element.prop('checked', true/false); like this (fiddle):
HTML
<input
type="checkbox"
name="aisis_options[package_Aisis-Related-Posts-Package-master]"
value="...."
checked="checked"
/> Aisis-Related-Posts-Package-master
(Disable)
JS
$('.trigger').click (function () {
closest_checkbox = $(this).siblings('input[type=checkbox]');
closest_checkbox.prop('checked', !closest_checkbox.prop('checked'));
});
JS part 2: AJAX
You can build an object with all your name:value combinations using the jQuery plugin serializeObject, your form submission event handler would be something like:
$('form').submit( function (e) {
// Prevent the form from being sent normally since we want it ajaxified
e.preventDefault();
// Send request to php page
$.ajax({
type: "POST",
url: "some.php",
data: $('form').serializeObject() // <== Magic happens here
});
});
PS. Don't forget to include the serializeObject plugin and give a unique id to the form, $('#unique_id') is way better than $('form') which will match all the forms in the page.
To grab the value of name attribute, you can use:
$(this).attr('name');

Jquery script not showing in firebug or firing

I'm trying to get a drop down box to alter a second drop down box through the use of a jquery/ajax script. Firebug is showing Jquery is working but my script isn't showing at all.
<script type="text/javascript">
function ajaxfunction(parent)
{
$.ajax({
url: '../functions/process.php?parent=' + parent;
success: function(data) {
$("#sub").html(data);
}
});
}
</script>
process.php is just a MySQL query (which works)
My initial drop down box is populated by a MySQL query
<select name="front-size" onchange="ajaxfunction(this.value)">
//Query
</select>
And then the second drop down box is just
<select name = "front-finish" id="sub">
</select>
How can I solve this?
calling inline function is not good at all... as web 2.0 standards suggest using unobtrusive JS rather than onevent attributes....check out why here..
other thigs..correct way to use ajax is by using type and data ajax option to send values in controller..
<script type="text/javascript">
$(function(){
$('select[name="front-size"').change(function()
{
$.ajax({
url: '../functions/process.php',
type:'get',
data:{'value' : $(this).val()},
dataType:"html", //<--- here this will take the response as html...
success: function(data) {
$("#sub").html(data);
}
});
});
});
</script>
and your proces.php should be..
<?php
//db query ...thn get the value u wanted..
//loop through it..
$optVal .= "<option value="someDbValue">some DDB values</option>";
// end loop
echo $optValue;exit;
updated
looks like you still have onchange="ajaxfunction(this.value)" this in your select remove that it is not needed and the ajaxfunction in javascript too...
<select name="front-size" >
//----^ here remove that
use jQuery.on() that will allow us to add events on dynamically loaded content.
$('select[name^="front-"]').on('change',function(e){
e.preventDefault();
var value = $(this).val();
ajaxfunction(value);
});
[name^="front-"] this will select all the SELECT box having name starts with front-.
In your process.php give like this
echo "<select name='front-finish' id='sub' onchange='ajaxfunction(this.value)'>";
like this you need to add the "onchange" function to the newly created select box through ajax
or you can remove onchange function and write like
$("select[name^='front-']").live('change',function(){
//Do your ajax call here
});

How do I get the values and id's of multiple select lists and pass it to AJAX?

I am trying to iterate through a number of selects in a cell of a table (they are not in a form). I have a submit button when pressed is supposed to retrieve the values and id of each select list which I will pass to the server via AJAX and PHP. My table is a table of students of a course. The table contains the students name and their attendance for a lesson in the course.
This is my table on Pastebin and jsFiddle. http://pastebin.com/NvRAbC7m and http://jsfiddle.net/4UheA/
Please note that this table is entirely dynamic. The no. of rows and the info in them is dynamically driven.
This is what I'm trying to do right now with jQuery. Please excuse the logic or the complete nonsense that is my JavaScript skills. I don't actually know what I'm doing. I'm just doing trial and error.
$('#saveAttendances').live('click', function()
{
var attendSelect = $('.attendSelect');
var students = new Array();
//get select list values and id.
for(var i in attendSelect)
{
students['student_id'] += attendSelect[i].id;
students['student_id']['attedance'] += attendSelect[i].value;
console.log(students['student_id']);
}
//after retrieving values, post them through ajax
// and update the attendances of students in PHP
$.post("",{ data: array }, function(msg)
{
alert(msg);
});
});
How do I get the values and id's of each select list and pass it to AJAX?
Edit
If you insist on going against jQuery's grain and using invalid HTML, here's a suitable solution for you:
$(function() {
$('button').click(function(){
var data = $(".attendSelect").wrap('<form/>').serialize();
$.post('process.php', data, function(response){ ... });
return false;
});
});​
Worth mentioning, this example does not rely on fanciful .on() or .live() calls. However, this requires you to have the proper name attribute set on your <select> elements as described below. This also resolves your invalid numeric id attributes issue.
See it working here on jsFiddle
Original Answer
First off, some minor changes to your HTML. You need to wrap your <select> elements in a <form> tag. Using the form tag will give you access to jQuery's .serialize() method which is the exact functionality you're looking for. Personally, I'd recommend doing things the jQuery Way™ instead of implementing your own form a serialization. Why reinvent the wheel?
Next, your td have non-unique IDs. Let's update those to use a class attribute instead of an id. E.g.,
<td class="studentName">Aaron Colman</td>
Secondly, your <select> elements could benefit from a name attribute to make form processing way easier.
<select class="attendSelect" name="students[241]">
...
<select class="attendSelect" name="students[270]">
...
<select class="attendSelect" name="students[317]">
...
Lastly, jQuery's .serialize() is going to be your winning ticket.
​$(function() {
$('form').submit(function(){
$.post('process.php', $(this).serialize(), function(response){ ... });
return false;
});
});​
Upon submit, the serialized string will look something like
students[241]=Late&students[270]=Absent&students[317]=default
See it working here on jsFiddle
live() is deprecated as of jQuery 1.7, use on() instead
http://api.jquery.com/on/
students is an array, so I don't think you can do students['student_id'], if you would like to push an array of student, you can:
$('#saveAttendances').on('click', function() {
var students = [];
// iterate through <select>'s and grab key => values
$('.attendSelect').function() {
students.push({'id':$(this).attr('id'), 'val':$(this).val()});
});
$.post('/url.php', {data: students}, function() { // do stuff });
});
in your php:
var_dump($_POST); // see what's inside :)
As #nathan mentioned in comment, avoid using number as the first character of an ID, you can use 'student_<?php echo $id ?>' instead and in your .each() loop:
students.push({'id':$(this).attr('id').replace('student_', ''), 'val':$(this).val()});
Here's jQuery that will build an object you can pass to your script:
$('button').click(function() {
var attendance = new Object;
$('select').each(function() {
attendance[$(this).attr('id')] = $(':selected', this).text();
})
});​
jsFiddle example.
This results in: {241:"Late",270:"Absent",317:"Late"}
Edit: Updated to iterate over select instead of tr.
Perhaps you want something like below,
DEMO
var $attendSelect = $('#tutorTable tbody tr select');
var students = {};
$attendSelect.each (function () { //each row corresponds to a student
students[$(this).attr('id')] = $(this).val();
});
This would give you an object like below,
students = { '241': 'Late', '270': 'Absent', '317': 'default' };
If the above is not the desired structure then modify the .each function in the code.
For ex: For a structure like below,
students = [{ '241': 'Late'}, {'270': 'Absent'}, {'317': 'default'}];
You need to change the code a little,
var students = [];
...
...
students.push({$dd.attr('id'): $dd.val()});
var $select = $('.attendSelect'),
students = [];
$('body').on('click', '#saveAttendances', function() {
$select.each(function(k, v) {
students[k] = {
student_id : $(this).attr('id'),
attedance : $(this).val()
};
});
console.log(students);
});

How to get index of input in javascript - can use jQuery

I have an array of inputs generated from js code. I have set the name of the inputs like this: name="myTextInput[]"
How can I get the index of the selected input?
I tried something like:
onClick="oc(this);"
where:
function oc(inp)
{
return(inp.index);
}
but is not working.
I can use jQuery as well
You can use the EACH function in jquery. This will parse through the set of matched elements. You can put a custom function inside that will use the index of each element, as you parse through, as an argument.
$('input').each(function(index){
alert(index);
});
You can also get the value of each input like this:
$('input').each(function(index, val){
alert(index + ' has value: ' + val);
});
see details here: http://api.jquery.com/jQuery.each/
** EDIT **
If you want the value shown in an alert box on click, use the each function and the click function together. Remember to get the real-time value of the input, use $(this).val(). Return index and value data on click:
$('input').each(function(index, val){
$(this).click(function(){
alert(index + ' has value: ' + $(this).val());
});
});
You could get the input like this (not sure if you actually wanted the click event though)...
var inputs = $('input[name="myTextInput[]"]');
inputs.click(function() {
alert(inputs.index(this));
});
Please use the index() method to find the position of an element.
Check out this example: http://jsbin.com/uyucuv/edit#javascript,html
<ul>
<li id="foo">foo</li>
<li id="bar">bar</li>
<li id="baz">baz</li>
</ul>
$(function() {
$("li").on("click", function() {
alert($(this).index());
});
});
Check the index() documentation here: http://api.jquery.com/index/
Hope this helps!
The "jQuery way" is to avoid onClick="whatever()" and use pure JavaScript separate from the HTML tags. Try this between a pair of <script> tags (note: requires jQuery 1.7 or higher):
$('input').on('click', function() {
var varname = $(this).attr('name'),
$arr = $('input[name="'+varname+'"]'),
idx = $arr.index(this);
alert(idx);
});​
http://jsfiddle.net/mblase75/EK4xC/

How to preload a div combobox in jquery

I have code as follows:
$("#item_select").change(function()
{
var params = $("#item_select option:selected").val();
$.post('/account/ar_form.php', {idata: params}, function(data){
$("#message_display" ).html(data);
});
});
This is a dropdown that uses /account/ar_form.php to display html in the div correctly.
But it only displays on the change event. I'd like it to preload the data. When I use a load event, it will display the html, but on change, it displays it twice.
$("#item_select").change(function(){
var params = $("#item_select option:selected").val();
$.post('/account/ar_form.php', {idata: params}, function(data){
$("#message_display" ).html(data);
});
}).triggerHandler("change");
It depends a bit... what does your ar_form.php return with blank params?
You could do a hackish way (at fear of being downvoted) by calling
$("#item_select").change();

Categories