How to populate the form fields based on drop down selection? - javascript

I have a form with input fields: name and description. The name field is a drop down. based on the name selected the description needs to change. I have made the drop down to populate the names already.
<form>
<select name="name" >
#foreach($books as $book)
<option value="{{$book->name}}">{{$book->name}}</option>
#endforeach
</select>
how do i change the description field based on the selected drop down?
<input type="text name="description" value="{{ $book->description }}>

Updated version:
You should store somewhere all $books as JavaScript variable. After that when you select name of the book, you can find book object (with description and other fields) and do whatever you want with them. You can achive by implementing these steps:
1) Make sure you have jQuery on your page
2) Add this JS code somewhere on the page (see comments)
<script type="text/javascript">
// 2.1 "Store" all books in some place on the page, for example, you can pass PHP variable into JS variable like this
var books = <?= json_encode($books); ?>;
/*
* 2.2 Create function for search book by its name
* (if each value of the field "name" in the $books is unique) or by some unique field, for example, "id"
*/
// get book by name
var getBookByName = function (bookName) {
if (typeof books === 'object') {
for (var key in books) {
if (typeof books[key].name !== 'undefined' && books[key].name === bookName) {
return books[key];
}
}
}
return false;
}
$(document).ready(function () {
// add event listener on the select with the attribute name="name"
$('select[name="name"]').on('change', function (e) {
// get book by selected name of the book
var selectedBook = getBookByname($(e.target).find('option:selected').text());
if (selectedBook) {
// set new value for the input with the attribute name="description"
$('input[name="description"]').val(selectedBook.description);
}
// we can't find book by it's name
else {
alert("Sorry, we can find description for this book");
}
});
});
</script>

Related

Move the check mark in MacOS dropdown

I made a drop down list using the <select> and <option> tag, where every time a new input is typed, the program creates a new option tag with value attribute to add it to the existing options in the drop down list.
However, my client uses a MacOS and he wanted to move the check mark on the drop down list to the recently added option. The check mark only moves when you click on the selected line, but in my case, I want it to also move to the recently added/typed data.
Here is the HTML code:
<!-- Created select tag so user can access history of talk -->
<div style="top:60px;position:absolute;z-index:2" id="speechBox">
<!-- The select tag acts like a drop down button, so it passes its value to the input box and not to itself -->
<select id = 'combo-box' title = "Saved Talk" onchange="document.getElementById('userText').value=this.options[this.selectedIndex].text; document.getElementById('idValue').value=this.options[this.selectedIndex].value;">
</select>
<span class = "dropdown" name = "Saved Talk"></span>
<input id ="userText" name="userText" type="text" onfocus="this.select()" ></input>
<input name="idValue" id="idValue" type="hidden">
<button id="speakText" class="toolbutton" title="Speak"></button>
<hr>
</div>
And the JS:
hiddenArray(); // Access speakArray
// Function containing the speakArray, which saves the recent talk array
function hiddenArray() {
speakArray = [];
}
function playVoice(language, text) {
playing = text;
//Adds option when text is spoken
var addUserInput = document.createElement("OPTION");
addUserInput.setAttribute("value", playing);
addUserInput.text = playing;
document.getElementById("combo-box").appendChild(addUserInput);
speakArray.push(playing); // Adds recent talks to speakArray
if(document.getElementById('mode').innerHTML=="2"){
//After the voice is loaded, playSound callback is called
getBotReply(text);
setTimeout(function(){
loadVoice(language, playSound);
}, 4000);
}
else{
loadVoice(language, playSound);
}
}
I've figured it out in the end. Here is the code:
hiddenArray(); // Access speakArray
// Function containing the speakArray, which saves the recent talk array
function hiddenArray() {
speakArray = [];
}
function playVoice(language, text) {
playing = text;
//Adds option when text is spoken
var addUserInput = document.createElement("OPTION");
addUserInput.setAttribute("value", playing);
addUserInput.text = playing;
document.getElementById("combo-box").appendChild(addUserInput);
document.getElementById("combo-box").value = playing;
speakArray.push(playing); // Adds recent talks to speakArray
if(document.getElementById('mode').innerHTML=="2"){
//After the voice is loaded, playSound callback is called
getBotReply(text);
setTimeout(function(){
loadVoice(language, playSound);
}, 4000);
}
else{
loadVoice(language, playSound);
}
}
So what I did here is asign the value of the combo box (select tag) to the recently added option (variable playing).

Magento - reloadPrice() modifications

My client needs to make an operation on products custom options.
Using Magento CE, I create a product, and give it some custom options from within the built-in left hand side menu in "Manage products" > "Add new product", such as "mm" (millimeters) and "mt" (meters)
This product will have both radio options and a textbot input.
Let's say we have
Base price: 0
MM:
Radio option A which costs 0,9
Radio option B which costs 1,2
Radio option C which costs 2,3
MT:
Textbox value = unknown yet
Let's say user chooses Radio option B and enters 10 in the textfield
Price should be updates as such:
1,2 * 10 + 0
Which is
radio value cost * textbox value + base price
Is there any way to tell the code to take the value of the radio button, multiply it for the value of the textbox and sum it all to the base price?
Where could I look to see the current behavior of a product's custom options?
EDIT
I saw that whenever a value is selected, the reloadPrice() function is called.
I thought to check if both inputs are radio and text, then get the value of the text and multiply it for the value of the radio.
Is that right? Can you point me better?
This helps me, I hope this will also helps you
initialize : function(config){
this.config = config;
this.reloadPrice();
document.observe("dom:loaded", this.reloadPrice.bind(this));
},
reloadPrice : function(){
price = new Number();
config = this.config;
skipIds = [];
skipIds = [];
relatedword = [];
relatedvalue = [];
relatedid = [];
counter_each=0;
counter=1;
first=0;
areaValue=1;
submitbutton=true;
$$('body .product-custom-option').each(function(element){
var optionId = 0;
element.name.sub(/[0-9]+/, function(match){
optionId = match[0];
});
if (this.config[optionId]) {
if (element.type == 'checkbox' || element.type == 'radio')
{
if (element.checked)
{
if (config[optionId][element.getValue()])
{
<?php if(Mage::getVersion() >= 1.7): ?>
price += parseFloat(config[optionId][element.getValue()].price);
<?php else: ?>
price += parseFloat(this.config[optionId][selectOption.value]);
<?php endif; ?>
}
}
}
}
reloadPrice() does not update product price at server level. One way to do this product price update is by implementing checkout_cart_product_add_after event.
Do you custom logic at client level with javascript in detail page. Assign this value to some hidden variable under the form product_addtocart_form. A better way is to save to session to reduce client side vulnerabilities or you can find your own better way. Or Implement your login only in Observer method. Whatever you find secure.
Rewrite the class Mage_Checkout_Model_Cart to modify as,
public function addProduct($productInfo, $requestInfo=null)
{
...
Mage::dispatchEvent('checkout_cart_product_add_after', array('quote_item' => $result, 'product' => $product,'request_data'=>$request));
...
}
In your yourmodule/etc/config.xml:
<config>
...
<frontend>
...
<events>
<checkout_cart_product_add_after>
<observers>
<unique_name>
<class>modulename/observer</class>
<method>customPrice</method>
</unique_name>
</observers>
</checkout_cart_product_add_after>
</events>
...
</frontend>
...
</config>
And then create an Observer class at yourmodule/Model/Observer.php
class <namespace>_<modulename>_Model_Observer
{
public function customPrice(Varien_Event_Observer $observer)
{
// Get the quote item
$item = $observer->getQuoteItem();
$request=$observer->getRequestData();
// Ensure we have the parent item, if it has one
$item = ( $item->getParentItem() ? $item->getParentItem() : $item );
// Load the custom price
$price = "custom price logic";//whatever from your hidden value or by some other mean.
// Set the custom price
$item->setCustomPrice($price);
$item->setOriginalCustomPrice($price);
// Enable super mode on the product.
$item->getProduct()->setIsSuperMode(true);
}
}
For more information check here

Cannot convert jquery object to type string and pass it to asp code behind

i am building a map of seats(seat booking system, as in online theater seat booking) and i want to get the selected seats. I can get the selected seats based on CSS class and store it in var but i cannot convert that object to string to be passed to code behind.Right now i get [object object] as a result when i pass through hidden field. How can i accomplish this?
this is jquery code
$(function () {
//When an available seat is clicked on
$('.seat.available').click(function () {
//Toggle selection for this seat
$(this).toggleClass('selected');
});
//When "Purchase" button is clicked
$("#Purchase").click(function () {
//Grab the selected seats
var selectedSeat = $(".seat.selected").toArray();
var selected = $(".seat.selected");
if (selected.length == 0) {
alert("No seats were selected.");
}
else {
alert(selected.length + ' seats were selected.');
}
$('#hdCountrID').val(selectedSeat);//giving value to hidden field
});
});
Now this is being passed to a hidden field from which i use following to extract data
var elem =hdCountrID.Value;
Label1.Text = "selected seat is" + elem;//used a label to display value
but this shows "selected seat is [object object].
What can i do to convert that object to string, cause i have to send it to database.
EDIT:Div tag is enclosed in a repeater & there is a PoCo class in the code behind that is bound as source to this repeater
selectedSeat is an array thus [object object]
you could set it to one item in the array
$('#hdCountrID').val(selectedSeat[0]);
or you could join them all into some form of string that you can split in the back.
like so
$('#hdCountrID').val(selectedSeat.join(","))
then:
var elem = hdCountrID.Value.Split(',');
you will then have an array in the code behind.
Untested but the theory should be sound.
EDIT: Sorry i think it is a little more complicated. You want to get the value of the checkbox items. dont you? Therefore you will need to make a string out of all the selected values first. I would look at using a each loop over $('.seat.selected') to get $(this).val() out into a comma separated string
EDIT:
This code works to set the hidden field with values in a comma separated string.
<script type="text/javascript">
$(function () {
//When an available seat is clicked on
$('.available').click(function () {
//Toggle selection for this seat
$(this).toggleClass('selected');
});
//When "Purchase" button is clicked
$("#Purchase").click(function () {
//Grab the selected seats
var selectedItemIdString = "";
$(".selected").each(function (index) {
selectedItemIdString += $(this).attr("data-id") + ",";
});
$('#hdCountrID').val(selectedItemIdString);
});
});
</script>
<input type="hidden" id="hdCountrID" name="hdCountrID" />
<div class="seat available" data-id="1">
Seat 1
</div>
<div class="seat available" data-id="2">
Seat 2
</div>
<div id="Purchase">Purchase</div>
Then in the code behind split the string like so
string[] SplitIds = hdCountrID.Value.Split(',', StringSplitOptions.RemoveEmptyEntries);
foreach(var sId in SplitIds)
{
// quick way to get it as in int. but not the safest int i = int.Parse(sId);
}

Data entered alters string length

I am new to JavaScript and I have been doing some work creating a form in HTML and JavaScript. In this work I have been trying to limit the string of a field depending on the text entered into a previous field.
What i have been trying is if the country 'Australia' is entered into the 'Country' text box than the 'Postcode' text box is limited to only 4 numbers (the Australian postcode standard)
i have done this much of a function so far:
document.getElementById('txtcountry').onblur = function postcode()
{
var country = document.getElementById('txtcountry').value;
if (country == "Australia" || category == "australia")
{
document.getElementById('txtpostcode').maxLength = 4;
}
else
{
document.getElementById('txtpostcode').maxLength = 9;
}
}
Here is the segment of the initial HTML that i have to use the function with:
<b>Postcode:</b> <input type="text" id="txtpostcode" name="postcode">
<br>
<b>Country:</b> <input type="text" id="txtcountry" name="country">
I am calling the function using :
<form name="rego" action="submit.htm" onsubmit="return !!(validateText() & validateCheckBoxes(this) & validateRadioButton() & validateEmail() & populateInstitution() & postcode());" method="POST">
Any help would really be appreciated!
UPDATE: i have updated my function to the finished function after some help as it doesn't seem to work and i need some further help with it
Are you trying to set the maxLength property:
var pc = document.getElementById('txtpostcode');
pc.maxLength = 4;
pc.value = pc.value.substr(0,4); // remove any extra characters already entered
...and then add an else condition to set the maxLength to whatever your default is for other countries.
You would then call your postcode() function from the blur event of your txtcountry field.
EDIT: Note that the function you've shown has an undefined variable category in the second part of the if test - should be country. And as I mentioned already you do need to call the function from somewhere.
I would use the
var country = document.getElementById('txtcountry');
if (country.value == "Australia" || category == "australia")
{
country.setAttribute("maxlength","4");
country.value = country.value.substr(0,4);
}

Removing child nodes on dynamic select

I'm creating a dynamic selection form. Basically the user picks an option from the select and then depending on what option they chose it goes into a data object and then generates a new selection based on their previous answer. After they answer 3 questions regarding their vehicle choice it prints out their vehicle choice.
The problem I'm running into is having the ability to change a previous option on the fly. I'd like to have them be able to change a previous selection and it would remove the later selection
Ex. The user first selects Car, Ford and a selection for model is displayed. If the user went back and changed Car to Truck. I would like to remove Ford and the model selection. Here is the part of the code I have that holds the data and creates the new selections dynamically
var data=new Object();// create a new data object to hold info
data['init']=['Car','Truck','SUV'];
data['Car']=['Audi','Dodge','Ford','Volkswagon'];
data['Audi']=['A4','TT','R8'];
data['Dodge']=['Charger','Challenger','Stealth'];
data['Ford']=['Focus','Fusion','Mustang'];
data['Volkswagon']=['Jetta','GTI','Beetle'];
data['Truck']=['Dodge Truck','Ford Truck','Toyota Truck'];
data['Dodge Truck'] = ['Ram-1500','Ram-2500','Ram-3500'];
data['Ford Truck'] = ['F-150','F-250','Ranger'];
data['Toyota Truck'] = ['Tundra','Tacoma'];
data['SUV']=['Dodge SUV','Ford SUV','Toyota SUV'];
data['Dodge SUV'] = ['Durango','Journey','Caliber'];
data['Ford SUV'] = ['Escape','Edge','Explorer'];
data['Toyota SUV'] = ['Rav4','Highlander','4runner'];
var hold = data['init'];//Sets data to 'init' by default
var selectedArray = [];//This array holds the selected options (to be used to display the vehicle name)
function init(){//call first to create the first select box and populate with 'init'
firstSelect = document.createElement('select');
firstSelect.setAttribute("onChange","createSelect(this.value)");
createSelect('init');
}
//Main create function for select boxes
function createSelect(value){
selectHold = value;//sets selectHold to the value of the selected item (this will be used for displaying the name in disName)
//This just prevents it from adding "Car, Truck or SUV to the selectedArray
if(value != 'init' && value != 'Truck' && value != 'Car' && value != 'SUV' && value != 'Select your vehicle options'){
selectedArray.push(selectHold);
}
hold=data[value];// sets this holder to the value of the selected item for the if statement
if(hold){ //just checks to see if hold exists
var selEle = document.createElement('select');//creates new select element
//gives selEle onchange function
selEle.setAttribute("onChange","createSelect(this.value)");
//Creates the "default" option. Forcing them to pick something.
var defaultOpt = document.createElement('option');
var vehInfo = document.createTextNode("Select your vehicle options");
defaultOpt.appendChild(vehInfo);
selEle.appendChild(defaultOpt);
//Populates the options and adds it to the document
for(var i = 0, l = hold.length; i < l; i++){
var newOpt = document.createElement('option');
newOpt.appendChild(document.createTextNode( hold[i]));
newOpt.setAttribute('value',hold[i]);
selEle.appendChild(newOpt);
}
//put select on the page
document.getElementById('top-container').appendChild(selEle);
}
else{ //if not, then put out final form
disName(selectHold,selectedArray);//call disName function an dpass it the value of selectHold
}
}
HTML:
<div id="top-container">
<h1>Awesome<br/>
Car<br/>
Picker</h1>
</div>
<div id="middle-container">
<h2>Your vechle choice:</h2>
</div>
<div id="bottom-container">
<div id="mail-form">
<form name='mail-form'>
<label>Name</label>
<input name="name" autofocus>
<label>Email</label>
<input name="email">
<label>Credit Card number</label>
<input name="cc">
<input id="submit" name="submit" value="Submit" onClick="validate()">
</form>
</div>
</div>
<body>
What I'm thinking is to check the to see if the selection is the lastChild of the parent node (top container). and if it is not then delete the child of that until it's at the point where it's only the selection that was changed and any selection that fell before it.
Any suggestions?
Thanks!
In your createSelect function, assign an ID to the new element using something like selEle.id = 'newID';.
Before calling the createSelect function, check to see if the new element exists and if so, remove it:
if (document.getElementById('newID'))
document.getElementById('top-container').removeChild(document.getElementById('newID'));

Categories

Resources