Dynamically ceate fields from select Javascript - 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.

Related

I'm trying to source values for a select drop down from a table using JavaScript and jQuery, but the select menu doesn't show any values?

This is the html for the drop down:
<div id="selectEvent" style="width:200px;">
<select>
<option value="0">Select Event:</option>
<option value="1">Event Name</option>
</select>
</div>
This is how I am trying to get the values from a table into the drop down list:
var options = [];
function callback(tx, results) {
var htmlCode;
var cmbType = $("#cboAddEventType");
for (var i = 0; i < results.rows.length; i++)
{
var row = results.rows.item(i);
htmlCode += '<option value="' + row.id + '">' + row.name + '</option>';
}
cmbType.append(htmlCode);
cmbType.html(htmlCode).val(1).change();
}
EventType.selectAll(options, callback);
var sqlInsertEventType = ["INSERT INTO eventType (name) VALUES ('Business')",
"INSERT INTO eventType (name) VALUES ('Personal')",
"INSERT INTO eventType (name) VALUES ('Commercial')"];
But nothing appears in the drop down when I run the application. It's empty. What's wrong? Does it matter what order I link the scripts in the html page or something?
You do not have an html element with id cboAddEventType, you should add this as an id for your select element.
<select id="cboAddEventType">
your code needs some more fixes, but I guess you will get them yourself.

how to keep last time selected value in dropdownlist even after re-open app

dropdown = '';
dropdown += '<option value="' + CONFIGURATOR.ChineseLanguage + '">Series 1520</option>\n';
dropdown += '<option value="' + CONFIGURATOR.EnglishLanguage + '">Series 1580</option>\n';
$('.tab-setup select[name=languageSelect]').html(dropdown);
html
<select class="dropdown" name="languageSelect" id="selectlanguage"></select>
datavariable.js
var CONFIGURATOR = {
'ChineseLanguage': 'zh',
'EnglishLanguage': 'en'
};
how to keep last time selected option in dropdownlist still appear even after re-open app
You can use localStorage api to store the value, and it will be persisted even when the application is closed.
var dropdown = '',
$select = $('.tab-setup select[name=languageSelect]'),
storedValue = localStorage.getItem('languageSelectValue');
dropdown += '<option value="' + CONFIGURATOR.ChineseLanguage + '">Series 1520</option>\n';
dropdown += '<option value="' + CONFIGURATOR.EnglishLanguage + '">Series 1580</option>\n';
$select.html(dropdown);
//Set the initial value if any
if (storedValue) {
$select.val(storedValue);
}
//Bind a listener to store the selected value in localStorage
$select.on('change', function () {
localStorage.setItem('languageSelectValue', $(this).val());
});

Keep auto created fields shown after reload

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.

Trying to delete Select box using jQuery remove() function

I am trying to delete select box using jQuery remove function but it does not work. The select box itself is dynamically generated one. I want to delete the same select box if the user wants to delete the dropdown after adding. My code is:
$("#dltElement").click(function() {
$("#idSelect").remove();
});
My code to add the select boxes:
$(document).ready(function() {
var count = 3;
$("#btnCompare").click(function() {
if (count > 4) {
alert("Only 4 options are allowed");
return false;
}
$("#form-group").append(
"<select name='idSelect" + count + "' id='idSelect" + count + "'>" +
"<option>--Select Product" + counter + "--</option>" +
'<option value="p1">Product 1</option>' +
'<option value="p2">Product 2</option>' +
"</select>" + '<input type="button" value=" - " id="dltElement' + count + '" class="btn-minus pull-left" />'
);
count++;
}); // Script for adding dropdown dynamically
});
#idSelect is not present you have to use #idSelect0 or #idSelect1 ... and so on. Rather than you can lookup the events using event delegation on your #form-group to delete the closest element select closest to your input button or in your case your sibling select. This ~ is a sibling selector and will select the sibling select.
A good idea would be to add a class to your select and use that instead as we have used your class .btn-minus for listening to click events, (in case if you have more than one select all will be selected)
$("form-group").on('click', '.btn-minus' , function() {
$(this).find('~select').remove();
});
Find the sibling select and remove
Edit 2
I have added a snippet using .closest() You can check it out. Closest will try to locate the parent div with class container and remove the select and the minus button
$(document).ready(function() {
$("#form-group").on('click', '.btn-minus' , function() {
$(this).closest('.container').remove();
});
$("#btnCompare").click(function() {
var count = $("#form-group > div.container").length;
if (count >= 4) {
alert("Only 4 options are allowed");
return false;
}
//you need to have data-id="number" for all div.container, add class container and data-id to all the divs having select and button
var label = $("#form-group > div.container").last().data('id')*1+1;
$("#form-group").append(
"<div class=container data-id="+label+"><select name='idSelect" + label + "' id='idSelect" + label + "'>" +
"<option>--Select Product" + label + "--</option>" +
'<option value="p1">Product 1</option>' +
'<option value="p2">Product 2</option>' +
"</select>" + ' <input type="button" value=" - " id="dltElement' + label + '" class="btn-minus pull-left" /></div>'
);
}); // Script for adding dropdown dynamically
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="form-group">
<input type=button id=btnCompare value=btnCompare />
<div class="container" data-id="1">
<select id="idSelect1" name="idSelect1">
<option>--Select Product1--</option>
<option value="p1">Product 1</option>
<option value="p2">Product 2</option>
</select>
<input disabled type="button" class="btn-minus pull-left" id="dltElement1" value=" - ">
</div>
<div class="container" data-id="2">
<select id="idSelect2" name="idSelect2">
<option>--Select Product2--</option>
<option value="p1">Product 1</option>
<option value="p2">Product 2</option>
</select>
<input disabled type="button" class="btn-minus pull-left" id="dltElement2" value=" - ">
</div>
</div>
Edit 3:
Please find updated snippet. you need to have data-id="number" for all div.container, add class container and data-id to all the divs having select and button.
It is hard to have what you want since you can delete from the middle as well. You can have an array of deleted objects and update it everytime you delete or add into that. In this code I have added to disbaled input delete for 1 and 2 so that you can add and delete other 2. You can play around the logic.
It counts the number of divs in DOM and then checks if you are trying to add more than the limit, It then picks the last added in DOM and increments the data-id to use it as a label for the next select
Currently what you are using is called a "direct" binding which will only attach to element that exist on the page at the time your code makes the event binding call.
You need to use Event Delegation using .on() delegated-events approach, when generating elements dynamically or manipulation selector (like removing and adding classes).
i.e.
$(document).on('event','selector',callback_function)
Example
As you have defined CSS class, use the to get the select element and perform removal operation.
$("#form-group").on('click', ".btn-minus", function(){
$(this).prev('select').remove();
});
$.fn.prev()
Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector.
you are assigning the <select> element an id that ends with a number, like this :
<select name='idSelect"+count+"' id='idSelect"+count+"'>
this means you end up with something like this :
<select name="idSelect1" id="idSelect1">
...
</select>
so the selector $("#idSelect") will never hit it unless it includes that number.
The part where you add the button :
'<input type="button" value=" - " id="dltElement' + count + '" class="btn-minus pull-left" />
has that same problem.
An easy way (though arguably not the best way) to achieve what you want is this :
function removeSelect(evt)
{
var selectBox = $(evt.currentTarget).parents(".group").find("select");
//do with select box as you will
}
$(document).ready(function() {
var count = 3;
$("#btnCompare").click(function() {
if (count > 4) {
alert("Only 4 options are allowed");
return false;
}
$("#form-group").append(
"<div class='group'>
"<select name='idSelect" + count + "' id='idSelect" + count + "'>" +
"<option>--Select Product" + counter + "--</option>" +
'<option value="p1">Product 1</option>' +
'<option value="p2">Product 2</option>' +
"</select>" + '<input type="button" value=" - " id="dltElement' + count + '" class="btn-minus pull-left" onclick="removeSelect(event)" /> </div>'
);
count++;
}); // Script for adding dropdown dynamically
});

Setting default value of <select> element

I have a table in my webpage that captures the details of a previous order history. The table has the following columns:
Order Date Review
Now, for the review, I want to have a select dropdown with some options. When user first launches the page, I want the previous rating to show up as default in the select dropdown. Here is what my code looks like:
tds.push( {
content: '<select id="clientReview" name="clientReview" value=' + obj.get("client_review") + '>' +
'<option value=1>Hate it!</option>' +
'<option value=2>Don't love it but don't hate it.</option>' +
'<option value=3>Fantastic!</option>'
});
I was expecting that setting the value in select would set the default value in the dropdown but that's not happening. I still see the first value as default. Any idea how I can fix that?
What about setting of value after inserting of HTML to document?
HTML:
<select id="dropdown">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<input id="textField" type="text" value="2" />
JavaScript:
(function() {
var dropdown$ = $('#dropdown'),
textField$ = $('#textField');
function changeVal() {
var val = parseInt(textField$.val());
if(!!val && val > 0 && val < 4) {
dropdown$.val(val);
}
}
textField$.on('keyup', changeVal);
changeVal();
})();​
DEMO
<option value="1" selected="selected">Text</option>
See:
http://www.w3.org/wiki/HTML/Elements/option#HTML_Attributes
http://www.w3schools.com/tags/att_option_selected.asp
Based on your code example I can assume that you'll use this HTML to insert somewhere later. In this case you can have something like next code:
tds.push( {
content: '<select id="clientReview" name="clientReview" data-value="' + obj.get("client_review") + '">' +
'<option value="1" >Hate it!</option>' +
'<option value="2" >Don\'t love it but don\'t hate it.</option>' +
'<option value="3" >Fantastic!</option>' +
'</select>'
});​
function insertDropdown(td$, dropdownHTML) {
var dropdown$ = $(dropdownHTML);
dropdown$.val(dropdown$.data('value'));
td$.html(dropdown$);
}
for(var i = 0, l = tds.length; i < l; i++) {
insertDropdown($('#td-' + i), tds[i].content);
}
DEMO

Categories