I have a web form that contains a javascript / php autocomplete for an input field.
problem is that this input field sits inside a PHP loop which repeats 50 times. I use the loop to give each input a unique name and id.
The javascript is hardcoded to populate input field "inputString" and display possible suggestions in div "suggestions"
with the loop, I give each input box a unique name "inputstring1", "inputstring2", "inputstring3" etc etc.
I need to be able to populate the inputstring that is currently being worked on.
how can I pass the variable "inputstringX" to the javascript so it populates the correct input box?
same applies to the div "suggestion" so that it displays nex tto the correct input box?
javascript is:
<script type="text/javascript">
function lookup(inputString) {
if(inputString.length == 0) {
// Hide the suggestion box.
$('#suggestions').hide();
} else {
$.post("autocompleteperson.php", {queryString: ""+inputString+""}, function(data){
if(data.length >0) {
$('#suggestions').show();
$('#autoSuggestionsList').html(data);
}
});
}
} // lookup
function fill(thisValue) {
$('#inputString').val(thisValue);
setTimeout("$('#suggestions').hide();", 200);
}
</script>
and php/html is:
<table>
<?
for ( $i = 1; $i <=50; $i++ ) {
?>
<tr>
<td> Job <? echo $i; ?></td>
<td>
<SELECT NAME=job<? echo $i; ?> id=job<? echo $i; ?> style="width:150px;border: 1px solid #2608c3;color:red">
<OPTION VALUE=0 ></option>
<option>
<?=$optionjobs?>
</option>
</SELECT>
</td>
<td> Person </td>
<td>
<div>
<input type="text" size="30" value="" id="inputString<? echo $i; ?>" onkeyup="lookup(this.value);" onblur="fill();" />
</div>
<div class="suggestionsBox" id="suggestions<? echo $i; ?>" style="display: none;">
<img src="upArrow.png" style="position: relative; top: -12px; left: 30px;" alt="upArrow" />
<div class="suggestionList" id="autoSuggestionsList">
</div>
</div>
</td>
</tr>
<?
}
?>
</table>
Thanks for yourideas and for your time,
Don't use the onkeyup html attribute and use the jQuery functions to attach your function. So you can use this to retrieve your input.
$(function() {
var inputs = $('input[type="text"]'); // You may want to use a css class instead of that
inputs.keyup(function() {
// Here, this == the input. So you can't get the id by using $(this).attr('id').
});
});
Related
I have a dropdown populated with values I get from the database.
I need to perform some queries based on the selected option, but first I need to save the selected value on a new variable.
This is my dropdown:
<form name="dashboard_form" action="" id="dashboard_form" method="post">
<tr>
<td><?php _e('Select City')?>:</td>
<td>
<select class="selected_city" name="selected_city" style="margin: 20px;width:300px;" required>
<?php
foreach ( $all_cities as $city )
{
echo '<option value='.$city->ID.'>'.$city->name.'</option>';
}
?>
</select>
</td>
</tr>
</form>
*$all_cities is an array with all the cities.
My jQuery:
<script>
jQuery("#dashboard_form").validate({
ignore:'',
rules: {
'selected_city': {
required: true
}},
messages: {
'selected_city': "Please Select a City",
},
errorPlacement: function(error, element) {
jQuery(element).closest('tr').next().find('.error_label').html(error);
}
});
</script>
How can I save on a $new_variable my selected value from the dropdown?
EDIT 1:
I added the following to
$(document).ready(function () {
var selected_city;
$('.selected_city').change(function() {
selected_city = $(this).val();
alert(selected_city);
});
});
The alert(selected_city) prints the correct city, how can I use this selected_city on the PHP?
EDIT2:
The problem is the dropdown is not submitting anything, so I created a Button to force it to Submit:
<input type="submit" value="<?php _e('Send Now')?>" name="send_now_button" id="send_now_button" class="button button-primary">
Then:
if(isset($_POST['send_now_button'])){
if(isset($_POST['selected_city'])) { $selected_city = $_POST['selected_city']; } else {$selected_city = 'Lisboa'; } }
Now when I echo $selected_cities_id; it gives the correct value!
Your HTML is invalid. <tr> can't be the child of <form>, it has to be the child or <table>, <tbody>, <thead>, or <tfoot>. This could be preventing the <select> from being treated as part of the form, so nothing is being submitted.
You need to put the form around the entire table.
<form name="dashboard_form" action="" id="dashboard_form" method="post">
<table>
...
<tr>
<td><?php _e('Select City')?>:</td>
<td>
<select class="selected_city" name="selected_city" style="margin: 20px;width:300px;" required>
<?php
foreach ( $all_cities as $city )
{
echo '<option value='.$city->ID.'>'.$city->name.'</option>';
}
?>
</select>
</td>
</tr>
...
</table>
</form>
I want to get the values of a dynamic created table but I couldn't figure out what is wrong.
the table created in a php file or it creates in server side by calling it in jquery.
for making it clear : in my html page I run a jquery method to load this table.
then I need this table values to be able to edit them. but what I get instead of the element value is undefined. (when I alert the value)
this is the jquery code :
//<!-- ajax Post Request -->
$(function() {
$('#edit_test_show').hide();
$('#save_edit').hide();
var vop_id = localStorage.getItem('op_id');
$.post("Requests/OPS.php", //Required URL of the page on server
{ // Data Sending With Request To Server
read_OPS: true,
op_id: vop_id
},
function(response) { // Required Callback Function
if (response) {
$("#result_table").html(response);
}
});
//====================
$('#enable_edit').on('click', function() {
$('#edit_test_show').show();
$('#enable_edit').hide();
$('#save_edit').show();
});
$('#save_edit').on('click', function() {
$('#edit_test_show').hide();
$('#enable_edit').show();
$('#save_edit').hide();
var vop_id = localStorage.getItem('op_id');
var vop_title = $('#result_table').find('#op_title').val();
var vop_descrip = $('#result_table').find('#op_descrip').val();
alert(vop_title);
});
});
html part which the table loads in :
<form method='post' class="form-inline">
<div class="form-group">
<div id="result_table">
<!-- dynamic op load -->
</div>
</div>
</form>
<button type='button' id="enable_edit" class='btn btn-default'>edit</button>
<button type='button' id="save_edit" class='btn btn-default'>save</button>
and this is the php code which generate the table :
if($row=mysqli_fetch_assoc($read_op)) {
echo "
<table class='styled-table' cellspacing='0' width='360' border='1' >
<tr>
<td>
<label for='mail_num' style='margin-right:10px;color:#595959;float: right;'>شماره فرآیند : </label>
</td>
<td>
<input name='op_id' style='width:240px;height: 25px;margin:0 3px 0 3px;'
value='".$row['id']."'/>
</td>
</tr>
<tr>
<td>
<label for='op_title' style='margin-right:10px;color:#595959;float: right;'>عنوان فرآیند : </label>
</td>
<td>
<input name='op_title' style='width:240px;height: 25px;margin:0 3px 0 3px;'
value='".$row['op_title']."'/>
</td>
</tr>
<tr>
<td>
<label for='op_descrip' style='margin-right:10px;color:#595959;float: right;'>شرح فرآیند : </label>
</td>
<td>
<textarea name='op_descrip' class='textarea_2' rows='0' cols='0' >".$row['op_descrip']."</textarea>
</td>
</tr>
</table>
<div class='cleaner h20'></div>";
}
You are using ID Selector (“#id”) but not defined ID in HTMl thus you are not able to find element
Define the IDs as
<input id='op_id' value='".$row['id']."'/>
OR, Use Attribute Equals Selector [name=”value”]
Selects elements that have the specified attribute with a value exactly equal to a certain value.
var vop_title = $('#result_table').find('[name=op_title]').val();
var vop_descrip = $('#result_table').find('[name=op_descrip]').val();
In the following example i have a script with a loop that fetches comments from database, and gives every comment a form with a textarea and submit button so that users can interact with every comment separately.
The follow code makes the page looks a big mess and disturbing due to the repetition of the texareas.
What i need is a jQuery code that will hide the textareas and allow me to show a selected textarea individually when a link or div is clicked. I will simplify what i want in the following code.
<?php
$comments = array('comment1','comment2','comment3','comment4','comment5','comment6','comment7','comment8','comment9');
$c_count = count($comments);
for($i=0; $i<$c_count; $i++){
$comment = $comments[$i];
echo $comment;
?>
<hr />
<div style="border:1px solid #999; width:200px;">Click Here to Show Reply Form</div>
<div class="comment_box">
<form action="path/to/insert_reply.php" method="POST">
<textarea name="reply" cols="47" rows="4"></textarea>
<input type="submit" name="submit" value="Post Reply">
</form>
</div>
<?php
}
?>
This can be done quite easily with JQuery. http://api.jquery.com/ will be helpful.
In this example, the client can click on the comment_header div to view or hide the comment box. Note I added an additional identifier to the divs. There are many different ways to select individual div elements - you might consider wrapping both the comment_header and comment_box divs under a container div with a unique id attribute. Here, I choose to use the .data() JQuery capability.
PHP:
<?php
$comments = array('comment1','comment2','comment3','comment4','comment5','comment6','comment7','comment8','comment9');
$c_count = count($comments);
for($i=0; $i<$c_count; $i++){
$comment = $comments[$i];
echo $comment;
?>
<hr />
<div data-index="<?= $i; ?>" style="border:1px solid #999; width:200px;">Click Here to Show Reply Form</div>
<div id="<?= $i; ?>" class="comment_box">
<form action="path/to/insert_reply.php" method="POST">
<textarea name="reply" cols="47" rows="4"></textarea>
<input type="submit" name="submit" value="Post Reply">
</form>
</div>
<?php
}
?>
JS/JQuery:
$(document).ready(function(e) {
$('.comment_box').hide();
$('.comment_header').on('click', function(e) {
$('#' + $(this).data('index')).toggle();
});
});
Hope this is helpful. Here is the JSFiddle: http://jsfiddle.net/EUQG2/
To hide unselected textarea when a particular textarea is focused
$(document).ready(function(){
$('textarea').focus(function(){
$('textarea').not(this).hide();
});
});
You can play around this. I hope it helps
At its simplest, assuming that all you want to do is to hide the textarea elements (in this case by hiding the parent .comment_box element), and to show them by clicking the preceding div element:
$('.comment_box').hide().prev('div').on('click', function(){
$(this).next('.comment_box').toggle();
});
JS Fiddle demo.
If you want only one .content_box/textarea visible at any given point:
$('.comment_box').hide().prev('div').on('click', function(){
var target = $(this).next('.comment_box');
$('.comment_box').not(target).hide();
target.toggle();
});
JS Fiddle demo.
References:
hide().
next().
not().
on().
prev().
toggle().
I have a table there is showing some values. In each row there is a Order_ID and a button.
How can i get my value in $Order_ID to show (alert) when clicking on a button?
<tbody>
<?php
foreach($menuextra_result as $transaction)
{
?>
<tr>
$order_id = isset($transaction['order_id'])?($transaction['order_id']) :"";
?>
<?php if($order_id){ ?>
<td><div id="orderID"><?= $order_id ?></a></td>
<?php } else {?>
<td><div ><span style="color:red">MANGLER</span></td>
<?php }?>
style="color:red">MISSING</span></td>
<?php }?>
//There's more here, but did not bother to show it, because it was irrelevant.
<td><input type="submit" onclick="getElementById" value="Yes "></td>
<?php }
?>
</tr>
<?php
}
?>
</tbody>
This is how i tried
<script type="text/javascript">
function getElementById()
{
el = document.getElementById('order_id');
alert(el);
}
</script>
But when clicking on a button, nothing happens
table.php
//assuming you have done you loop work
<table>
<tr>
<td>
<?php echo $row['name']?>
</td>
<td><input type="button" value="click me" onclick="clickMe(<?php echo $row['id']?>)" /></td>
</tr>
</table>
clickme unction is like this
function clickMe(id) {
alert(id);
}
You will pass one parameter to clickMe() function and the parameter is id
First of all, don't use id as you have more than one such element. You can use class instead:
<div class="orderID"><?= $order_id ?></div>
Also fixed invalid HTML you got, closing tag for <div> is </div> and not </a>.
Second, change the click to send the button to the function:
<input type="submit" onclick="FindOrder(this);" value="Yes " />
And finally this function should do the trick: (by searching for "brother" div)
function FindOrder(oButton) {
var oRow = oButton.parentNode;
while (oRow && oRow.tagName.toLowerCase() !== "tr")
oRow = oRow.parentNode;
var arrDivs = oRow.getElementsByTagName("div");
var orderDiv = null;
for (var i = 0; i < arrDivs.length; i++) {
if (arrDivs[i].className === "orderID") {
orderDiv = arrDivs[i];
break;
}
}
if (orderDiv != null) {
var orderNumber = orderDiv.innerHTML;
alert("order is " + orderNumber);
} else {
alert("order not found");
}
}
Live test case.
You'll need to print the $order_id to your HTML somewhere. You could use hidden input:
<input name="order_id" id="order_id" value="<?php echo $order_id; ?>">
Then you can submit form or grab the value.
You can't getElementById from you web page if it does not exist.
So solution is simple, just add an hidden input element on your table. You can get the id from your script.
<tbody>
<?php
foreach($menuextra_result as $transaction)
{
?>
<tr>
<?php
$order_id = isset($transaction['order_id'])?($transaction['order_id']) :"";
?>
//There's more here, but did not bother to show it, because it was irrelevant.
<td>
<input type="hidden" name="order_id" id="order_id" value="<?php echo $order_id;?>">
<input type="submit" onclick="getElementById" value="Yes "></td>
<?php }
?>
</tr>
<?php
}
?>
</tbody>
I have no idea how to basically use this. Im thinking of using javascipt arrays though.
Well I have a select option here with values from the database and the select is dynamic. The "add row" button will add another row of option select:
<td>Items </td>
<td style="text-align:left;">
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
<TABLE id="dataTable" width="350px" >
<TR>
<TD><INPUT type="checkbox" name="chk[]"/></TD>
<TD>
<select name="ItemNo[]" id="select" value="ItemNo" onChange="this.disabled=true;">
<?php
$sql2="select * from jewelry_system.item where NumStored !='0' order by ItemName asc";
$result2 = mysql_query($sql2);
while($row2=mysql_fetch_array($result2)){
?>
<option value="<?php echo $row2['ItemNo']?>">
<?php echo $row2['ItemName'];?>
Php:<?php echo $row2['SalePrice'];?> </option>
<?php } ?>
</select>
</TD>
</TR>
</TABLE>
</td>
</tr>
Here is what should be changed by ajax?
<tr>
<td>Total Payment (Php):</td>
<td> <div id="tpayment">0.00</div> </td>
</tr>
I wanted to compute total payment onChange of the values in the select option. and since the value can only be changed once should i use arrays? I'm quite clueless to ajax, tried learning at w3schools but failed.
pls thanks
You might not need AJAX unless you are needing to set something in your database prior to clicking a "submit" button of some sort. It looks like you should be able to store all the information in your selects when you build your page with PHP. You would need to show/hide your selects in the document using javascript.
Add ;updateTotal() to your select onChange event:
<select name="ItemNo[]" id="select1" value="ItemNo" onChange="this.disabled=true;updateTotal()">
Then add this function to your page or your javascript file:
<head>
<script language="javascript" type="text/javascript">
function updateTotal() {
var dropdown = document.getElementById('select1');
var total = 0;
for (var i=0; i<dropdown.length; i++){
if (dropdown.options[i].selected) {
total += dropdown.options[i].value;
}
}
document.getElementById('tpayment').innerHTML = total;
}
</script>
</head>
Since you're going to be adding/removing rows, you will need to keep track of them like you mentioned with an array - probably a global one.
at the beginning of your javascript, declare a global array to store your datatables like this:
var selects = new Array();
You'll also want to update your add/remove calls:
<INPUT type="button" value="Add Row" onclick="addRow('dataTable','select1')" />
<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable','select1')" />
Then, when you call your addRow function, do this:
function addRow(rowname,selectname) {
/* ... original function stuff ... */
selects.push(selectname); /* this will add the selectname to the selects array */
}
And likewise, when you call your removeRow function, do this:
function removeRow(rowname,selectname) {
/* ... original function stuff ... */
selects.splice(selects.indexOf(selectname),1);
updateTotal(); /* since selected items might have been removed */
}
And lastly, we'll modify our original function like this:
function updateTotal() {
var total = 0;
for (var h=0; h<selects.length; h++) {
var dropdown = document.getElementById(selects[h]);
for (var i=0; i<dropdown.length; i++){
if (dropdown.options[i].selected) {
total += dropdown.options[i].value;
}
}
document.getElementById('tpayment').innerHTML = total;
}
}