I have a button which appends a drop down menu to the site, and within the drop down value attribute are numbers. I’m using an ajax function to run a math equation using the values from the drop down.. this is my code:
var data1 = $('#data1').val();
var data2 = $('#data2').val();
var data3 = $('#data3').val();
$.ajax({
type: 'GET',
url: 'ajaxcalc.php',
data: {
data1: data1,
data2: data2,
data3: data3
},
dataType: 'json',
cache: false,
success: function(data) { alert('yay!'); })
});
},
});
//show dropdowns code
$('#data1').click(function() {
var $d = $('<select name="data1" id="data1"><option selected="selected" value="null">Choose your data!</option><option value="5">Option 1</option><option value="1">Option 2</option><option value="14">Option 3</option></select><br/>').fadeIn().delay(1000);
$('.data1').append($d);
});
//html button code for append data1 drop down
<button id="data1">Add Dropdown</button>
My problem comes in when people append 2 of the same drop downs with the same id and I can’t retrieve both variables… It only gets the first drop down value!
in my ajaxcalc.php file I have this to retrieve variables:
$data1 = $_GET['data1'];
$data2 = $_GET['data2'];
I’m trying to allow someone to append the data1 drop down twice and pick 2 different values but still pass those values to my ajaxcalc.php file through the .ajax() function! does anyone know how I can accomplish this?
In your case you don’t have an
idof “data2” or “data3”. You keep appending “data1”. When appending the dropdown, you need to increment the number with the id.Try using that code in place of your dropdown code.
EDIT
A better solution would be to use a class instead of
ids. If each dropdown had aclassyou could select them all (no matter how many were added) and loop through them to get values.EDIT2
Here is a fiddle I through together showing how you can add multiple dropdowns and pass an array back to your PHP page rather than individual variables.
http://jsfiddle.net/JtUuN/