On click suggestions don't replace the good value in text box - javascript

Basically, I have a search box that suggests results from a database as user types. It looks like this :
Example
.
I use ajax in a file to make a live search as user types :
<input name="estab" id="estab" type="text" class="estab" />
<div id="result"></div>
<script>
$("#estab").on("input", function(){
$estab = $("#estab").val();
if ($estab.length > 0){
$('#result').show();
$.get("res.php", {"estab":$estab},function($data){
$("#result").html($data);
})
}
});
<script>
Then in another file (res.php) I have a sql request and I display results. I also have my 'onclick' function to replace suggestion in text box :
while($result=$data->fetch_assoc()){
$sortie[] = $result['school'];
}
$sortie2=array_unique($sortie);
echo '<ul>';
foreach($sortie2 as $value){
echo "<script>
function fill(){
document.getElementById('estab').value = '$value';
$('#result').hide();
}
</script>";
echo "<li onclick='fill()'><b>$value</b></li>";
}
echo '</ul>';
My problem is : when i click on any of the suggestion, it is always the last option that is replaced in the text box, in this case "University of Washington".
I have been trying to solve that problem for 2 days now and I can't find the solution.
Any help would be greatly appreciated. Thanks
UPDATE
Found the solution, if someone is interested, here's what I did in res.php:
while($result=$data->fetch_assoc()){
?>
<li onclick='fill("<?php echo $result['school']; ?>")'><?php echo $result['school'];?></li>
<?php
}
?>
</ul>
and in the first file :
<script>
function fill(val){
$('#estab').val(val);
$('#result').hide();
}
$("#estab").on("input", function(){
$estab = $("#estab").val();
if ($estab.length > 0){
$('#result').show();
$.get("res.php", {"estab":$estab},function($data){
$("#result").html($data);
})
}
});
</script>

echo "<script>
function fill(newValue){
document.getElementById('estab').value = '" + newValue + "'" + ;
" $('#result').hide();
}
</script>";
echo '<ul>';
foreach($sortie2 as $value){
echo "<li onclick='fill($value)'><b>$value</b></li>";
}
echo '</ul>';

I wouldn't use the onclick method here. I would use jQuery to assign the events to your list items. But if you must, in your onclick method, try passing this.value like so:
<li onclick="fill(this.value)"><b>$value</b></li>
Then your fill() method could be something like so:
function fill(val){
$('#estab').val(val);
$('#result').hide();
}
EDIT: You are mixing plain JavaScript and jQuery code. I replaced your plain JS line with the jQuery equivalent.
Also, if you are adding the fill() method in the same loop that adds the LIs, then you are adding multiple fill methods, which is incorrect. Just add it once in the same script tag like below.
<script>
function fill(val){
$('#estab').val(val);
$('#result').hide();
}
$("#estab").on("input", function(){
$estab = $("#estab").val();
if ($estab.length > 0){
$('#result').show();
$.get("res.php", {"estab":$estab},function($data){
$("#result").html($data);
})
}
});
<script>

Related

button of javascript is displaying but function is not working

I am trying to call a function in javascript by clicking a button but the problem is that when I used to click the button then it do nothing i.e it doesn't call the function...
The following is the code
<?php
function view_cat1()
{
$i=1;
include("inc/db.php");
$fetch_data=$con->prepare("select * from main_cat order by cat_name");
$fetch_data->setFetchMode(PDO::FETCH_ASSOC);
$fetch_data->execute();
while($row=$fetch_data->fetch())
{
echo"<tr><td>".$i++."</td>
<td>".$row['cat_id']."</td>
<td>".$row['cat_name']."</td>
<td><a href='index.php?edit_cat=".$row['cat_id']."'>Edit</td>
<td><input type='button' onclick='delete_category(<?php echo
".$row['cat_id'].")' name='delete' value='Delete'></td>
</tr> ";
}
}
?>
<script language="javascript'">;
function delete_category(delname)
{
if(confirm("are you sure"))
{
window.location.href='delete_cat.php?del_name='+delname+'';
return true;
}
</script>
<?php
The above code don't use to show the confirmation message .
Modify the JavaScript as below, it may works:
<script>
function delete_category(delname)
{
if(confirm("are you sure"))
{
window.location.href='delete_cat.php?del_name='+delname+'';
return true;
}
}
</script>
The language attribute has been deprecated for a long time, and should not be used. Also, you missed the closing brace } of the delete_category function.
<script>
function delete_category(delname) {
if (confirm("are you sure")) {
window.location.href = 'delete_cat.php?del_name=' + delname + '';
return true;
}
}
</script>
You can use the attribute type="text/javascript" if you are not using HTML5
To simplify your code and make fewer mistakes, you could use a single echo statement in your while loop. If you render HTML with JavaScript functions linked with events, don't forget to add quotation marks around the arguments of the function. In your case, the function delete_category takes in as argument $row['cat_id']. To do that escape the double quotes with a blackslash : \"
Here is an example:
<?php
$var = "hello";
echo "<input type='button' onclick='delete_category(\"".$var."\")' name='delete' value='Delete'>";

A href load database items onClick

i'm developing a simple Content Management System that allow users to create categories and subcategories. This is the code.
$categories = mysql_query("SELECT * FROM categories");
while($row = mysql_fetch_array($categories)) {
$text = $row['text'];
$id = $row['id'];
echo "<li><a href='?category=$id'>$text</a></li>";
}
Now, all works fine as expected but i would like that when a user click on <li> items the system loads subcategories related to the selected category. In PHP i can't do this so i need to use JavaScript but i don't understand why. I wrote this code.
<script type="text/javascript">
function loadSubCategories() {
<?php
if(isset($_REQUEST['category'])) {
echo "Hello";
}
?>
}
</script>
and obviously
echo "<li><a href='?category=$id' onClick='javascript:loadSubCategories()'>$text</a></li>";
This not works because nothing appear when i click on a link. How can i solve?
Pass id attribute in function call like this:
echo "<li><a id="$id" onClick='javascript:loadSubCategories(this.id)'>$text</a></li>";
Then you can use jQuery/Ajax, try something like this:
$( document ).ready(function() {
function loadSubCategories(id){
$.ajax({
url : Class/Method-Name,
type : 'POST',
data : form_data,
success : function(msg){
// Action
}
}),
}
});

how to get next element by java script

I would like to get next element:
<script>
function editMediaInfo(mediaID){
var x = document.getElementById(mediaID);
alert(x.nextElementSibling.id);
}
</script>
<?php
$x = 1;
echo "<ol>";
while($x <= 5)
{
echo "<li id={$x}> item {$x} </li>";
$x++;
?>
<button onclick="editMediaInfo('<?php echo $x; ?>')">Click</button>
<?php
}
echo "</ol>";
?>
When i click it gives me an alert without nothing. I would like to get the id of the next element.
It appears you are using an incorrect Javascript function. Use nextSibling function. Replace nextElementSibling with nextSibling. I provided a sample below.
<script>
function editMediaInfo(mediaID){
var x = document.getElementById(mediaID);
alert(x.nextSibling.id);
}
</script>
Where I found and tried the solution was here. I would recommend using this site for help on Javascript in the future.
Simply Use :
document.getElementById(mediaID).nextElementSibling.nextElementSibling.id

how to load all options in selector without select

When I'm adding an options for a new product, there is a selector that must be used to select the options I need. But all the available options are required and must be visible without use of a selector.
How can I add to form each option by option_id, without using a selector?
HTML.file
<div class="ms-options">
<p class="error" id="error_options"></p>
<div class="options"></div>
<div>
<select name="options[0]" class="select_option">
<option value="0" disabled="disabled" selected="selected"><?php echo $ms_options_add; ?></option>
<?php foreach($options as $option) { ?>
<option value="<?php echo $option['option_id']?>"><?php echo $option['name']; ?></option>
<?php } ?>
</select>
</div>
</div>
JS.file
// add
$('body').delegate(".select_option", "change", function() {
$(this).children(':selected').attr('disabled', 'disabled');
var option_id = $(this).children(':selected').val();
var select = this;
$.get($('base').attr('href') + 'index.php?route=seller/account-product/jxRenderOptionValues&option_id=' + option_id, function(data) {
var lastRow = $(select).parents('.ms-options').find('.option:last input:last').attr('name');
if (typeof lastRow == "undefined") {
var newRowNum = 1;
} else {
var newRowNum = parseInt(lastRow.match(/[0-9]+/g).shift()) + 1;
}
var data = $(data);
data.find('input,select').attr('name', function(i,name) {
if (name) return name.replace('product_option[0]','product_option[' + newRowNum + ']');
});
$('div.options').append(data);
});
$(this).val(0);
});
pls hlp
my attempt
html.file
<div class="ms-options">
<p class="error" id="error_options"></p>
<div>
<?php foreach($options as $option) { ?>
<div id="<?php echo $option['option_id']?>"></div>
<?php echo addoption($option['option_id'])?>
<?php } ?>
</div>
</div>
js.file
$(function() {
function addoption(optionid) {
var option_id = optionid;
$.get($('base').attr('href') + 'index.php?route=seller/account-product/jxRenderOptionValues&option_id=' + option_id, function(data) {
$('div'."optionid").append(data);
});
});
});
but i've got this message
Fatal error: Call to undefined function addoption() in /home/moidomki/public_html/catalog/view/theme/default/template/multiseller/account-product-form-options.tpl on line 9
looks like it's can't see my function?
You are calling delegate. See your first parameter? It is ".select_option". This is where you specify the selector of the tag where you want to define the options. From here on you do not need to specify it again. Inside the function passed to delegate as a parameter, you can use $(this) instead. It is actually better to use $(this) inside delegate if possible, because then jquery will not have to search for it from the DOM.
See this example:
$( "table" ).delegate( "td", "click", function() {
$( this ).toggleClass( "chosen" );
});
Taken from here.
EDIT:
Hereby I am giving some notes about the experiment taken by Yurii Litvinenko:
let me start with nailing down that it is a very pleasant thing to see that people are actually trying to learn on their own. Off course, the experiment is flawed, but do not forget that the best way to learn it is to actually do it
the actual problem you are being pointed to is that you are trying to call a javascript function using php. It is important to understand that your php code is called server-side, or backend and your javascript code is called client-side, or frontend. Your php is running on the server and your javascript is running on the user's computer, therefore, you cannot call a client-side function on server-side
I do not see your select tag in your new experiment
You are successfully filling your initial option set on the server if I am not mistaken
If you intend to add options to your select already sent to your client-side, then you need to do it with javascript, like that:
function addOption(id, name) {
$(".select_option").html(select_option.html() + '<option value="' + id + '">' + name + '</option>');
}

Why wont javascript get values of php generated html?

im using ajax to query my mysql to my database.
But im stock at issue with my php generated html form input - javascript/jquery will simply not pick up the value. From normal html is no issue of course.
php (works fine, all echos are good)
<?php
function getAge() {
$age = "<select name='age'>";
$result = $mysqli->query("select * from ages");
while ($row = $result->fetch_row()) {
$age.="<option value=" . $row[0] . ">". $row[1] ."</option>";
}
$age.="</select>";
return $age;
}
?>
html
<form id="myform">
<input name='name' value='Nick'>
<input name='sport' value='Football'>
<?php echo getAge(); ?>
<input type='submit'>
</form>
javascript
$("form#myform").on('submit', function(e){
e.preventDefault();
var json = {}
$.each(this.elements, function(){
json[this.name] = this.value || '';
});
}
Everything works well except it wont get the value of the <select>. If i make a normal html select it works.. ?!
Also anybody know how to delete the submit button from the json object? :-)
Any dynamically generated HTML will not have the events applied to them, as those events are applied on page load. So if you apply the events to the document, you will be able to pull values from dynamically generated html. Like so:
var json = {};
$(document).on('submit', 'form#myform', function(e){
$('*', this).each(function(){
json[$(this).attr('name')] = $(this).val();
});
});
Hope this helps!
change this line:
$age.="<option value=" . $row[0] . ">". $row[1] ."</option>";
to this:
$age.="<option value='" . $row[0] . "'>". $row[1] ."</option>";
//----------------^---------------^------put quotes
And i think you can make use of .serializeArray() which does the same you want but in a different way like multiple objects with multiple [{ name : value}] pairs:
$(function(){ //<-----put this block too
$("form#myform").on('submit', function(e){
e.preventDefault();
var json = $(this).serializeArray();
}); //<----checkout the closing
}); //<---doc ready closed.

Categories

Resources