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>');
}
Related
I have the $value and $field generated dynamically from php $value = 'mango'; $field='user_username'. I now need to check if the text entered in input id user_username is mango or not.
<input type="text" class="input-text um-field " name="user_username" id="user_username" placeholder="">
Something like:
<?php
$value = 'mango';
$field = 'user_username';
<script>
$(document).ready ( function(){
var value = $("#<?php echo $field;?>").val();
if(value === '<?php echo $value;?>') {
alert('hi');
}
});
</script>
?>
A better approach would be to load your desired field into some js variable and then compare.
here is how it works roughly
$(document).ready(function(){
$("button").click(function(){
$.get("demo_test.php", function(data, status){
var server_data=data;
});
});
});
then compare it with desired field
$(document).ready ( function(){
var value = $("#<?php echo $field;?>").val();
if(value === server_data) {
alert('hi');
}
});
hope it helps
You could check the value on blur, because $(document).ready() is called at the beginning of the script. Also you have to close the PHP tag before to write JavaScript:
<?php
$value = 'mango';
$field = 'user_username';
?>
<input type="text" class="input-text um-field " name="user_username" id="user_username" placeholder="">
<script>
$(document).ready(function(){
$("#<?php echo $field;?>").bind('blur', function(){
var value = this.value;
if(value === '<?php echo $value;?>') {
alert('hi');
}
});
});
</script>
As per my comment, your script only compares the input field's value at runtime against a PHP variable. JavaScript does not automagically performs the comparison whenever the user updates the input field—you will have to bind an event handler to your input element, so that when triggered will re-invoke the logic to perform the check:
$(document).ready (function(){
var $field = $("#<?php echo $field;?>");
var expectedFieldValue = '<?php echo $value;?>';
$field.on('change', function() {
if ($(this).val() === expectedFieldValue) {
alert('hi');
}
});
});
Sometimes, it might be just a bit heavy-handed to use jQuery if you're performing a simple logic like this. The above code can also be rewritten in native JS that works in modern, evergreen browsers:
document.addEventListener('DOMContentLoaded', function () {
var fieldElement = document.getElementById('<?php echo $field;?>');
var expectedFieldValue = '<?php echo $value;?>';
fieldElement.addEventListener('change', function () {
if (fieldElement.value === expectedFieldValue) {
alert('hi');
}
});
});
I have a problem putting Onchange() on a ajax returned html on my form.
Basically I have clients listed in a select.
<select name="company" id="company">
<?php
$sqlget1 = "SELECT * FROM clients WHERE 1=1 ORDER BY company ASC;";
$resget1 = mysql_query($sqlget1);
while($row1 = mysql_fetch_array($resget1)) {
?>
<option value="<?php echo $row1['id']; ?>"><?php echo $row1['company']; ?></option>
<?php
}
?>
</select>
And when some one selects a client, im using Ajax to fetch projects that are assigned to that client.
$('#company').change(function() {
var selectedProject = $("#company option:selected").val();
$.ajax({
type: "POST",
url: "get_projects.php",
data: { projects : selectedProject }
}).done(function(data){
$("#response").html(data);
});
});
It gets returned back to
<div id="response"></div>
The code for get_projects.php is
<?php
include('inc.php');
if(isset($_POST["projects"])) {
$projects = $_POST["projects"];
$sqlget2 = "SELECT * FROM projects WHERE cid=\"$projects\" ORDER BY pname ASC;";
$resget2 = mysql_query($sqlget2);
echo '<select name="project" id="project" class="select2 form-control">';
echo '<option value="">-- Select a project --</option>';
while($row2 = mysql_fetch_array($resget2)) {
?>
<option value="<?php echo $row2['id']; ?>" pstatus="<?php echo $row2['pstatus']; ?>" ptype="<?php echo $row2['ptype']; ?>"><?php echo $row2['pname']; ?></option>
<?php
}
echo '</select>';
}
?>
Now when i use on change function on the returned html from ajax it is not working.
I tried to see the source code and found out that it is not there atall. It only shows the <div id="response"></div>
But i can see the result on the form but cant see the source in the source code.
Hence i thought that's why the Onchange() is not working for <select name="project" id="project" class="select2 form-control"> because it is not showing.
I see, the data which is return from Ajax is object
You should parse it to get the raw content an set into DIV
When you are dynamically adding mark up to the page the javascript doesn't know about the controls you have added through php.
Try finding the newly added control like this:
var select = document.getElementById('project');
Then you should be able to fire your on change method
Not tested, but it should work
<?php
include('inc.php');
if(isset($_POST["projects"]))
{
$projects = $_POST["projects"];
$varOut = "";
$sqlget2 = "SELECT * FROM projects WHERE cid=\"$projects\" ORDER BY pname ASC;";
$resget2 = mysql_query($sqlget2);
$varOut .= '<select name="project" id="project" class="select2 form-control">';
$varOut.= '<option value="">-- Select a project --</option>';
while($row2 = mysql_fetch_array($resget2))
{
$varOut.= "<option value=" . $row2['id'] . " pstatus=". $row2['pstatus']. ">ptype=".$row2['ptype']."><".$row2['pname']."></option>";
}
$varOut.= '</select>';
}
echo $varOut;
?>
I've finally solved the issue.
Basicall i just pasted the Onclick() script for '#projects' inside the get_projects.php file.
So now every time when it comes from ajax it also brings the javascript as well.
When you use ajax, you add a piece of html later to the DOM (browsers view), because you use .change the onchange is only added to the '#company' elements wich already exist in the browser.
You need to bind the onchange after you appended the html. for example:
$('#company').change(function() {
onCompanyChange()
});
function onCompanyChange(){
var selectedProject = $("#company option:selected").val();
$.ajax({
type: "POST",
url: "get_projects.php",
data: { projects : selectedProject }
}).done(function(data){
$("#response").html(data);
$('#company').change(function() {
onCompanyChange()
});
});
}
OR
You can also use an on change, on change does work with elements added later to to the dom. so this code works with elements wich already exists and new added elements with for example ajax
$("#company").on("change",function(){
console.log("change");
});
Try below code. Hope this works fine.
$(document).ready(function() {
$(document).on('change', '#company', function() {
var selectedProject = $("#company option:selected").val();
$.ajax({
type: "POST",
url: "get_projects.php",
data: { projects : selectedProject }
}).done(function(data){
$("#response").html(data);
});
});
});
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>
I'm new to this so I have a question regarding dependent drop down menu.
I have two drop down menu first, Leave Type and the second Available Balance.
Below shows the js and form.
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#parent_cat").change(function() {
$(this).after('<div id="loader"><img src="img/loading.gif" alt="loading subcategory" /></div>');
$.get('loadsubcat.php?parent_cat=' + $(this).val(), function(data) {
$("#sub_cat").html(data);
$('#loader').slideUp(200, function() {
$(this).remove();
});
});
});
});
$sql = mysql_query("SELECT * FROM leaves WHERE emp_id=$emp_id'");
<form method="get">
<label for="category">Leave Type</label>
<select name="parent_cat" id="parent_cat">
<option> Select one </option>
<?php
if ($row['leave_al'] == 1)
{
echo "<option value='Annual Leave'> Annual Leave </option>";
}
if ($row['leave_matl'] == 1)
{
echo "<option value='Maternity Leave'> Maternity Leave </option>";
}
?>
</select>
<label>Available Balance</label>
<select name="sub_cat" id="sub_cat"></select>
</form>
loadsubcat.php
<?php
$parent_cat = $_GET['parent_cat'];
$emp_id = $_GET['emp_id'];
$query = mysql_query("SELECT * FROM leaves WHERE emp_id = 'OR9090'");
$row = mysql_fetch_array($query);
if ($parent_cat == 'Annual Leave')
{
echo "<option value='$row[id]'>$row[total_annual]</option>";
}
if ($parent_cat == 'Maternity Leave')
{
echo "<option value='$row[id]'>$row[maternity_days]</option>";
}
?>
Example above, parent_cat is been passed to loadsubcat in order to load the available balance. I would also like to pass $emp_id to loadsubcat so that the sql can read based on $emp_id. Right now, I can only assign the emp_id manually. Please help me thanks!
and you can try this:
<form method="get">
<input type="hidden" name="emp" value="<?php echo $emp_id ?>"/>
<label for="category">Leave Type</label>
<select name="parent_cat" id="parent_cat">
Put the emp_id on hidden input and then get the value on jquery change
$("#parent_cat").change(function() {
var emp = $(this).siblings('input[name=emp]').val(); (...)
and then complete with Drake said.
$.get('loadsubcat.php?parent_cat=' + $(this).val() + '&emp_id=' + emp, function(data) {
Oh, and be careful with the GET vars from the loadsubcat.php
use mysql_real_escape_string or PDO to protect SQL injections.
I would also like to pass $emp_id to loadsubcat
To add another parameter to the loadsubcat.php query string, you can change
$.get('loadsubcat.php?parent_cat=' + $(this).val(), function(data) {
to
$.get('loadsubcat.php?parent_cat=' + $(this).val() + '&emp_id=' + $("...").val(), function(data) {
where $("...").val() is the location of the employee ID value in some HTML tag, then in your PHP file you can access them with your code below:
$parent_cat = $_GET['parent_cat'];
$emp_id = $_GET['emp_id'];
my code is now working! I've changed the
var emp = $(this).siblings('input[name=emp]').val();
to
var $form = jQuery(this).closest('form');
var emp = $form.find("input[name='emp']").val();
The rest of code given above is working perfectly fine!
I have a form on my page which includes 2 dependent drop down lists. When user selects value from 1st list, it populates the second list and user then selects value from 2nd list.
I want to submit form data to php page to insert into table in mysql, but when it submits, all data is passed EXCEPT value from 2nd list. Value from 1st list and other input fields are passed OK.
I've tried everything I know and I can't make this work. Any ideas how to implement this?
This is the form from index2.php (EDIT: simplified the form element):
<form name="part_add" method="post" action="../includes/insertpart.php" id="part_add">
<label for="parts">Choose part</label>
<select name="part_cat" id="part_cat">
<?php while($row = mysqli_fetch_array($query_parts)):?>
<option value="<?php echo $row['part_id'];?>">
<?php echo $row['part_name'];?>
</option>
<?php endwhile;?>
</select>
<br/>
<label>P/N</label>
<select name="pn_cat" id="pn_cat"></select>
<br/>
<input type="text" id="manufactured" name="manufactured" value="" placeholder="Manufactured" />
<input id="submit_data" type="submit" name="submit_data" value="Submit" />
</form>
And this is javascript:
$(document).ready(function() {
$("#part_cat").change(function() {
$(this).after('<div id="loader"><img src="img/loading.gif" alt="loading part number" /></div>');
$.get('../includes/loadpn.php?part_cat=' + $(this).val(), function(data) {
$("#pn_cat").html(data);
$('#loader').slideUp(200, function() {
$(this).remove();
});
});
});
});
And this is php to load 2nd list:
<?php
include('db_connect.php');
// connects to db
$con=mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$part_cat = $_GET['part_cat'];
$query = mysqli_query($con, "SELECT * FROM pn WHERE pn_categoryID = {$part_cat}");
while($row = mysqli_fetch_array($query)) {
echo "<option value='$row[part_id]'>$row[pn_name]</option>";
}
?>
I am getting $part_cat from 1st list to insertpart.php, but $pn_cat.
EDIT: this is insertpart.php (simplified and it just echos resuls)
<?php
//Start session
session_start();
//Include database connection details
require_once('../includes/db_details.php');
//DB connect
$con=mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
// find part name based on ID
$part_typeID = mysqli_real_escape_string($con, $_POST['part_cat']);
$part_name_result = mysqli_query($con, "SELECT part_name FROM parts WHERE part_id = $part_typeID");
$part_row = mysqli_fetch_array($part_name_result, MYSQL_NUM);
$part_type = $part_row[0];
echo"part_type='$part_type'";
//find pn value based on id
$pn_typeID = mysqli_real_escape_string($con, $_GET['pn_cat']);
$pn_name_result = mysqli_query($con, "SELECT pn_name FROM pn WHERE pn_id = $pn_typeID");
$pn_row = mysqli_fetch_array($pn_name_result, MYSQL_NUM);
$pn = $pn_row[0];
echo"pn='$pn'";
mysqli_close($con);
?>
It's still work in progress, so the code is ugly, and I know I'm mixing POST and GET that is being rectified. If I echo $pn_cat on this page there is no output, $part_type is OK.
Can you try swapping the $_GET in
$pn_typeID = mysqli_real_escape_string($con, $_GET['pn_cat']);
with $_POST?
$pn_typeID = mysqli_real_escape_string($con, $_POST['pn_cat']);
EDIT: based on asker's feedback and idea for a work-around
NOTE: This edit is based on what you suggested, even though I tested your original code and received satisfactory results (after I removed the PHP and MySQL from the code and replaced them with suitable alternatives).
The Work-Around
Here's the HTML for the hidden field:
<input type="hidden" id="test" name="test" value="" placeholder="test" />
Here's a simple Javascript function:
function setHiddenTextFieldValue(initiator, target){
$(initiator).change(function() {
$(target).val($(this).val());
});
}
You can call the above function within the function(data) { of your original code with something like:
setHiddenTextFieldValue('#pn_cat', '#test'); // note the hashes (#)
I also recommend you to hard-code the following HTML into your HTML and PHP files, right before the looping of the <option>s begin:
<option value="" disabled selected="selected">Select</option>
The above line could improve user experience, depending on how you want your code to work. Note however, that this is entirely optional.
Solved it! It was just a stupid typo, can't believe I've lost 2 days over this!
In loadpn.php instead of:
$row[part_id]
it should read:
$row[pn_id]
For some reason drop down worked, but offcourse value of pn_cat wasn't being set.
Also this works in setting 2 field values (which now I don't need but if somebody wants to know):
$(document).ready(function() {
$("#part_cat").change(function() {
$('#pn_hidden').val($(this).val());
});
$("#pn_cat").change(function() {
$('#pn_hidden2').val($(this).val());
});
});
Also changed js to post:
$(document).ready(function() {
$("#part_cat").change(function() {
$.post('../includes/loadpn.php', 'part_cat=' + $(this).val(), function(data) {
$("#pn_cat").html(data);
});
});
});
And thanks for the:
<option value="" disabled selected="selected">Select</option>
It really helps with user experience.