Jquery dynamic image change from selection - javascript

Trying to create a nice dynamic selection process. There are two parts to the selection process: Choose category, then choose name. The form process works just fine. I then want to display an image based on the name chosen. I can't seem to figure it out, here's the code:
<form action="file.php" method="post">
<select id="first-choice" name="cardset">
<?php foreach ($data as $row): ?>
<option><?=$row["name"]?></option>
<?php endforeach ?>
</select>
<select id="second-choice" name="card">
<option>Please choose from above</option>
</select>
<img src="" name="image-swap">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script language=JavaScript >
$(document).ready(function() {
$("#first-choice").change(function() {
$.get("getter.php", { choice: $(this).val() }, function(data) {
$("#second-choice").html(data);
});
});
});
$(document).ready(function() {
$("#card").change(function() {
var first = $("first-choice");
var sec = $(this).val();
$("#image-swap").html(src ? "<img src='/pics/" + first + sec + "'>" : "");
});
});
</script>
I am trying to pull the image from pics/"first"/"sec".jpg

Hard to tell without seeing the HTML, but . . .
var first = $("first-choice");
. . . is missing the .val() at the end. If you change it to this, it should get you much closer to what you are looking for:
var first = $("first-choice").val();
At the moment, you are trying to append the jQuery reference to the HTML option to a string value (sec).
UPDATE
Was looking a little further and found some other issues . . .
1) You are using an HTML img element, but you've given it a name attribute value of "image-swap":
<img src="" name="image-swap">
. . . and are trying to reference it with a jQuery "id" selector:
$("#image-swap")
In order for that selector to work, you must change the name attribute to and id attribute, like this:
<img src="" id="image-swap">
2) You appear to be attempting to update the src attribute of the img tag, but you don't have that quite right in your code:
$("#image-swap").html(src ? "<img src='/pics/" + first + sec + "'>" : "");
There are a couple of issues here:
src does not exist as a variable, but you appear to be checking for its existence as one
you want to update the src attribute of the img, but you are using the .html() method, which sets/gets the HTML content of a tag, not its attributes
To do what you appear to be wanting to do, you probably need to use this code:
$("#image-swap").attr("src", (first !== "" && + sec !== "") ? "pics/" + first + "/" + sec + ".jpg" : "");
That will update the src attribute with the image location, if neither of the selections has an empty value, or with "", if one of them does.

I figured out $("first-choice").val() and Try this,
$(document).ready(function(){
$("#first-choice").change(function() {
$.get("getter.php", { choice: $(this).val() }, function(data) {
$("#second-choice").html(data);
});
});
$("#card").change(function() {
var first = $("first-choice").val();
var sec = $(this).val();
$("#image-swap").html(src ? "<img src='/pics/" + first + sec + "'>" : "");
});
});

Two things:
You only need 1 document ready wrap:
$(document).ready(function(){
$("#first-choice").change(function() {
$.get("getter.php", { choice: $(this).val() }, function(data) {
$("#second-choice").html(data);
});
});
$("#card").change(function() {
var first = $("first-choice");
var sec = $(this).val();
$("#image-swap").html(src ? "<img src='/pics/" + first + sec + "'>" : "");
});
});
The second, non of your options have values, which is why it isn't passing.
<select id="first-choice" name="cardset">
<?php foreach ($data as $row): ?>
<option value="<?=$row["name"]?>"><?=$row["name"]?></option>
<?php endforeach ?>
</select>
Given if the is correct. I've never used = is php to echo, normally I would do <?php echo $row["name"]; ?>.

Related

JQuery and the editableSelect package is not allowing me to Filter a select menu with a RegExp. JavaScript and jQuery nub or novice

Here is a select list built using PHP, MariaDB, and HTML:
echo "<select name='companylist' id='companylist' size='86' value='' tabindex='1' >";
echo "<option value=''></option>";
echo "<option value='0-Create a New Company'>0-Create a New Company</option>";
foreach ($companyResult as $company) {
echo "<option id='".$company['Company_Key']."'
value='".$company['Company_Key']."'>".$company['Company_Names']."</option>";
}
echo "</select>";
It builds a dropdown list that is appropriate for my application.
Next, I built this testing script to find out if I was on the right track in the use of RegExp to filter the dropdown select list dynamically, and it works well, for its purpose. I only built it because the list following it is giving me fits.
echo "<script>";
echo "$('#companylist option').each(function() {
var Val = this.text;
var Filter='W';
var CompRegex = new RegExp('^'+Filter);
if(CompRegex.test(Val)){
console.log('RegExp with Filter has found the following Val starting with this
Filter: '+Filter);
console.log('Val = ' + Val);
}
})";
echo "</script>";
This above gives me the following console output:
RegExp with Filter has found the following Val starting with this Filter: W
Val = Welch Tile
RegExp with Filter has found the following Val starting with this Filter: W
Val = West Michigan Molding
RegExp with Filter has found the following Val starting with this Filter: W
Val = WL Molding of MI
This is a good start.
echo "<script>";
echo " $('#companylist')";
echo " .editableSelect()";
echo " .on('select.editable-select', function (e, li) {
console.log('value = ' + document.getElementById('companylist').value);
console.log('li.val() = '+li.val());
getCustomer_Names(li.val());
getTool_Numbers(li.val());
getPart_Name(li.val());
newCompany_Name();
})";
echo "</script>";
This above script loads other menus, as expected, once the user selects an item.
The next script here simply will not let me get the option text that the user sees in the list. I have 5 days into this, because I am new to JQuery and not a master of Javascript either, but I do read all kinds of sites for help, including reference guides, and the support boards (thank you for this one!), but I would like a happy ending soon. Any help, as stated, would be very appreciated.
echo "<script>";
echo " $('#companylist')";
echo " .editableSelect()";
echo " .on('input.editable-select', function () {
$(this).each(function() {
var Val = this.text;
var Filter = this.value;
var CompRegExp = new RegExp('^'+Filter);
console.log('Val = '+Val);
console.log('Filter = '+Filter);
console.log('CompRegExp = '+CompRegExp);
if(CompRegExp.test(Val)){
console.log('RegExp with Filter has found the following Val starting with this
Filter: '+Filter);
console.log('Val = ' + Val);
}
else {
// remove from select list
}
});
});";
echo "</script>";
This above script gives me
Val = undefined
Filter = a
CompRegExp = /^a/
It is the "Val = undefined" that is my undoing.
I also took a long-view of this problem and wrote a jQuery/JavaScript program that clears the dropdown list and then recreates the options by having a PHP program re-query the database to get the values that match a SQL LIKE 'Input%' which I will include to show you the depth of effort here. The problem here is that I could not get the dropdown menu to stay open even though I issued .editableSelect('show'); as instructed in the editableSelect git website to open the dropdown menu and show the modified list, although, if I clicked in the field and moved the cursor around, it would pop the menu open with the values that matched the return from MariaDB. It follows:
echo "<script>
function getCompany_Names(comp_val)
{
if(document.getElementById('companylist').value.substring(0,8) != '0-Create'){
$('#companylist').editableSelect('clear');
var xhttp;
if (comp_val === null || comp_val === '' ) {
$('#companylist').editableSelect('add', '<option value=></option>');
$('#companylist').editableSelect('add', '<option value=0-Create a New Company>0-Create a
New Company</option>');
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var select = $('#companylist');
var c_text = this.responseText;
console.log('comp_ctext = ' + c_text);
c_text = JSON.parse(c_text);
$.each($(c_text),function(key,value){
if (value.compname == 'One or more Company Names are Probably Not Entered.')
{
$('#companylist').editableSelect('add','<option value=' + 'One or more Company
Names are Probably Not Entered.' + '>One or more Company Names are Probably Not
Entered.</option>');
}
else
{
console.log('<option id=\'' + value.compkey + '\' value=\'' + value.compkey + '\'>'
+ value.compname + '</option>');
$('#companylist').editableSelect('add','<option id=\'' + value.compkey + '\'
value=\'' + value.compkey + '\'>' + value.compname + '</option>');
}
}); // end .editableSelect('add',...)
}
};
xhttp.open('GET', 'getCompany_Names.php?q='+comp_val, true);
xhttp.send();
}
}
</script>";
This is all because my patron does not like the default filter behavior of the editableSelect package where it matches what is typed to any values anywhere in the dropdown and wants some dropdowns to come up matching the input to the results from first character onward with something like (exactly like) a regex of /^input_variable/.
Thank you for your time.
R
its not a solution, just easier to ask something..i'll delete more later
i dont understand this syntax: no selector before .on??
.on('input.editable-select', function () {
$(this).each(function() {
i see $(this) that means you have more input?
the problem with these lines:
var Val = this.text;
var Filter = this.value;
what is Val? because this.text is not functional for input? (its the reason Val => undefined)
this.value gives what you type in input
This is WAY more complicated than my core problem actually is. I have posted another question that is just my actual failure. It is at: [https://stackoverflow.com/questions/66801231/the-use-of-https-github-com-indrimuska-jquery-editable-select-for-editable-sel]
I think I have an example of an example page the creator put together and it has a function their I am only just starting to understand, but it is all about adding values to the list. I will study it and post my results on the core issue page. Thank you to all who tried to help. Here's one for brevity.

Trying to set up mailto: link

I have a webpage that has a form to insert vendor data, once inserted the company name is the placed into a select box. when the company is selected a table is called with all the vendor information.
My problem is the
the vendor_email is called from a php script, is there a way to make the value of the id insert into a mailto: function.
<tbody id="records">
<td id="vendor_company"></td>
<td id="vendor_rep"></td>
<td id="vendor_email"></td>
</tbody>
<div class="row" id="no_records"><div class="col-sm-4">Plese select vendor name to view details</div></div>
here is my php and js code
<?php
include_once("Database/db_connect.php");
if($_REQUEST['empid']) {
$sql = "SELECT id, companyName, repName, venderEmail FROM vender_contact
WHERE id='".$_REQUEST['empid']."'";
$resultset = mysqli_query($conn, $sql) or die("database error:".
mysqli_error($conn));
$data = array();
while( $rows = mysqli_fetch_assoc($resultset) ) {
$data = $rows;
}
echo json_encode($data);
} else {
echo 0;
}
?>
my js code
$(document).ready(function(){
// code to get all records from table via select box
$("#vendors_data").change(function() {
var id = $(this).find(":selected").val();
var dataString = 'empid='+ id;
$.ajax({
url:"getVendor.php",
dataType: "json",
data: dataString,
cache: false,
success: function(vendorData) {
if(vendorData) {
$("#heading").show();
$("#no_records").hide();
$("#vendor_company").text(vendorData.companyName);
$("#vendor_rep").text(vendorData.repName);
$("#vendor_email").text(vendorData.venderEmail);
$("#records").show();
} else {
$("#heading").hide();
$("#records").hide();
$("#no_records").show();
}
}
});
})
});
It's absolutely possible! You simply need to use .html() instead of .text().
Note that the mailto comes on the href attribute, which is unique to the <a> tag. As such, you'll want to place your inside of your <td id="vendor_email"></td>:
$("#vendor_email").html("<a href='mailto:" + vendorData.vendorEmail + "'>" + vendorData.vendorEmail + "</a>");
Which will render as something like:
vendorData = {};
vendorData.vendorEmail = 'test#test.com';
$("#vendor_email").html("<a href='mailto:" + vendorData.vendorEmail + "'>" + vendorData.vendorEmail + "</a>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="vendor_email"></div>
In addition to this, please be aware that your MySQLi is vulnerable to SQL injection. You should use prepared statements, and also ensure that your database user only has the required privileges in order to prevent this.
You can refer to this post for further information on how to prevent SQL injection in PHP :)
Hope this helps!
By using jQuery's .html() method you can insert html like so:
$( '#vendor_email' ).html( '' + vendorData.vendorEmail + '' );
By the way, I couldn't help but notice that you've spelled vendor as "vender" in venderEmail.

PHP - Onchange reload page with value of select

I am working on PHP. I have three dynamic dropdown boxes. On the basis of first selected value I change the content of second select box and same case for the third. I have achieved this functionality through javascript. The problem I am having is my code works perfectly on localhost but when I upload the code on the online server the page keeps on reloading. Let me first share my code so that you can have an idea of what I am talking about
javascript
<script>
var valnew = <?php echo $cat3; ?> ;
function reload() {
var val = form.cat.options[form.cat.options.selectedIndex].value;
var text = form.cat.options[form.cat.options.selectedIndex].text;
self.location = 'douglas-college.php?cat=' + val + '&text=' + text
}
function reload3(form) {
var val = form.cat.options[form.cat.options.selectedIndex].value;
val2 = form.subcat.options[form.subcat.options.selectedIndex].value;
self.location = 'douglas-college.php?cat=' + val + '&cat3=' + val2;
}
function reload4(form) {
var val3 = form.subcat3.options[form.subcat3.options.selectedIndex].value;
var text = form.subcat3.options[form.subcat3.options.selectedIndex].text;
self.location = 'course-title.php?inst_id=' + val3 + '&coursecode=' + valnew;
}
</script>
<?php
$query1 = mysql_query("SELECT * FROM course");
echo "<select name='cat' class='input-large form-control' onchange=\"reload(this.form)\">";
if (!isset($_GET['cat'])) {
echo '<option>Select one</option>';
while ($row = mysql_fetch_array($query1)) {
echo '<option value="' . $row['courseID'] . '">' . $row['courseName'] . '</option>';
}
} else {
while ($row = mysql_fetch_array($query1)) {
echo '<option value="' . $row['courseID'] . '">' . $row['courseName'] . '</option>';
}
}
echo "</select>";
?>
I have added only one selectbox php code right now. I can share the whole code upon request. I have checked the page by using only one dropdown but still page keeps on refreshing. Means the page is keep on reloading again and again
The real problem is that in :
http://smithdeveloper.com/test/js/sitefunction.js
$('select').change(function() {
$('option').css('background', 'white');
$('option:selected').css('background', '#ff87c3');
}).change();
U trigger .change() on all select elements.
So thats why onchange events are called immediately after page load.
So every time page loads u call change event and listen to change event and fire reload() function
first ditch the inline onchange="" events inside select tags..
Than remove your script from begining of the file and save this in file that you include in the end of the page, sitefunction.js inside document.ready hook.
Here is mine jsfiddle and I changed your functions a bit..
$('[name=cat]').on('change', function(){
var val1 = form.cat.options[form.cat.options.selectedIndex].value;
var txt1 = form.cat.options[form.cat.options.selectedIndex].text;
self.location = 'http://smithdeveloper.com/test/douglas-college.php?cat=' + val1 + '&text=' + txt1
});
$('[name=subcat]').on('change', function(form) {
var val2 = form.cat.options[form.cat.options.selectedIndex].value;
var txt3= form.subcat.options[form.subcat.options.selectedIndex].value;
self.location = 'http://smithdeveloper.com/test/douglas-college.php?cat=' + val2 + '&cat3=' + txt3;
});
$('[name=subcat3]').on('change', function(form) {
var val3 = form.subcat3.options[form.subcat3.options.selectedIndex].value;
var text = form.subcat3.options[form.subcat3.options.selectedIndex].text;
self.location = 'course-title.php?inst_id=' + val3 + '&coursecode=' + valnew;
});
http://jsfiddle.net/mkdizajn/wLz2g3sw/
hth, cheers, k

javascript call inside php where loop not working and breaks query

I am attempting to call a javascript function inside a php where loop. I've succeeded in calling the variable, however the function only works on the first line, and then breaks a subsequent query.
The javascript is a simple show/hide of a div or span tag with a specific id. I'm trying to have this appear for every instance of a variable, but only open the span associated with that entry, so I used a php variable from the query.
The javascript code is contained in the header; it works fine without the php, and the php works fine without the javascript but I can't seem to make them work together.
Here's the code:
while($row = mysqli_fetch_array($qir)) {
$ingredient_id = $row['ingredient_id'];
echo '<input type="checkbox" value="' . $ingredient_id . '" name="markdelete[]">';
echo $row['amt'] . ' ' .$row['ingredient_name']; ?> <button onclick="showHide('<?php echo $row['ingredient_id']; ?>'); return false">Edit amount</button> <br />
<span id="<?php echo $row['ingredient_id']; ?>" class="hide">
<?php include_once('amt.php');
echo '</span> ';
// }
echo '<br />';
}
echo '<input type ="submit" name="remove" value="Remove">';
First of all, the showHide is only working on the first record
It is also making this query not respond at all.
if (isset($_POST['remove'])) {
iF (!empty($_POST['markdelete'])) {
foreach ($_POST['markdelete'] as $delete_id) {
// remove specific source from source_subject
$rem_ing = "DELETE from dish_ingredient
where ingredient_id = $delete_id
and dish_id = $dish_id ";
mysqli_query($dbc, $rem_ing)
or die ('Error removing ingredient: '.mysqli_error($dbc));
}
}
}
I tried removing the return false;, to no avail. Please let me know if I need to show more of the code (e.g. the javascript itself)
Edit:
I've tried working within the php string (this is actually what I had tried first) but it seems to break everything (no javascript, no php)
echo $row['amt'] . ' ' .$row['ingredient_name'] . '<button onclick="showHide(\''. $row['ingredient_id'] .'\') return false">Edit amount</button> <br />';
echo '<span id=" '. $row['ingredient_id'] .' " class="hide">';
include_once('amt.php');
echo '</span> ';
Edit: I am open to other solutions if this is not something that is possible. I'm feeling a bit stumped. Realistically I just want to have a list of items called from a mysql database, and have a field appear onclick to edit an associated variable if desired without having to send it to another page or reload the script for usability (hence the javascript piece).
Thanks again, anyone who can assist.
Note: this is the script that I am calling:
<script language="JavaScript" type="text/JavaScript">
menu_status = new Array();
function showHide(theid){
if (document.getElementById) {
var switch_id = document.getElementById(theid);
if(menu_status[theid] != 'show') {
switch_id.className = 'show';
menu_status[theid] = 'show';
}else{
switch_id.className = 'hide';
menu_status[theid] = 'hide';
}
}
}
</script>
You don't need tag there as you are already in php block.Try it without and use
showHide(\''.$row['ingredient_id'].'\')
and change
<?php include_once(....);
to
include_once(........);
Hopefully that would work
===========
try this for you javascript
<script language="JavaScript" type="text/JavaScript">
function showHide(theid){
if (document.getElementById) {
var switch_id = document.getElementById(theid);
if(!switch_id) {
switch_id.className = (switch_id.className.indexOf("show") > -1) ? "hide" : "show"
}
}
}
Okay after a long time on this, I finally figured out what was going on. Part of the issue was that I was trying to call a form inside a form, which I had forgotten is not permitted in HTML, so this required some redesign.
Other issues involved calling loops within inside loops, which caused problems where the first record would work, but not for the remaining records.
The javascript above did not need to be modified, only the way that it was called.
Here is what worked. The main key was using include() instead of include_once().
while($r = $qir->fetch_assoc()) {
$ingredient_id = $r['ingredient_id'];
$amt = $r['amt'];
$ingredient_name = $r['ingredient_name'];
echo $r['amt'] . ' ' .$r['ingredient_name'];
if ($row['user_id'] == $user_id) {
echo ' <span class="openlink"><button onclick="showHide(\''.$ingredient_id. '\')">edit amount</button></span><br/>';
echo '<div id="'.$ingredient_id.'" class="hide">';
include('amt1.php');
echo '</div>';
}
}

Can we put php in jquery code?

I want to use php script in jquery code. Here I put php script in my jquery but my jquery function is not working then. Is it right way to put php script in a jquery function.
<script type="text/javascript">
$(function() {
var count2=1;
$('a#addTelefono').click(function() {
count2 +=1;
$('<p><div style="float:left;width: 100%;"><select name="product_id[]" ><?php $sql=mysql_query("SELECT * FROM tbl_product"); while($res=mysql_fetch_array($sql)){ echo "<option value='".$res['id']."'>".$res['product_name']."</option>";}?></select><input type="text" name="discount[]" placeholder="discount ' + count2 + '" style="margin-left: 8px;" id="discount_' + count2 + '" />%<img src="images/cross.png"></div></p>').fadeIn("slow").appendTo('#extendTelefono');
i++;
return false;
});
//fadeout selected item and remove
$('.remove').live('click', function() {
$(this).parent().fadeOut(300, function(){
$(this).remove();
return false;
});
});
});
</script>
You have to make it in two steps and separate your php code from jQuery for readability :
$sql = mysql_query("SELECT * FROM tbl_product");
while($res=mysql_fetch_array($sql))
{
$contents .= "<option value='".$res['id']."'>".$res['product_name']."</option>";
}
$('<select name="product_id[]" ><?php echo($contents); ?></select> .....');
Also, be carreful of caracters you have in $res['product_name'] : It can fail if you have a quote in your product name (so you must escape it).
Moreover, mysql_* is deprecated, see mysqli_* or PDO.

Categories