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

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/

Related

Attaching textbox value to a link in the form of a variable without using submit button

I was wondering how it would be possible to attach an HTML form's text box value to a link. For instance, I have 3 links and each link goes to a different PHP file, however, I need to pass a variable. Because of the design of my page, I cannot use buttons. So, I created a form with a text field. How do I send that Text Fields value with the links?
EG:
<form>
<input type="text" name="test1" id="test1"></input></form>
Link 1
Link 2
Link 3
I hope this makes sense as to what I am trying to do.
EDIT:
I tried to do this dynamically, but:
OK, I made a function like this:
<script>
function awardcode()
{ var awamount = document.getElementById("awardamount");
document.write('<?php $awardvar = ' + awamount.value + '; ?>');
};
</script>
Then, I made the link via PHP that looks like this:
echo '<a id=awlink3 name=awlink3 href="index.php?siteid=gmaward&type=xp&post=' . $posts_row['posts_id'] . '&handle=' . $posts_row['handle'] . '&varamount=' . $awardvar . '">Award XP</a>';
However, that didn't work. This is my input box code:
<form><input type=text name='awardamount' id='awardamount' onchange='awardcode()' style:'width:10px;'></form>
When I put the number and then tab, it loads an empty page.
How can I adjust that?
You'll need to dynamically change the link using JavaScript. Here's one approach:
$('a').on('click',function(e) {
e.preventDefault();
var url = $(this).attr('href').split('$')[0];
window.location = url + $('#test1').val();
});
But it might be better to add an onchange event to the textbox itself, so that the HREF changes instantly and the user can see the intended destination on mouseover:
$('#test1').on('change', function () {
var val = $(this).val();
$('a[href*=\\?id\\=]').each(function (i, el) {
$(el).attr('href', function (j, str) {
return str.split('?')[0] + "?id=" + val;
});
});
});

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

Settings Selector Dynamically in JQuery

I have a table whose values are being generated dynamically with PHP, including the id and name attributes (e.g. id="question_".
How can I set an element attribute with this in mind? For example, I have a div whose text will change after a successful ajax call, but the id is dynamic.
I have tried making the following test function, and calling it on an onclick event:
function approve(question_id)
{
var div = 'suggestion_status_' + question_id;
$('#div').html('test');
}
But that does not work. How can make the value of variable 'div' the selector?
The problem with your example is that div is a variable, not a string; so the following will work:
function approve(question_id)
{
var div = 'suggestion_status_' + question_id;
$('#' + div).html('test');
}
Or even:
function approve(question_id)
{
$('#suggestion_status_' + question_id).html('test');
}
Another approach would be to utilize classes, and add a known class to your elements. Without seeing the full HTML, I can't provide a full example, but something like this would be the way to go:
$('.yourCommonClass').bind('click', function () {
var that = this;
jQuery.get('/accept.php', {
id: this.id
}, function (msg) {
$(that).html('Accepted!');
});
});
Bearing in mind that jQuery.get parameters are the target url, optional data attributes that are encoded in the request, and then a callback function.
you defined div as a variable then used it as a string try concatenating it instead
function approve(question_id)
{
var div = 'suggestion_status_' + question_id;
$('#'+ div).html('test');
}
or shorten like this
function approve(question_id)
{
$('#suggestion_status_' + question_id).html('test');
}
$('#suggestion_status_' + question_id).html('test');
$('#suggestion_status_' + question_id)
I think you want this:
function approve(question_id)
{
var div = 'suggestion_status_' + question_id;
$('#'+div).html('test');
}
this. $('#suggestion_status_' + question_id).html('test');

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

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

Print the value in loop in Jquery ready function

somehow still not able to do what I’m inted to do. It gives me the last value in loop on click not sure why. Here I want the value which is been clicked.
Here is my code:
$(document).ready(function() {
var link = $('a[id]').size();
//alert(link);
var i=1;
while (i<=link)
{
$('#payment_'+i).click(function(){
//alert($("#pro_path_"+i).val());
$.post("<?php echo $base; ?>form/setpropath/", {pro_path: $("#pro_path_"+i).val()}, function(data){
//alert(data);
$("#container").html(data);
});
});
i++;
}
});
Here the placement_1, placement_2 .... are the hrefs and the pro_path is the value I want to post, the value is defined in the hidden input type with id as pro_path_1, pro_path_2, etc. and here the hrefs varies for different users so in the code I have $('a[id]').size(). Somehow when execute and alert I get last value in the loop and I don’t want that, it should be that value which is clicked.
I think onready event it should have parsed the document and the values inside the loop
I’m not sure where I went wrong. Please help me to get my intended result.
Thanks, all
I would suggest using the startsWith attribute filter and getting rid of the while loop:
$(document).ready(function() {
$('a[id^=payment_]').each(function() {
//extract the number from the current id
var num = $(this).attr('id').split('_')[1];
$(this).click(function(){
$.post("<?php echo $base; ?>form/setpropath/", {pro_path: $("#pro_path_" + num).val()},function(data){
$("#container").html(data);
});
});
});
});
You have to use a local copy of i:
$('#payment_'+i).click(function(){
var i = i; // copies global i to local i
$.post("<?php echo $base; ?>form/setpropath/", {pro_path: $("#pro_path_"+i).val()}, function(data){
$("#container").html(data);
});
});
Otherwise the callback function will use the global i.
Here is a note on multiple/concurrent Asynchronous Requests:
Since you are sending multiple requests via AJAX you should keep in mind that only 2 concurrent requests are supported by browsers.
So it is only natural that you get only the response from the last request.
What if you added a class to each of the links and do something like this
$(function() {
$('.paymentbutton').click(function(e) {
$.post("<?php echo $base; ?>form/setpropath/",
{pro_path: $(this).val()},
function(data) {
$("#container").html(data);
});
});
});
});
Note the use of $(this) to get the link that was clicked.

Categories