Dynamically changing dropdown to textfield opencart - javascript

I am trying to change a drop down so that a user can add a custom input instead.
I am using VQMod and have currently set up a PHP array as follows:
<td><select name="electricColours">
<?php foreach (array("", "White", "Black", "Add Custom Colour..." ) as $eColours) { ?>
<?php if ($electricColours == $eColours) { ?>
<option value="<?php echo $eColours;?>" selected="selected"><?php echo $electricColours; ?></option>
<?php } else { ?>
<option value="<?php echo $eColours;?>"><?php echo $eColours; ?></option>
<?php }?>
<?php } ?>
<td class="left"><a onclick="AddCustomColour();" class="button"><?php echo "Add Custom Colours"; ?></a></td>
</select>
How would I be able to add new values to the eColours using the "Add Custom Colour..." so that the user inputs something and that colour is added on to the array.
I thought using Javascript so that it shows up as an alert and the user gets to choose their option would work however it keeps saying the variable is not defined.
<SCRIPT TYPE="text/javascript">
function AddCustomColour()
{
var colour=prompt("Please add custom colour","Silver");
var arrays = <?php echo json_encode($electricColours); ?>;
if (colour!=null)
{
electricColours.push(colour);
}
}
</SCRIPT>
Thanks

Use the DOM API:
var option = document.createElement("option");
option.setAttribute("value", value);
option.appendChild(document.createTextNode(value));
document.getElementById("the_select_element").appendChild(option);
Instead of:
document.getElementById("the_select_element")
You could do something like:
document.forms.the_form.electricColours

replace this code
<SCRIPT TYPE="text/javascript">
function AddCustomColour()
{
var colour=prompt("Please add custom colour","Silver");
var arrays = <?php echo json_encode($electricColours); ?>;
if (colour!=null)
{
electricColours.push(colour);
}
}
</SCRIPT>
With this Code
<script type="text/javascript">
function AddCustomColour()
{
var colour=prompt("Please add custom colour","Silver");
var ob = $("#electricColours");
if (colour!=null)
{
ob.prepend("<option value="+ val +">" + text + "</option>");
}
}
</script>

Related

how create if for option in select?

How can I create if for option in select? The code works, it is necessary to code only worked for option = 5
<select id="select<?php echo $product['id_product'];?>" name="status_id" class="form-control" onchange="changeFunction(<?php echo $product['id_product'];?>)">
<?php foreach ($statuses as $status) { ?>
<option id="option<?php echo $product['id_product'];?>" value="<?php echo $status['id_product_status'];?>"
<?php if ($status['id_product_status'] == $product['id_product_status']) { ?> selected="selected"<?php } ?>>
<?php echo $status['name_product_status']; ?>
</option>
<?php } ?>
<textarea id="onchange<?php echo $product['id_product'];?>" style="visibility: hidden" "></textarea>
</select>
function changeFunction(item) {
if ($("#option" + item).val == 5) {
var selectOption = document.querySelector("#onchange" + item);
selectOption.setAttribute('style', 'visibility: visible');
}
}
Do like this, though you don't need to pass "item" as parameter to achieve this. When you select an option, a change event is triggered on select. So you can bind a change event for this particular requirement. Upto you.
function changeFunction(item){
if($("#select"+item).val() == 5) {
var selectOption = $("select option:selected");
selectOption.setAttribute('style', 'visibility: visible');
}
}
you can use this code :
function changeFunction(item){
if($(this).val() == 5) {
$(this).css('visibility': 'visible');
}
}

How to get a value of an attribute inside a loop using jQuery

I have this code from my HTML form.
<?php foreach ($charges as $c): ?>
<br><input type="checkbox" id="charge<?php echo $c->id; ?>" cash="<?php echo $c->amount; ?>"> <?php echo $c->description; ?>
<?php } ?>
when I tick a textbox I want the value for that element pops up.
So far, only the value for the first occurrence pops up.
This is the jQuery code. I know I'm missing something, but i dont know
function triggerChange1(){
$("#ch1").trigger("change");
}
$("#charge1").change(function() {
var v = $(this).attr('cash');
alert(v);
});
if($("#charge1").prop('checked')){
triggerChange1();
}
Firstly you should use a class attribute to group elements together. You should also use data-* attributes to assign any custom meta data to an element as creating your own non-standard attributes will render the page invalid and lead to potential UI and JS issues:
<?php foreach ($charges as $c): ?>
<br><input type="checkbox" class="charge" id="charge<?php echo $c->id; ?>" data-cash="<?php echo $c->amount; ?>"> <?php echo $c->description; ?>
<?php } ?>
Then you can have a single click handler to get the value from the element which raised the event:
$('.charge').change(function() {
var v = $(this).data('cash');
alert(v);
});
// raise the event on checked elements on load:
$('.charge:checked').change();
EDIT: As rightfully stated in Rory's answer you should prefix your custom attributes with data-
What you need is a class.
<?php foreach ($charges as $c): ?>
<br><input type="checkbox" class="charge" id="charge<?php echo $c->id; ?>" data-cash="<?php echo $c->amount; ?>"> <?php echo $c->description; ?>
<?php } ?>
$(".charge").change(function() {
var v = $(this).data('cash');
alert(v);
});
You can see it working here: http://jsfiddle.net/0cude9jr/
function triggerChange1(){
$("#ch1").trigger("change");
}
$(document).ready(function() {
$("#charge1").change(function() {
var v = $(this).attr('cash');
alert(v);
});
if($("#charge1").prop('checked')){
triggerChange1();
}
}
And you should use value attribute and not cash attribute.
And then you can call var v = $(this).val();

How to get the parent div id in javaScript?

I want to get the parent div id (the div class is called "col-sm-2") when selecting each option in HTML "select" tag in each div. But it always gives only the div id of latest added product at "id" alert. For example if the id of my last added product is "7", it always gives "7" as the alert.
Here is my PHP code for getting the product id.
$jsql_ae7 = mysql_query("select request_list.product_id from request_list where request_list.product_id='{$jrowa2['id']}' and request_list.email='$visit_email'") or die(mysql_error());
$jfeta7 = mysql_fetch_assoc($jsql_ae7);
Here is my HTML code.
<div class="col-sm-2" id="<?php echo $jfeta7['product_id']; ?>">
<select id="formats_id" name="aformats" onchange="showFormat(this);">
<option value="<?php echo $jrowa2['formats']; ?>"><?php echo $jrowa2['formats']; ?></option>
<?php foreach($formats3 as $v3){ ?>
<?php if($v3 !== $jrowa2['formats']) { ?>
<option value="<?php echo $v3; ?>"><?php echo $v3; ?></option>
<?php } ?>
<?php } ?>
</select>
</div>
Here is my javaScript code.
var showFormat = function(dd) {
var format_value = dd.options[dd.selectedIndex].value;
var scriptTags = document.getElementsByTagName('select');
var id = scriptTags[scriptTags.length - 1].parentNode.id;
alert(id);
};
Try to use each:
$('select').each(function() {
alert($(this).parent().attr('id'));
});
You coild get the id property of the immediate container div using closest() :
$('select').on('change',function() {
alert($(this).closest('div').prop('id'));
});
use this code
var showFormat = function(dd) {
var format_value = dd.options[dd.selectedIndex].value;
var scriptTags = document.getElementsByTagName('select');
var parent = scriptTags[scriptTags.length - 1].parentNode;
alert(parent.getAttribute('id'));
};
Try this:
Fiddle
$('#formats_id').change(function(){
alert($(this).parent().attr('id'));
});
First we will start with making the selection:
$('select').each(function() {
var selectField = $(this); // this will point to select element
});
There are two ways:
This will take direct parent of select
selectField.parent().attr('id');
This will select first ancestor that is a div with class 'my-class':
selectField.closest('div.my-class').attr('id');
Both work, but differ in deep of search:)

Small glitch but could be an important issue

I currently have an issue with my drop down menu using JavaScript/AJAX and PHP.
Here's the code for the edit.php file which is supposed to retrieve data from multiple selection boxes in a drop-down list:
<td ><input readonly type="text" id="mainlines" value='<?php echo $_SESSION["mainlines"];?>' name="mainlines"/> </td>
<td ><input readonly type="text" id="categories" value='<?php echo $_SESSION["categories"]; ?>' name="categories"/> </td>
<td>
<select name="subcategories" id="menu" onChange="SelectAccountHead_Code(this.value)">
<option value="<?php print $subcategories; ?>"><?php print $subcategories; ?></option>
<?php
$sql1a = "SELECT * FROM subcategory ORDER BY subcategories asc";
$smt1a = $dbs->prepare($sql1a);
$smt1a -> execute();
while($row1a=$smt1a->fetch(PDO::FETCH_ASSOC))
{
if($row1a['subcategories']==$_GET['id2'] )
echo ("<option selected value=$row1a[subcategories]>$row1a[subcategories]</option>");
else
echo ("<option value=$row1a[subcategories]>$row1a[subcategories]</option>");
}
?>
</select>
</td>
For the "mainlines" and "categories", I get the data showing output only when it is selected, but when the item is being edited it doesn't automatically print it out unless I use "print $mainlines" or "print $categories".
How do I insert the onChange event changer in the if/else statement?
I want it to state the following in pseudo-code:
if (onChange = "SelectAccountHead_Code(this.value)"){
print $mainlines;
} else {
echo $_SESSION["mainlines"];
}
How do I go about inserting the correct syntax in the if/else clause with regards to the JavaScript/AJAX event changer/handler?
Update:
Here's my JavaScript code - where am I missing the AJAX code?
function SelectAccountHead_Code(i)
{
var k=document.getElementById("menu").selectedIndex;
var l=document.getElementById("menu1").selectedIndex;
if((k>0)&&(l>0))
{
self.location="edit3.php?productsnames=<?php print $productsnames;?>&id="+document.getElementById("menu").options[k].value+"&id2="+document.getElementById("menu").options[k].innerHTML +"&id3="+document.getElementById("menu1").options[l].value+"&id3="+document.getElementById("menu1").options[l].innerHTML;
}
}
function SelectAccountHead_Codes(j)
{
var k=document.getElementById("menu").selectedIndex;
var l=document.getElementById("menu1").selectedIndex;
if((k>0)&&(l>0))
{
self.location="edit3.php?productsnames=<?php print $productsnames;?>&id="+document.getElementById("menu").options[k].value+"&id2="+document.getElementById("menu").options[k].innerHTML +"&id3="+document.getElementById("menu1").options[l].value+"&id3="+document.getElementById("menu1").options[l].innerHTML;
}
}
function SelectUp(i)
{
var k=document.getElementById("menuUp").selectedIndex;
var l=document.getElementById("menuUp").selectedIndex;
self.location="edit3.php?id="+document.getElementById("menuUp").options[k].value+"&id2="+document.getElementById("menu").options[k].innerHTML +"&id3="+document.getElementById("menu1").options[l].value+"&id3="+document.getElementById("menu1").options[l].innerHTML;
}
function SelectUp(j)
{
var k=document.getElementById("menuUp").selectedIndex;
var l=document.getElementById("menuUp").selectedIndex;
self.location="edit3.php?id="+document.getElementById("menuUp").options[k].value+"&id2="+document.getElementById("menu").options[k].innerHTML +"&id3="+document.getElementById("menu1").options[l].value+"&id3="+document.getElementById("menu1").options[l].innerHTML;
}
You cant combine Javascript and PHP without further requests (Ajax) and server interaction.
Other big mistake:
echo ("<option selected value=$row1a[subcategories]>$row1a[subca.........
you have constants in your associative arrays.
See this example why this is wrong:
$array = array('test' => 111);
define('test', 999);
echo $array[test];
proper:
echo ("<option selected value='" . $row1a['subcategories'] . "'>" . $row1a['su..
// consider adding htmlspecialchars() or addslashes() to your output
More minor mistakes / bad practice:
onChange should be all small letters: onchange
if .. else block should have { }

Pass and update php variable into javascript

Is there a way I can pass the php option value variable $option_value['price'] into javascript as a string, then each time a different option is chosen, the javascript 'updates' the string with the new value. I have tried with onchange() but must be doing something wrong. I am sure my mistake is because php is server side and javascript is client side, but I have no idea how to get the two to act how I want.
<?php if ($options) { ?>
<?php foreach ($options as $option) { ?>
<?php if ($option['type'] == 'select') { ?>
<span id="option-<?php echo $option['product_option_id']; ?>" class="option">
<select name="option[<?php echo $option['product_option_id']; ?>]" onchange="getIt(this)">
<?php foreach ($option['option_value'] as $option_value) { ?>
<option value="<?php echo $option_value['product_option_value_id']; ?>"><?php echo $option_value['name']; ?>
<?php if ($option_value['price']) { ?>
<?php $option_value['price']; ?>
<?php } ?>
</option>
<?php } ?>
</select>
</span>
I have tried:
<script type="text/javascript">
function getIt(elm) {
var val = elm.options[elm.selectedIndex].text;
window.alert(val);
}
</script>
and
<script type="text/javascript">
function getIt() {
var val = "<?php $option_value['price']; ?>";
window.alert(val);
}
</script>
Here is an example how you can do it. What you have to do are:
Analyze the code (notice that I use jquery from google's account. You will need to at some point install jquery on your web site and use this one instead of the google's one.
Build your fruits array so it looks like the one in the example.
I have prepared page that will show you this working here: http://jsfiddle.net/7uudp/
Below is what it contains. Notice that this example does not use your variables. You will need to use them the way you want/need. I have also defined entry_fruit to show you how to chose the default one to be selected. Hope it will help.
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
fruits = [{n:"apple",p:1},{"n":"strawbery",p:3}];
entry_fruit="strawbery";
function build_select(select,list,which)
{
$.each( list, function(i,v){
var selopt="" ;
if ( v.n == which ) selopt="selected" ;
$(select).append("<option "+selopt+" value="+i+">"+v.n+" - $"+v.p+"</option>");
}) ;
}
$(document).ready(function(){
build_select($("select[name=fruits]"),fruits,entry_fruit);
$("select[name=fruits]").change(function(){
alert("Price is $" + fruits[$(this).val()].p);
}) ;
})
</script>
</head>
<body>
<select name="fruits"></select>
</body>
</html>
<script type="text/javascript">
function getIt() {
var val = "<?php echo $option_value['price']; ?>";
window.alert(val);
}
</script>
Like so? Looks to me like you just forgot the "echo".
EDIT-
<script type="text/javascript">
var val = "<?php echo $option_value['price']; ?>";
function getIt(elm) {
val = elm.options[elm.selectedIndex].text;
window.alert(val);
}
</script>
Okay, Revoking my previous entry.
What you need to do is to add selected keyword to your <option> element when you match your option_value['price']
Now yuou need to arrange your data in a little bit different way.
In your javascript, prepare an array that will map $option_value['product_option_value_id'] to $option_value['price'];. When you build your <select>, for each $option_value['product_option_value_id'] check if its price matches the one that came in initially from php.
Your getIt will simply take the <option value="___"> value, find it in that map, and show it to the user using the alert() window.

Categories