Hey, I'm having some trouble with this problem, and I don't even know where to start.
I'm using foxycart for an ecommerce website I'm building for my girlfriend, so sending values to the "cart" is limited to the input names foxycart is looking for.
IE; name, price, product_sku.
I have a tiny CMS backend that allows you to add different sizes, sku's for those sizes and a different price for that size.
So, being that I'm using foxycart, I need hidden inputs to send the values to the cart.
<input type="hidden" name="name" value="Test" />
<input type="hidden" id="price" name="price" value="19.99" />
<input type="hidden" id="product_sku" name="product_sku" value="sku3445" />
<input type="hidden" id="product_id" name="product_id" value="123" />
This works good. sends the name, price and sku to the cart.
I've made a drop down box that lists the different sizes/prices related to that product. I've set it up so that selecting a different size changes the price:
<select id="single" name="options" />
<option name="option_price" value="19.99">Default - $19.99</option>
<option name="option_price" value="18.99">Test Size: 18.99</option>
</select>
function displayVals() {
var singleValues = $("#single").val();
("#item_price").html(singleValues);
$("#price").val(singleValues);
}
$("select").change(displayVals);
displayVals();
This works too, send the price selected to a div and the hidden price input(so you can see the new purchase price) and to the cart(so the cart is showing the price of the product you want to purchase)
And now for the question:
How do I set this up so that selecting a different size/price will change the hidden inputs so that the product_sku, and size name are updated along with the price?
I'm thinking I have to use some Jquery.ajax() call, but have no idea...
Would this work?:
Jquery:
$(document).ready(function(){
$("form#get_stuff").change(function() {
var product_id= $('#product_id').attr('value');
$.ajax({
type: "POST",
url: get_stuff.php,
data: "product_id="+product_id,
success: function(data){
$('#product_inputs').html(data);
}
});
return false;
});
});
the 'data' being:
from the php page?
This is my first foray into Jquery ajax, so I really have no idea.
Edit:
Sorry, I just read this over and it's kind of confusing....
Here is the workflow I'm trying to accomplish:
Page loads:
using php, echo product name, price, sku. (This is the default)
Drop-box change:
using jquery, dynamically change the hidden inputs with new information based off the product_id, and the size selected from the drop-box (Update 4 hidden inputs based off the value from one value from a select menu)
Instead of using AJAX when the select box changes, you can also load the SKU and product ID when the page loads and add them as data on the option tags. One way to do this is to add them as classes like so:
<select id="single" name="options">
<option name="option_price" class="sku3445 id123" value="19.99">Default - $19.99</option>
<option name="option_price" class="sku3554 id321" value="18.99">Test Size: 18.99</option>
</select>
Then using a little RegEx you can extract these values from the selected option in your change() function and update the hidden inputs accordingly:
function displayVals() {
var $single = $('#single'),
singleValues = $single.val(),
singleClasses = $single.find('option:selected').attr('class'),
singleSKU = singleClasses.match(/\bsku\d+\b/)[0],
singleID = singleClasses.match(/\bid\d+\b/)[0].replace('id','');
$("#item_price").html(singleValues);
$("#price").val(singleValues);
$('#product_sku').val(singleSKU);
$('#product_id').val(singleID);
}
$("select").change(displayVals);
displayVals();
Here is a working example →
Using Ajax is the way to go. When the dropdown value changes, you will want to trigger the Ajax call to a PHP method, which I assume would query a backend database for necessary information using the dropdown value as a parameter, then return that information to populate the hidden fileds. All these steps should happen in your Ajax call.
Related
I'm using Laravel 5 to generate a form for a warehouse. In Main form you can select which items to get and it should generate a PDF with the items (all info), people to get the items, date and invoice number.
All the information is on a DIV called 'invoice'. How can I send this object to a new view to generates the PDF. I read about 'invoking dompdf via web' to make it more interactive but the documentation is not clear enough or doesn't fit with I'm needing.
This is my current code:
From:
Recibo.js
$('#createPDF').click(function()
{
$htmlData = "data";
$_token = $('[name="_token"]').val();
$.get('recibos/pdf',{ html:$htmlData, _token: $_token })
.done(function(data)
{
console.log('Done PDF!');
});
});
ReciboController.php
public function reciboPDF(Request $request)
{
$data = $request->get('html');
$pdf = \PDF::loadView('create.template.formReciboPDF',compact('data'))->setPaper('letter')->setOrientation('landscape');
return $pdf->stream();
//return view('create.template.formReciboPDF');
}
formReciboPDF.blade.php
<tr>
<td>{{$data}}</td>
<td>Papeleria</td>
<td>Unidad</td>
<td>Grande</td>
<td>La Palma</td>
<td>2342423424234</td>
<td>Bueno</td>
<td>9</td>
</tr>
Instead of trying to capture the HTML can you send the selection parameters to the server and rebuid the page? Then you would just need to feed the generated HTML into dompdf and render. If visual appearance is important you could use hidden checkboxes as the selection mechanism.
If you want to use a shortcut you can capture the HTML using jQuery.contents().
In your second part it looks like you're trying to send your request via AJAX and get back the PDF. While this is technically possible it's more trouble than it's worth. An easier alternative would be to submit a hidden form to a blank window. It would require some minor changes to your HTML/JS but little else, e.g.
$('#createPDF').click(
function() {
$('#html').val($('#invoice').content());
$(this).closest('form').submit();
});
<form method="POST" action="recibos/pdf" target="_blank">
<input type="hidden" name="html" id="html" value="" />
<input type="hidden" name="_token" value="{value from server}" />
<button type="button" id="createPDF">Create PDF</button>
</form>
I'm trying using Backbone.Marionette to build an application. The application gets its data through REST calls.
In this application I created a model which contains the following fields:
id
name
language
type
I also created an ItemView that contains a complete form for the model. The template I'm using is this:
<form>
<input id="model-id" class="uneditable-input" name="id" type="text" value="{{id}}"/>
<input id="model-name" class="uneditable-input" name="name" type="text" value="{{name}}" />
<select id="model-language" name="language"></select>
<select id="model-type" name="type"></select>
<button class="btn btn-submit">Save</button>
</form>
(I'm using Twig.js for rendering the templates)
I am able to succesfully fetch a model's data and display the view.
What I want to do now is populate the select boxes for model-language and model-type with options. Language and type fields are to be restricted to values as a result from REST calls as well, i.e. I have a list of languages and a list of types provided to me through REST.
I'm contemplating on having two collections, one for language and one for type, create a view for each (i.e. viewLanguageSelectOptions and viewTypeSelectOptions), which renders the options in the form of the template I specified above. What I am not sure of is if this is possible, or where to do the populating of options and how to set the selected option based on data from the model. It's not clear to me, even by looking at examples and docs available, which Marionette view type this may best be realized with. Maybe I'm looking in the wrong direction.
In other words, I'm stuck right now and I'm wondering of any of you fellow Backbone Marionette users have suggestions or solutions. Hope you can help!
Create a view for a Select in my opinion is not needed in the scenario that you are describing, as Im assuming that your languages list will not be changing often, and the only porpouse is to provide a list from where to pick a value so you can populate your selects in the onRender or initializace function of your view using jquery.
you can make the calls to your REST service and get the lists before rendering your view and pass this list to the view as options and populate your selects on the onRender function
var MyItemView = Backbone.Marionette.ItemView.extend({
initialize : function (options) {
this.languages = options.languages;
this.typeList = options.typeList;
},
template : "#atemplate",
onRender : function () {
this.renderSelect(this.languages, "#languagesSelect", "valueofThelist");
this.renderSelect(this.typeList, "#typesSelect", "valueofThelist")
},
renderSelect :function (list, element, value) {
$.each(list, function(){
_this.$el.find(element).append("<option value='"+this[value]+"'>"+this[value]+"</option>");
});
}
})
var languagesList = getLanguages();
var typeList = getTypesList();
var myItemView = new MyItemView({languages:languagesList,typeList :typeList });
Hope this helps.
I have a drop down list that list different options to the user. I need the list to populate a text area based on what the user selects. I have the data already in my database and I want to be able to run a query based the user's selection from the drop down list.
This is how my select tag looks like right now:
<select name="procedure" onChange="">
<option value="">Select Procedure</option>
<cfloop query="procedures">
<option value="#procedureId#">#procedureName#</option>
</cfloop>
</select>
And this is my text area:
<textarea name="procedureDescription" cols="80" rows="6">#the query output will go here#</textarea><br />
Is there a way to use onSelectChange function to control a server side query with Ajax?
I hope my thoughts are clear, if you need more info please ask.
Yes, unless I misunderstand, you should be able to do this using an Ajax request. The onchange method should look something like this:
function handleProcedureChange()
{
var selectedVal = $(this).val();
var url; // TODO set procedure URL here, using selectedVal as needed
$.get(url, function(procedureResult) {
$("#procedureDescription").text(procedureResult);
});
}
Then you'd need to set up the server-side method to run the procedure and return the result as plain text.
MVC/Razor/Javascript newbie question:
I have a MVC3/Razor form where the use can select a single product from a drop down list.
<div class="editor-label">
Product
</div>
<div class="editor-field">
#Html.DropDownList("ProductID", (IEnumerable<SelectListItem>)ViewBag.Products, "--Select One--")
#Html.ValidationMessageFor(model => model.ProductID)
</div>
What I then want is to display the price of the selected product on a label just below the drop down list (model property name is Amount).
This should be pretty easy, but I am pretty new at Razor, and know almost nothing about Javascript, so I would appreciate any verbose explanations of how do do it, and how it all hangs together.
Add a div/span under the Dropdown .
#Html.DropDownList("ProductID", (IEnumerable<SelectListItem>)ViewBag.Products, "--Select One--")
<div id="itemPrice"></div>
and in your Script, make an ajax call to one of your controller action where you return the price.
$(function(){
$("#ProductId").change(function(){
var val=$(this).val();
$("#itemPrice").load("#Url.Action("GetPrice","Product")", { itemId : val });
});
});
and have a controller action like this in your Product controller
public string GetPrice(int itemId)
{
decimal itemPrice=0.0M;
//using the Id, get the price of the product from your data layer and set that to itemPrice variable.
return itemPrice.ToString();
}
That is it ! Make sure you have jQuery loaded in your page and this will work fine.
EDIT : Include this line in your page to load jQuery library ( If it is not already loaded),
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
The Amount isn't available to your view when the user selects a product (remember the page is rendered on the server, but actually executes on the client; your model isn't available in the page on the client-side). So you would either have to render in a JavaScript array that contains a lookup of the amount based on the product which gets passed down to the client (so it's available via client-side JavaScript), or you would have to make a callback to the server to retrieve this information.
I would use jQuery to do this.
Here's a simple example of what the jQuery/Javascript code might look like if you used an array.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
// This code can easily be built up server side as a string, then
// embedded here using #Html.Raw(Model.NameOfPropertyWithString)
var list = new Array();
list[0] = "";
list[1] = "$1.00";
list[2] = "$1.25";
$("#ProductID").change(displayAmount).keypress(displayAmount);
function displayAmount() {
var amount = list[($(this).prop('selectedIndex'))];
$("#amount").html(amount);
}
});
</script>
<select id="ProductID" name="ProductID">
<option value="" selected>-- Select --</option>
<option value="1">First</option>
<option value="2">Second</option>
</select>
<div id="amount"></div>
You'll want to spend some time looking at the docs for jQuery. You'll end up using it quite a bit. The code basically "selects" the dropdown and attaches handlers to the change and keypress events. When they fire, it calls the displayAmount function. displayAmount() retrieves the selected index, then grabs the value out of the list. Finally it sets the HTML to the amount retrieved.
Instead of the local array, you could call your controller. You would create an action (method) on your controller that returned the value as a JsonResult. You would do a callback using jquery.ajax(). Do some searching here and the jQuery site, I'm sure you'll find a ton of examples on how to do this.
This is my first attempt at chaining select boxes in a web form using ajax and I I'm obviously missing something. I'm simply at a loss for what that is, exactly. Here is my issue:
A user selects a Country from one select box and an ajax request is made and options (containing names of States and Territories) are returned to a select box below. While the options are returned into the form select field, the user-selected option is NOT sent when the form is submitted.
Here is the code I've cooked up:
<script type="text/javascript">
jQuery(document).ready(function($){
$("select#state").attr("disabled","disabled");
$("select#country").change(function(){
$("select#state").attr("disabled","disabled");
$("select#state").html("<option>Loading States...</option>");
var id = $("select#country option:selected").attr('value');
$.post("http://example.com/terms.php", {id:id}, function(data){
$("select#state").removeAttr("disabled");
$("select#state").html(data);
});
});
});
</script>
You can see the live example here (see the Country/State section):
http://shredtopia.com/add/
Any ideas what is needed to get this working?
As far i can see, the user input is sent
input_32 79
input_29 alberta
Being 79 the country canada and alberta the state.
<select tabindex="11" class="medium gfield_select" id="input_1_32" name="input_32"></select>
<select tabindex="12" class="medium gfield_select" id="input_1_29" name="input_29" disabled=""></select>
Maybe i misunderstood the issue?
Try .live( eventType,handler )
Description: Attach a handler to the event for all elements which match the current selector, now and in the future.
http://api.jquery.com/live/
Add to your code and try it~
$('select#state').live('change', function() {
var id = $("select#state option:selected").attr('value');
alert(id);
});
Or try this:
add a hidden in form:
<input type="hidden" id="hiddenValue">
alter your select#state like this:
<select onchange='innerValue(this.options[this.options.selectedIndex].value)'></select>
and create a javascript function
function innerValue(value){
$("#hiddenValue").val(value)
}
then,click submitbutton,$("#hiddenValue").val() is you need
$("#submitbutton").click(function(){
alert($("#hiddenValue").val())
})
but,I think this is not the best solution...