Does anyone know how to let ajax update text from a select input.
What I mean is if you select (form -> input) something, it will update/appear in a <span> or something.
This is what I have:
<?php
echo '<select name="test">';
for ($i=0; $i <= 20; $i++) {
echo '<option value="'.$i.'">'.$i.'</option>';
}
echo "</select>";
?>
And in the <script>:
<script>
function upperCase()
{
var A = document.getElementById('test').value;
var B = document.getElementById('txtHint1').value;
C = A * B
document.getElementById('result').value = C;
}
</script>
And where I want to show it:
<span id="txtHint1" onchange="upperCase()"></span>
I hope you understand me.
I see several errors in your original question. The first of which is here:
echo "<select name="test">;
Since it's a double-quoted string, you'll need to escape the double quotes around test, or surround the string in single quotes. You're also missing a closing quote. Is should look something like this:
echo '<select name="test">';
Also, rather than binding your onchange event to where you want to show the results, bind it to the element that, when changed, you want your JavaScript to execute. In this case, that would be your select. Now we're up to this:
echo '<select name="test" onchange="upperCase()">';
This line: C = A * B should look more like:
var C = A * B;
Additionally, your code is attempting to set the value of an element with ID result. According to your post, it seems that you may want to change that to txtHint1.
I'm assuming this is your scenario:
User selects an option from a drop down box
Once they have selected their option, the value of that option multiplied by your 'txtHint1' span is shown in the 'result' span
First, you don't need ajax to do that, just JavaScript, which I'm sure you meant. Next, you don't want onchange on your 'txtHint1' span, because there's nothing to change there. You want onchange to be on your 'select' element. You were very close in your code.
function upperCase()
{
var a = document.getElementById('test').value;
var b = document.getElementById('txtHint1').value;
var c = a * b;
document.getElementById('result').value = c;
}
<select name="text" onchange="upperCase()">YOUR PHP CODE<select>
I didn't test this, but it should work.
Related
So I have a php array that I am JSON encoding and handing to some JQuery. Basically I am using the information from the array to dynamically change the content of one drop down based on the value of another drop down. I am running into some problems with the JQuery though as JQuery is pretty new to me.
First off my PHP:
<?php
$sql = mysql_query("SELECT * FROM menu") or die(mysql_error());
$menuItems = array();
$x = 0;
while($row = mysql_fetch_object($sql))
{
$menuItems[$x]['ID'] = $row->ID;
$menuItems[$x]['parent'] = $row->parent;
$menuItems[$x]['name'] = $row->Name;
$menuItems[$x]['header'] = $row->header;
$menuItems[$x]['Sort'] = $row->sort;
$x++;
}
?>
This code returns an array of ~30 menu items.
Then my JQuery:
<script>
var menuItems = <?php echo json_encode($menuItems); ?>;
$('#dropdown1').change(function (){
if($('#dropdown1').val() == 0){
$('dropdown2').children().remove().end()
for(var x = 0; x < menuItems.length; x++){
if(menuItems[x]['header'] == 1){
$('#dropdown2').options[menuItems[x]['sort']] = new Option(menuItems[x]['name'], menuItems[x]['sort']);
}
}
}
});
</script>
What I want this to do is when dropdown1 is changed, dropdown2's options are removed and then repopulated with specific things from the array.
Currently this code does delete the options for dropdown2 when dropdown1 is changed but re-population just isn't working. From what I can tell in testing, the for loop to iterate through the array is only entered once, despite their being about 30 items in it and I assume that is were my main problem is.
What am I doing wrong here?
change it to
for(var x = 0; x < menuItems.length; x++){
if(menuItems[x]['header'] == 1){
var option = $('<option />', {
text : menuItems[x]['name'],
value: menuItems[x]['sort']
});
$('#dropdown2 option[value="'+[menuItems[x]['sort']]+'"]').replaceWith(option);
}
}
$('#dropdown2').options[] is not valid, as jQuery doesn't have those methods, that's for plain JS DOM nodes.
So from the comments there seemed to be some confusion on what I meant, and I apologize. It was one of the instances where the explanation made sense to me, but I just must not have conveyed everything well enough.
To clear up a little bit of the confusion. The array that was passed from the PHP code to the javascript contained everything I could ever need for the second drop-down.
As many pointed out the .options[] was the culprit for why the code wasn't executing. This was simply from another example I had found, and with my limited knowledge I assumed it was correct, and it wasn't.
I instead used the the .append() function and things seem to be working normally now.
I have this PHP Code which populates a select menu from a MySQL Database...
<select name="input" id="input">
<?php
$sql="SELECT * from table ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
while($result=mysql_fetch_array($rs))
{
echo '<option value="'.$result["db_field"].'">'.$result["db_field"].'</option>';
}
?>
</select>
which works perfectly fine but i need to somehow get it into a javascript function.
I have the javascript code that when you click a button it adds more text boxes and another select menu but it does not populate the data from the database in any new (added on) select menus
You can probably convert the options into JSON using json_encode (I am not a PHP programmer and dont know exact semantics of using it)
In PHP do something like:
echo '<script>var optionsJSON = '.json_encode(mysql_fetch_array($rs)).'</script>'
In javascriptn do something like (I am using jquery):
var select = $('select.classOfThisSelect');
var options = JSON.parse(optionsJSON);
for(var i = 0; i < options.length; i++)
$('option').attr({value: options[i]}).append(options[i]).appendTo(select);
optionsJSON will be the JSON string which will be globally available
You can freely use it in your Javascript function
Note: You may need to surround the json_encode with quotes
Start by converting the string of values into an array, so you have something like:
var values = ['value0','value1','value2'];
Then you can convert them to options and add them to a select element like:
function addOptions(select, values) {
for (var i=0, iLen=values.length; i<iLen; i++) {
select.appendChild(new Option(values[i],values[i]));
}
}
And call it like:
addOptions(document.getElementById('input'), values);
after the select is added to the page.
Incidentally, you don't need to add both an id and name to form controls. You must have a name for them to be submitted, the ID is unnecessary. If you get a reference to the form you can access controls as named properties of the form, so you might reference the select using:
document.forms[0]['input'];
or
document.forms[0].input;
and so on. Note that "input" isn't a good choice of control name.
The plan:
Basically I have a set of clothing items stored in a table each containing "item_name" "item_id" and "item_shortcode" I want to have a link per clothing item, when the user clicks the link the item needs to be added to an array (the selected array)
I'm trying to create a javascript object based off the data I've gathered from the mySQL database, then pass that data to a function when a div is clicked to my method.
this is an example:
<?php
while($row = mysql_fetch_array($results)){
?>
<script>
var item = new Object();
item.itemName = <?php echo json_encode($row['item_name']); ?>;
</script>
<?php
echo "<div id=\"".$row['item_name']."\" class=\"choice\" onclick=\"SetSelectedChoice(item);\">";
//echo $row['item_name'];
echo "</div>";
}
}
?>
EDIT: this is just an example I'll be populating my object with lots of data, not just item_name
problem is the last object seems to be assigned to every div in while loop.
Anyone point out where I am going wrong?
Well, i honestly don't know if i really got you, but if i see it right, then you simply overwrite the item-object in every run of the while-loop.
After the last loop (after this comes the output) the variable "item" is set to the last result of the loop, so clicking on any div will return "item" - the last item of the loop.
As a solution, try to save the rows name in the div as a parameter, like
echo "<div id=\"".$row['item_name']."\" class=\"choice\" onclick=\"SetSelectedChoice(\'".$row['item_name']."\');\">";
You're redefining item on every iteration. Why not do something like this:
As per edit, you can create an item array and populate it in the loop:
<script type="text/javascript">
var objects = new Array();
</script>
<?php while($row = mysql_fetch_array($results)): ?>
<script type="text/javascript">
var item = new Object();
item.itemName = '<?php echo json_encode($row['item_name']); ?>';
objects.push(item);
</script>
<div id="<?php echo $row['item_id']; ?>" class="choice">
<?php echo $row['item_name']; ?>
</div>
<?php endwhile; ?>
then in js OUTSIDE of your loop:
$('.choice').on('click', function(){
SetSelectedChoice($(this).html());
});
function SetSelectedChoice(name)
{
for(var i = 0; i < objects.length; i ++)
{
if(objects[i].itemName == name)
{
//do something
}
}
}
NOTE: I wouldn't really recommend this kind of weird loop for comparing names. I just don't know what else you are doing with passing the name to this function. I would pass the item id or the index value and directly access an item in the array instead of a loop. Make sense?
Basically, stop using onclick. The whole world is leaning more on listeners. Secondly, no need to create an object at all. You don't seem to be using it and even if you did, you didn't put single quotes around the name like you should for strings. Thirdly, please break out of php to write html. It's just cleaner and easier. Morely, assign the item's id to the id parameter. It gets really ugly to have names and spaces in the ids of elements. And you don't really seem to need one since you don't use it in your example. None the less, I put it in there in case you wanted to access it like $(this).attr('id') in the on click listener.
But if I missed the point, perhaps you can clarify and I may update to better fit your needs
i want to create array of same id or name using getElementById..
i have a "add button", when the user press this button, its generate a dropdown list(dynamic) which the value is get from mysql..
and its looks like this when the user press 3 times..
i want to create an array of this id, and store it to mysql..
this is my JS code :
var menu_paket_array = document.getElementById('menu_paket').value;
alert(menu_paket_array);
the problem is, when i try to create this array(menu_paket_array), the value in this array is just the first id (Test 1) only..
how can i fix this?
thanks...
Using the same id for more than one element is wrong. Id is to uniquely identify certain element. Using it for more elements defeats its -purpose. If you need that for i.e. CSS styling, then use class instead, which is designed just for such scenarios.
An ID must be unique on a page. You can only use it on one element.
Instead, use a CSS class or element type to iterate (here's a fiddle demonstrating this code):
function alertValues() {
var select, selects = document.getElementsByTagName('select');
var out = "";
for (var i = 0; i < selects.length; i++) {
select = selects[i];
if (select.className && select.className.match(/CLASSNAME_TO_INCLUDE/)) {
out += select.options[select.selectedIndex].value;
}
}
alert(out);
}
A better solution, of course, would be to utilize a dom library like jQuery or mootools, with which you could do something like this:
jQuery(function($) {
vals = [];
$('select.CLASSNAME').each(function() { vals.push($(this).val()); });
alert(vals.join(','));
});
document.getElementsByClassName(names);
Where names is the classname u generate for each one.
Instead of assigning each element with id='menu_paket' (for the reasons #WebnetMobile.com explained) assign class='menu_paket'.
Instead of var menu_paket_array=document.getElementById('menu_paket').value;, do
var temp_array = document.getElementsByClassName('menu_paket');
var menu_paket_array = [];
for(i in temp_array){
menu_paket_array[] = temp_array[i].value;
}
From within php, I have a large html <form> filled out with lots rows of patient info from a postgres database. When a doctor double-clicks on a row, it sets a var in $_POST and invokes another php script to read up and display specific info about that row from the database. This all works.
But there are now so many rows of patient data that the doctors don't want to scroll and scroll to find the patient rows they're looking for, they want a patient prefilter <form> so that a click on an element in it will result in the large display filtered to just that patient's rows.
What's a basic approach to doing this? I'm a newb; I'm currently using html, php, and some javascript.
Make a second form with whatever options you'd like to filter on, this part will be specific to your data but you want something like
<form id="search-form">
<label>Name:</label><input type="text" name="patient-name"></input>
</form>
You'll need to build a query string (and make sure you use GET, because that will make things easier for you). This will require tweaking if you want to use radio buttons, or something similar, but here's the general idea:
function getSearchParameters () {
var form = document.getElementById('search-form');
var inputs = form.getElementsByTagName('input');
var result = '';
var i;
for (i = 0; i < inputs.length; i++) {
if (inputs[i].value) {
result += "&" + inputs[i].name + "=" + inputs[i].value;
}
}
return result;
}
In the onClick handler for your patient data links, you'll call this function and append its result to your query string:
element.onclick = function () {
var patientDataUrl = '/patients.php?param1=someValue';
patientDataUrl += getQueryParameters();
/* then do your ajax stuff as normal */
};
Then on the server side, within patients.php simply check for the presence of the search fields i.e.
if(isset($_GET['patient-name'])) {
$patient_name = mysql_real_escape_string($_GET['patient-name']);
$query = "SELECT * FROM `patients` WHERE `patient_name`='$patient_name';";
} else {
$query = "SELECT * FROM `patients`;";
}
(make sure you sanitize the string!)
I'd recommend considering a JS framework to make your life much easier (for instance, jQuery would allow you to send this via POST or easily serialize it into a GET query string via .serialize())