Keep auto created fields shown after reload - javascript

I have a javscript code that create fields based on select menus
HTML
<div class="container">
<div id="selected_form_code">
<select id="select_btn">
<option value="0">--How many rooms ?--</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
</div>
<div id="form_submit">
<!-- Dynamic Registration Form Fields Creates Here -->
</div>
</div>
JS
function get_chambre_html(cn)
{
return "<div>"
+ "<b>Chambre " + cn + ":</b> "
+ "<br/>Adultes: <select id='adultes" + cn + "'>"
+ "<option value='0'>--How many adults ?--</option>"
+ "<option value='1'>1</option>"
+ "<option value='2'>2</option></select>"
+ "<br/>Enfants: <select id='enfants" + cn + "'>"
+ "<option value='0'>--How many enfants ?--</option>"
+ "<option value='1'>1</option>"
+ "<option value='2'>2</option><option value='3'>3</option><option value='4'>4</option></select>"
+ "<div id='ages" + cn + "'></div>" // empty block for further usage
+"</div>";
}
$(document).ready(function()
{
$('select#select_btn').change(function()
{
var sel_value = $('option:selected').val();
$("#form_submit").empty(); //Resetting Form
// Below Function Creates Input Fields Dynamically
create(sel_value);
// Appending Submit Button To Form
});
function create(sel_value)
{
for (var i = 1; i <= sel_value; i++)
{
$("div#form1").append($("#form_submit").append(get_chambre_html(i)));
$("div#form1").append($("#form_submit").append("<div id='ages"+i+"'/>"));
$('select#enfants'+i).change(function(){
var infants = this.value;
var i=this.id.substr(7); // 7 = strlen of 'enfants'
$('#ages'+i).empty();
for(var j=0; j<infants; j++)
$('#ages'+i).append("Age enfant "+(j+1)+" : <select><option>1 an</option><option>2 ans</option><option>3 ans</option></select>");
});
}
};
});
Is there any way to keep auto created fields shown after page reload ? Because, for now, if i reload the page for another search, this fields disappear.
Before/After search:
Fields values are sent by GET method.

There are many ways of doing this. I would write a cookie. A cookie is data written to the user's browser and will persist between requests. Cookies are a great way to store data and there are already API's in javascript to do so. You can write to the cookie by assigning to document.cookie. As your working with a form I would serialize an object that represents the current state of your form.
document.cookie = JSON.stringify({ destination: 'BERCELONE' });
When the page loads you can check your value
var currentFormState = JSON.parse(document.cookie);
functionThatBuildsTheFormFromObject(currentFormState);
Now that we know how to store a cookie we need to figure out what to store in the cookie. To do this I would write two functions. The first function lets call it functionThatBuildsTheFormFromObject() would accept an object. I would use the following object. Note here that for each adult and child we use a value in an array.
{
destination : "Berclona",
depatureDate : "30-08-2016",
adults : [],
children : [ 5, 8],
seniors : [ 55, 58 ]
}
With this object let's create the form
functionThatBuildsTheFormFromObject (theFormObject) {
createDestinationField(theFormObject.destination);
createDepatureDateField(theFormObject.depatureDate);
theFormObject.adults.forEach(adultAge => {
createSelectAgeField('adult', adultAge)
})
theFormObject.children.forEach(childAge => {
createSelectAgeField('child', childAge)
})
theFormObject.seniors.forEach(seniorAge => {
createSelectAgeField('senior', seniorAge)
})
}
So now all that is required is to white functions to create all the fields which in part you have already done. Going the other way I would define a function that will give you the current values of your form. Check this
Convert form data to JavaScript object with jQuery question as it does exactly what you need. I would call this function serializeForm(). I would also look at setting the cookie each time the form changed. That way when ever the user refreshes their browser the form should always be updated. You might also think about providing the user a reset form button too incase they want to start again.

Related

Load a selected option on a dynamically created `<select>`?

I have a web page that saves a bunch of options (from a <select>). I can store the values via PHP and MySQL just fine and restore the values of those selects.
The problem comes with dynamically created selects. Through logging to the console, I can confirm the HTML of the <select>s has loaded properly and they function properly on screen. But none of them load the stored value.
I’ve tried using:
$("#selectID").val(storedVariable);
$("#selectID").prop("selectedIndex", storedIndex);
$("#selectID option[value=" + storedVariable + "]").prop("selected", true);
None of these options work. And to make matters worse, I can use the console to check the .val() or .prop("selectedIndex") and they return the proper value, but the <option> displayed/selected drop-down option is blank (index 0).
Again, this is only on dynamically created selects, the ones hard-coded in work just fine.
here's the code I'm using:
file.html
<select id="select1">
<option value="choice1">Choice 1</option>
<option value="choice2">Choice 2</option>
</select>
<select id="select2"></select>
file.js
// selectedValue1 & selectedValue2 are sent from file.php
console.log(selectedValue1); // -> "choice2"
console.log(selectedValue2); // -> "choice2B"
// these work, I can verify them in the console
$("#select1").val(selectedValue1);
updateSelections();
$("#select2").val(selectedValue2);
function updateSelections() {
$("#select2").html(function() {
var optionChoices = "<option value='blank'> </option>";
if ("#select1".val() == "choice1") {
optionChoices += "<option value='choice1A'>Choice 1A</option>";
optionChoices += "<option value='choice1B'>Choice 1B</option>";
optionChoices += "<option value='choice1C'>Choice 1C</option>";
return optionChoices;
} else if ("#select1".val() == "choice2") {
optionChoices += "<option value='choice2A'>Choice 2A</option>";
optionChoices += "<option value='choice2B'>Choice 2B</option>";
optionChoices += "<option value='choice2C'>Choice 2C</option>";
}
return optionChoices;
}, 0);
}
Basically selectedValue1 loads perfectly, but selectedValue2 does not.
UPDATE: Here's the actual line of code from my app that should work.
console.log(fieldOfStudy);
$("#selectFieldOfStudy").val(fieldOfStudy);
console.log($("#selectFieldOfStudy").val());
The console.log() outputs the correct stored information both times, but the value is not displayed correctly on screen.
You have errors in your code.
Function updateSelections should be defined before being used
"#select1".val() : wrap "#select1" into $()
Also consider updating select2 each time the first select is modified:
$("#select1").on('change', updateSelections);
See the jsFiddle: https://jsfiddle.net/xpvt214o/613071/

Dynamically ceate fields from select Javascript

I have a javascript code that dynamicly create select lists from a select list.
It's working fine, i just need to keep all created select lists shown after a page reload. Now, if i reload the page new select lists disappear.
<div class="container">
<div id="selected_form_code">
<select id="select_btn">
<option value="0">--How many rooms ?--</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
<div id="form_submit">
<!-- Dynamic Registration Form Fields Creates Here -->
</div>
</div>
<script>
function get_chambre_html(cn)
{
return "<div>"
+ "<b>Chambre " + cn + ":</b> "
+ "Adultes: <select id='adultes" + cn + "'>"
+ "<option value='0'>--How many adults ?--</option>"
+ "<option value='1'>1</option>"
+ "<option value='2'>2</option></select>"
+ "<br/>Enfants: <select id='enfants" + cn + "'>"
+ "<option value='0'>--How many enfants ?--</option>"
+ "<option value='1'>1</option>"
+ "<option value='2'>2</option></select>"
+ "<div id='ages" + cn + "'></div>" // empty block for further usage
+"</div>";
}
$(document).ready(function()
{
$('select#select_btn').change(function()
{
var sel_value = $('option:selected').val();
$("#form_submit").empty(); //Resetting Form
// Below Function Creates Input Fields Dynamically
create(sel_value);
// Appending Submit Button To Form
});
function create(sel_value)
{
for (var i = 1; i <= sel_value; i++)
{
$("div#form1").append($("#form_submit").append(get_chambre_html(i)));
$("div#form1").append($("#form_submit").append("<div id='ages"+i+"'/>"));
$('select#enfants'+i).change(function(){
var infants = this.value;
var i=this.id.substr(7); // 7 = strlen of 'enfants'
for(var j=0; j<infants; j++)
$('#ages'+i).append(':[input age block '+i+']: ');
});
}
};
});
</script>
Before the user leaves/refreshes the page, you can store selections in localStorage or sessionStorage like this:
window.onbeforeunload = function() {
localStorage.setItem(name, $('#select_btn :selected').val());
}
And on page load, you can check to see whether any data has been saved to local storage so you can make sure your page displays what the user had last selected.

How to pass select list value in action link without using javascript and creating a model for it?

I have a shopping cart and I created a simple select list for quantity via Html. I would like to use an Html.ActionLink to get the value of that select list, however if I use JavaScript in will not work as it is inside a PartialView called product and there are multiple number of product on the page.
How could I get the value of that select list without JavaScript? I did look around, but did not find anything useful. Is there any other way?
PartialView
<p>#Model.Description</p>
<p id="price">#Model.Price</p>
<p class="id hidden">#Model.GadgetID</p>
<select name="Select" id="quantity">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<p>
Html.ActionLink("Add To Cart", "AddOrder", "Home",new { qty = ?? , id = Model.GadgetID, price = Model.Price }, null )
</p>
Or if I use JavaScript how can I get the right details as there are multiple products on the page.
View that includes that PartialView.
<div class="col-lg-10 products">
<div class="pad">
#foreach (var item in Model)
{
foreach (var gadget in item.Gadgets)
{
#Html.Partial("Gadget", gadget)
}
}
</div>
</div>
JQuery
<script type="text/javascript">
$(document).ready(function () {
$(".AddToCartBtn").click(function () {
var _qty = $(this).find("#quantity").val();
var _id = $(this).find(".id").val();
var _price = $("#price").html();
alert("qty: " + _qty + " id: " + _id + " price: " + _price);
});
});
You cannot do it without client side javascript because user can change the selection of your quantity dropdown at client side.
With Javascript / jQuery, you can read the value of selected option and append to the query string when the link is clicked. Also since you will have the same markup generated from the partial view, you should not use hardcoded static ids. Id's should be unique for html elements. With your current code, it will generate same id for all the quantity select elements. You can use a css class and use the closest() and find() method to get access to the quantity select element of the link clicked.
<div class="gadgetItem">
<select name="Select" class="qtySelect">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
#Html.ActionLink("Add To Cart", "AddOrder", "Home",
new { #id = Model.GadgetID, price = Model.Price }, new { id="addToCart"} )
</div>
and in JavaScript, listen to the click event on the link. Assuming jQuery is available to the page,(this code should go in the main page,not in the partial view)
$(function(){
$(document).on("click","#addtoCart",function(e){
e.preventDefault(); // Stop the normal link click behaviour
var currentUrl = $(this).attr("href"); // Get the url
// Append the quantity value to query string
var newUrl = currentUrl + "?qty =" + $(this).closest(".gadgetItem")
.find(".qtySelect").val();
window.location.href=newUrl; ///Load the new page with all query strings
});
});
Also I suggest you not read the price from the client request. You should always read it back from the db in server based on the Id of the item. If not, I can update the price in the query string to "0.0001" and order thousands of your products!

jquery dynamically add html fields met mysterious problems

I am using jquery to duplicate several html fields based on user's selection. However, I met an interesting problem. In general, I am asking users to select how many applications they want:
if there is only one application:
a. One need to choose application method (for simplicity, only 'aerial' is available); b. after selecting 'aerial', it will ask you for the further information, chemically application method (CAM).
if they choose two applications, jquery code will clone and rename the necessary questions for you.
My problem is when I choose there are two applications, the sub-question 'CAM' will not show up. After some trouble shoot, I found the problem could be in this javascript :$('.app_method:last').find('select').change(function(). The statement, automatically increase my loop index by one (Can anyone tell me why this will happen?), which mismatch the code.
Here is a DEMO for my code:
Below is my html code:
<div class="articles">
<table align="center">
<tr><th><label for="id_NOA">Number of applications:</label></th><td><select name="NOA" id="id_NOA">
<option value="1" selected="selected">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select></td></tr>
<tr><th><label for="id_Ap_m">Application method 1</label></th><td><select name="Ap_m" id="id_Ap_m">
<option value="" selected="selected">Select an application method</option>
<option value="1">Aerial</option>
</select></td></tr>
<tr><th><label for="id_CAM_1">Chemical application Method (CAM) 1</label></th><td><select name="CAM_1" id="id_CAM_1">
<option value="2">2-Interception based on crop canopy</option>
<option value="9">9-Linear foliar based on crop canop</option>
</select></td></tr>
</table>
</div>
​
jquery code:
$(document).ready(function() {
//this part of code controls inputs when there is only one application
$('#id_CAM_1').attr('id', 'id_1').closest('tr').addClass('method_options').hide();
$('#id_Ap_m').change(function() {
$('tr.method_options').hide();
if ($(this).val() == "1") {
$('#id_' + $(this).val()).closest('tr').show();
}
});
i = 1;
$('.articles').find('table').addClass('table');
$('#id_Ap_m').closest('tr').addClass('app_method');
$('#id_NOA').change(function() {
var total = $(this).val();
//remove all
$('.app_method').each(function(index) {
if (index != 0) $(this).remove()
});
//create new ones
for (var i = 2; i <= total; i++) {
alert('a=' + i);
$('.app_method:first').clone().appendTo('.table').find('label').text('Application method ' + i);
$('.app_method:last').find('select').attr('name', 'Ap_m' + i).attr('id', 'id_Ap_m' + i);
alert('b=' + i);
$('<tr class="method_options_1' + i + '" style="display: none;"><th><label for="id_CAM_1">Chemical application Method (CAM)' + i + '</label></th><td><select name="CAM_1_' + i + '" id="id_1_' + i + '"><option value="2">2-Interception based on crop canopy</option><option value="9">9-Linear foliar based on crop canop</option></select></td></tr>').appendTo('.table');
alert('c=' + i);
//The following statement increase the loop index by one, which causes me problems. Can
//anyone let me know why this could happen?
$('.app_method:last').find('select').change(function() {
alert('d=' + i)
$('.method_options_1').hide();
alert('e=' + i);
if ($(this).val() == "1") {
alert('e=' + i);
$('.method_options_1' + i).show();
}
})
}
})
})​
​
I think this can be done much more simply: (fiddle: http://jsfiddle.net/QaHWz/)
<!DOCTYPE html><html><head></head><body>
<table align="center"><tbody>
<tr><th></th><td>Add Application</td></tr>
</tbody></table>
<table id="template" style="display:none"><tbody>
<tr>
<th><label for="id_Ap_m_{n}">Application method {n}</label></th>
<td>
<select class="Ap_m" name="Ap_m_{n}" id="id_Ap_m_{n}" data-application="{n}">
<option value="" selected="selected">Select an application method</option>
<option value="1">Aerial</option>
</select>
</td></tr>
<tr style="display:none" class="app_{n} method_1"><th><label for="id_CAM_{n}">Chemical Application Method (CAM) {n}</label></th><td><select name="CAM_{n}" id="id_CAM_{n}">
<option value="2">2-Interception based on crop canopy</option>
<option value="9">9-Linear foliar based on crop canopy</option>
</select></td></tr>
</tbody></table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
jQuery(function($) {
var applications = 0;
$('#add_application').click(function() {
applications++;
var last_row = $(this).closest('tr');
last_row.before(jQuery('#template tbody').html().replace(/{n}/g, applications));
});
$(document).delegate('.Ap_m', 'change', function() {
var app = $(this).data('application');
$('.app_'+app).hide();
$('.app_'+app+'.method_'+this.value).show();
});
});
</script>
</body></html>
EDIT: The problem you are having with .change() is that you are using the i variable , which gets incremented before the function is run. You need to get the value of i into the function another way. Here is one possible way you can do it:
$('.app_method:last').find('select').bind('change', { row: i }, function(event) {
var i = event.data.row;
alert('d=' + i)
// ...
});
The { row: i } bit causes jQuery to attach this data to the event object which is passed to the function. Then I create var i inside the scope of the function, which will not be affected by the i outside, and assign this value to it.

Manually type in a value in a "Select" / Drop-down HTML list?

In a Windows Forms application, a drop-down selector list also gives the user the option of typing an alternate value into that same field (assuming the developer has left this option enabled on the control.)
How does one accomplish this in HTML? It appears as if it is only possible to select values from the list.
If it's not possible to do this with straight HTML, is there a way to do this with Javascript?
It can be done now with HTML5
See this post here HTML select form with option to enter custom value
<input type="text" list="cars" />
<datalist id="cars">
<option>Volvo</option>
<option>Saab</option>
<option>Mercedes</option>
<option>Audi</option>
</datalist>
I faced the same basic problem: trying to combine the functionality of a textbox and a select box which are fundamentally different things in the html spec.
The good news is that selectize.js does exactly this:
Selectize is the hybrid of a textbox and box. It's jQuery-based and it's useful for tagging, contact lists, country selectors, and so on.
The easiest way to do this is to use jQuery : jQuery UI combobox/autocomplete
ExtJS has a ComboBox control that can do this (and a whole host of other cool stuff!!)
EDIT: Browse all controls etc, here: http://www.sencha.com/products/js/
Another common solution is adding "Other.." option to the drop down and when selected show text box that is otherwise hidden. Then when submitting the form, assign hidden field value with either the drop down or textbox value and in the server side code check the hidden value.
Example: http://jsfiddle.net/c258Q/
HTML code:
Please select: <form onsubmit="FormSubmit(this);">
<input type="hidden" name="fruit" />
<select name="fruit_ddl" onchange="DropDownChanged(this);">
<option value="apple">Apple</option>
<option value="orange">Apricot </option>
<option value="melon">Peach</option>
<option value="">Other..</option>
</select> <input type="text" name="fruit_txt" style="display: none;" />
<button type="submit">Submit</button>
</form>
JavaScript:
function DropDownChanged(oDDL) {
var oTextbox = oDDL.form.elements["fruit_txt"];
if (oTextbox) {
oTextbox.style.display = (oDDL.value == "") ? "" : "none";
if (oDDL.value == "")
oTextbox.focus();
}
}
function FormSubmit(oForm) {
var oHidden = oForm.elements["fruit"];
var oDDL = oForm.elements["fruit_ddl"];
var oTextbox = oForm.elements["fruit_txt"];
if (oHidden && oDDL && oTextbox)
oHidden.value = (oDDL.value == "") ? oTextbox.value : oDDL.value;
}
And in the server side, read the value of "fruit" from the Request.
I love the Shadow Wizard answer, which accually answers the question pretty nicelly.
My jQuery twist on this which i use is here. http://jsfiddle.net/UJAe4/
After typing new value, the form is ready to send, just need to handle new values on the back end.
jQuery is:
(function ($)
{
$.fn.otherize = function (option_text, texts_placeholder_text) {
oSel = $(this);
option_id = oSel.attr('id') + '_other';
textbox_id = option_id + "_tb";
this.append("<option value='' id='" + option_id + "' class='otherize' >" + option_text + "</option>");
this.after("<input type='text' id='" + textbox_id + "' style='display: none; border-bottom: 1px solid black' placeholder='" + texts_placeholder_text + "'/>");
this.change(
function () {
oTbox = oSel.parent().children('#' + textbox_id);
oSel.children(':selected').hasClass('otherize') ? oTbox.show() : oTbox.hide();
});
$("#" + textbox_id).change(
function () {
$("#" + option_id).val($("#" + textbox_id).val());
});
};
}(jQuery));
So you apply this to the below html:
<form>
<select id="otherize_me">
<option value=1>option 1</option>
<option value=2>option 2</option>
<option value=3>option 3</option>
</select>
</form>
Just like this:
$(function () {
$("#otherize_me").otherize("other..", "put new option vallue here");
});
Telerik also has a combo box control. Essentially, it's a textbox with images that when you click on them reveal a panel with a list of predefined options.
http://demos.telerik.com/aspnet-ajax/combobox/examples/overview/defaultcs.aspx
But this is AJAX, so it may have a larger footprint than you want on your website (since you say it's "HTML").

Categories