I have a number between 1 and 100 stored in a JavaScript variable:
var number_units = 3;`
I want to take the value of number_units and create this HTML selection field that many times:
var html = '<select class="form-control input-sm">'+
'<option value="1">1</option>'+
'<option value="2">2</option>'+
'<option value="3">3</option>'+
'<option value="4">4</option>'+
'</select>';
If number_units is 3, my code should create the selection field 3 times.
I then save the form that these selection fields are part of using AJAX to a PHP backend. So I need to figure out how to get all the selection values when my AJAX post is made and create a separate database entry for each value.
I need help with the JavaScript to create the selection field number_units times.
I can probably store in a hidden form field the count of selection fields and then give them a name with an increment number and iterate to that number in my back end to save each one. How would I go on from here?
You can use jQuery's $.parseHTML() to turn your field HTML into a DOM node. If you set an id value using a loop counter, you can refer to the fields later using the id.
In the following snippet, the id for each field has the form select-<number>. The first field is select-1, the second field is select-2, and so on. (I have changed the variable name number_units to numberUnits in keeping with JavaScript naming customs.)
var numberUnits = 3;
var fieldHTML = '<select class="form-control input-sm">' +
'<option value="1">1</option>' +
'<option value="2">2</option>' +
'<option value="3">3</option>' +
'<option value="4">4</option>' +
'</select>';
window.onload = function () {
var form = document.getElementById('bigForm'), // Field container.
fields = [];
for (var i = 1; i <= numberUnits; ++i) { // Iterate numberUnits times.
var field = $.parseHTML(fieldHTML)[0]; // Make field.
field.id = 'select-' + i; // Set field ID.
fields.push(field);
}
// Insert all fields at front of form.
$('#bigForm').prepend(fields);
// Test: set fields 2 and 3 to values 2 and 3.
$('#select-2').val(2);
$('#select-3').val(3);
};
#bigForm select {
margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="bigForm"></form>
// Get your form
var form = document.getElementById('#form');
// Repeat n times
for(var i = 0; i < number_units; i++){
// Create select element and assign it the class name
var select= document.createElement('select');
select.className = 'form-control input-sm';
// Create 4 option elements with value and text
var o1 = document.createElement('option');
o1.value = '1';
o1.text = '1';
var o2 = document.createElement('option');
o2.value = '2';
o2.text = '2';
var o3 = document.createElement('option');
o3.value = '3';
o3.text = '3';
var o4 = document.createElement('option');
o4.value = '4';
o4.text = '4';
// Append the option elements to the select element
select.appendChild(o1);
select.appendChild(o2);
select.appendChild(o3);
select.appendChild(o4);
// Append the select element to the form element
form.appendChild(s);
}
Check this fiddle http://jsfiddle.net/vgp8kx4g/
var number_units = window.prompt("Enter the number of options", 2);
if(number_units * 1 > 0) {
var html = '<select class="form-control input-sm">';
for(var i=1; i<= number_units; i++) {
html += '<option value="' + i + '">' + i + '</option>';
}
html += '</select>';
document.body.innerHTML = html;
}
Instead of document.body you can insert the html into any valid DOM element. If multiple values are taken change tag to <select multiple>
Don't know if this is what you are looking for but check this Fiddle
$("#save").on("click", function () {
$(".form-control").each(function () {
alert("Selected values: " + $(this).val());
});
});
Related
I need to select first option of select with jQuery. My code is a bit complex and can't figure out how to make it work. Thanks
Html:
'sortingHtml': '<select id="bc-sf-filter-top-sorting-select">{{sortingItems}}</select>'
Javascript:
BCSfFilter.prototype.buildFilterSorting = function() {
if (bcSfFilterTemplate.hasOwnProperty('sortingHtml')) {
jQ(this.selector.topSorting).html('');
var sortingArr = this.getSortingList();
if (sortingArr) {
// Build content
var sortingItemsHtml = '';
for (var k in sortingArr) {
sortingItemsHtml += '<option value="' + k +'">' + sortingArr[k] + '</option>';
}
sortingItemsHtml = '<option disabled="disabled" selected>Sort by</option>' + sortingItemsHtml
var html = bcSfFilterTemplate.sortingHtml.replace(/{{sortingItems}}/g, sortingItemsHtml);
jQ(this.selector.topSorting).html(html);
// Set current value
jQ(this.selector.topSorting + ' select').val(this.queryParams.sort);
}
}
};
Code to select the first option:
$("#bc-sf-filter-top-sorting-select").val($("#bc-sf-filter-top-sorting-select option:first").val());
$("#bc-sf-filter-top-sorting-select option:first").prop("selected", true);
Problem:
I have a dynamically created HTML table, that is used for filling out time sheets. It is created programmatically - there is no formal control. The design is a mix of CSS with text boxes being created through JavaScript. Now each 'row' of this table is in a class called 'divRow', and is separated from the others by having 'r' and the number of the row assigned to it as the class (i.e 'divRow r1', 'divRow r2', etc.).
Within each of these 'divRow's, I have cells in a class called 'divCell cc'. These do not have any identifiers in the class name. At the very last cell, I have a 'Total' column, which ideally calculates the total of the row and then adds it into a dynamically created text box.
What I have at the moment:
// Function to create textboxes on each of the table cells.
$(document).on("click", ".cc", function(){
var c = this;
if(($(c).children().length) === 0) {
var cellval = "";
if ($(c).text()) {
cellval = $(this).text();
if(cellval.length === 0) {
cellval = $(this).find('.tbltxt').val();
}
}
var twidth = $(c).width() + 21;
var tid= 't' + c.id;
if(tid.indexOf('x17') >= 0){
var thtml = "<input id='t" + c.id + "' type='text' Class='tbltxt' style='width: " + twidth + "px;' readonly />";
eval(spproc(spcol(t[getx(c.id)],thtml,tid,twidth)));
//var getRow = $(this).parent().attr('class'); - this gets the 'divRow r#' that it is currently on.
var arr = document.getElementsByClassName('cc');
var tot = 0;
for(var i = 0; i<arr.length; i++){
if(parseInt(arr[i].innerHTML) > 0){
tot += parseInt(arr[i].innerHTML);}
}
$('#t' + c.id).focus();
$(this).children().val(tot);
}else{
var thtml = "<input id='t" + c.id + "' type='text' Class='tbltxt' style='width: " + twidth + "px;' />";
eval(spproc(spcol(t[getx(c.id)],thtml,tid,twidth)));
$('#t' + c.id).focus();
$('#t' + c.id).val(cellval);
}}
});
As you can see, when the user clicks on the 'divCell cc', it creates a text box if one is not present. If the user clicks on the 17th column ('x17'), then it runs the for loop, and assigns the value of the total to the text box.
What I need to happen:
So what happens now is that the last cell sums the total of each cell that has a value. However, they are not row-dependent. I need it to calculate based on the row that it is currently 'on'. So if I'm calculating the 2nd row, I don't want the sum of the first, second and third being entered into the total, I just want the 2nd rows' values summed.
What I've tried:
I've tried looping through and using the 'divRow r#' number to try and get the items in the array that end in that number. (cells are given an id of 'x#y#' and the text boxes assigned to those cells are given an id of 'tx#y#').
I've tried getting elements by the cell class name, and then getting their parent class and sorting by that; didn't get far though, keep running into simple errors.
Let me know if you need more explanation.
Cheers,
Dee.
For anyone else that ever runs into this issue. I got it. I put the elements by the row class into an array, and then using that array, I got the childNodes from the row class. The reason the variable 'i' starts at 2 and not 0 is because I have 2 fields that are not counted in the TimeSheet table (Jobcode and description). It's working great now.
Cheers.
$(document).on("click", ".cc", function(){
var c = this;
if(($(c).children().length) === 0) {
var cellval = "";
if ($(c).text()) {
cellval = $(this).text();
if(cellval.length === 0) {
cellval = $(this).find('.tbltxt').val();
}
}
var twidth = $(c).width() + 21;
var tid= 't' + c.id;
if(tid.indexOf('x17') >= 0){
var thtml = "<input id='t" + c.id + "' type='text' Class='tbltxt' style='width: " + twidth + "px;' readonly />";
eval(spproc(spcol(t[getx(c.id)],thtml,tid,twidth)));
// Get current row that has focus
var getRow = $(this).parent().attr('class');
// Get the row number for passing through to the next statement
var rowPos = getRow.split('r', 5)[1];
// Get all the elements of the row class and assign them to the rowClass array
var rowClass = document.getElementsByClassName('r' + rowPos)
// Given the rowClass, get the children of the row class and assign them to the new array.
var arr = rowClass.item(0).childNodes
// Initialize the 'total' variable, and give it a value of 0
var tot = 0;
// Begin for loop, give 'i' the value of 2 so it starts from the 3rd index (avoid the Req Code and Description part of the table).
for(var i = 2; i<arr.length; i++){
if(parseInt(arr[i].innerHTML) > 0){
tot += parseInt(arr[i].innerHTML);}
}
// Assign focus to the 'Total' cell
$('#t' + c.id).focus();
// Assign the 'total' variable to the textbox that is dynamically created on the click.
$(this).children().val(tot);
}else{
var thtml = "<input id='t" + c.id + "' type='text' Class='tbltxt' style='width: " + twidth + "px;' />";
eval(spproc(spcol(t[getx(c.id)],thtml,tid,twidth)));
$('#t' + c.id).focus();
$('#t' + c.id).val(cellval);
}}
});
I'm using jquery and trying to tune my select menu builder to run much quicker.
I was using each and append, however I've since switched to a standard for loop and currently trying to convert my options from using append to concatenated string appended to my select option using .html(). I seem to be at a loss trying to convert my var option object back to an html string. Could someone please tell me what I might be doing wrong.
$.selectMenuBuilder = function(json) {
var myselect = $("#myselect");
var list = "<option value=\"\">> Select Account Number</option>";
var l= json.funding.length;
for(var i=0;i<l; i++) {
var funding = json.funding[i];
var option = $("<option value=\"" + funding.id + "\">" + funding.accountNumber + "</option>")
if(someLogic) {
option.attr("selected", "selected");
}
//Having trouble here converting option object back to html.
list += option.html();
}
list += "<option value=\"addnew\">+ New Account Number</option>";
myselect .html(list);
}
You can totally do away with using jQuery for creating the option elements (unless theres some other untold reason you're using it).
i.e. Instead of
var option = $("<option value=\"" + funding.id + "\">" + funding.accountNumber + "</option>")
if(someLogic) option.attr("selected", "selected");
You can do:
list += "<option value=\"" + funding.id + "\" "+ (someLogic?'selected':'') +">" + funding.accountNumber + "</option>"
Secondly, $(option).html() will return the innerHTML of the option element, not including the option tag name. For doing this in a cross-browser fashion, you can wrap the option in an outer element and use its innerHTML instead.
i.e.
$(option).wrap('<select/>').parent().html() will give you what you want.
If you want to keep the for loop but want something that looks a bit cleaner, try this:
function menuBuilder( json ) {
var list = [],
$select = $('#myselect'),
i = 0,
l = json.funding.length,
funding;
for ( ; i < l; i++ ) {
funding = json.funding[ i ];
list.push(
'<option '+ somelogic ? 'selected' : ''+' value='+ funding.id +'>'+
funding.accountNumber +
'</option>'
);
}
$select.append(
'<option>Select Account Number</option>'+
list.join('') +
'<option value="addnew">New Account Number</option>'
);
}
You can create elements more efficiently like this:
$.selectMenuBuilder = function (json) {
var myselect = $("#myselect");
var l = json.funding.length;
for (var i = 0; i < l; i++) {
var funding = json.funding[i];
var opt = $("<option/>", {
value: funding.id,
html: funding.accountNumber,
selected: somelogic ? true : false //Pre-select option
});
myselect.append(opt);
}
}
efficiency with pure JavaScript
example jsfiddle
selectMenuBuilder = function(json) {
var myselect = document.getElementById("myselect"),
listItem = document.createElement("option"),
l = json.funding.length,
someLogic = false; // placeholder
listItem.innerText = "> Select Account Number";
myselect.appendChild(listItem);
for (var i = 0; i < l; i++) {
var funding = json.funding[i];
var listItem = document.createElement("option");
if (someLogic) {
listItem.setAttribute("checked", "checked");
}
listItem.setAttribute("value", funding.id);
listItem.innerText = funding.accountNumber;
myselect.appendChild(listItem);
}
listItem = document.createElement("option")
listItem.setAttribute("value", "addnew");
listItem.innerText = "+ New Account Number";
myselect.appendChild(listItem);
}
Among other things I am trying to alert the selected value in the 'Amount' drop down box which is a list of numbers from 1 to 10. The list is generated and then inserted in to a div.
// generate the amount dropdown list
var dropdown = "<select name=\"amount\">";
for(var i=1; i <= MAX_PRINT; i++) {
dropdown = dropdown + "<option>" + i + "</option>"
}
dropdown = dropdown + "</select>";
jQuery("#" + divId).html("<div>Amount: " + dropdown + "</div></div>");
var amount = 1;
jQuery(document).ready(function() {
amount = jQuery("#amount").val();
alert(amount);
});
My question is: Why does it produce 'undefined' when I alert the amount? I am expecting it to return the selected number
Make sure you give your select an id—right now it just has a name. As a result, your jQuery('#amount') selector is not returning anything, which is why the alert is showing
undefined.
var dropdown = "<select id='amount' name='amount'>";
you are using amount = jQuery("#amount").val(); for that you have to give your dropdown an id
var dropdown = "<select name=\"amount\" id=\"amount\">";
DEMO
there are 2-3 Approach to get a selected value from <select>
use :selected
use .prop
use .attr
use this if this works for you:
jQuery(document).ready(function() {
var amount = jQuery("select[name='amount']").val();
alert(amount);
});
The id is missing on your dropdown.
// Generate the amount dropdown list
var dropdown = "<select id="amount" name=\"amount\">";
for(var i=1; i <= MAX_PRINT; i++) {
dropdown = dropdown + "<option>" + i + "</option>"
}
dropdown = dropdown + "</select>";
jQuery("#" + divId).html("<div>Amount: " + dropdown + "</div>/div>");
var amount = 1;
jQuery(document).ready(function() {
amount = jQuery("#amount").val();
alert(amount);
});
Ok here's what I am doing. Based on some dropdown value I am craeting another dropdown value.
Is it possible to display that dropdown in some specific area as I wish based on my existing code.
if (SelectedIndex == 2 || SelectedIndex == 5 || SelectedIndex == 7) {
$("#DomContainer").remove();
var MainContainer = document.createElement("Div");
MainContainer.id = "DomContainer";
$("body").append(MainContainer);
var Options = new Array();
for(var i=1;i<=28;i++){
Options.push(i);
}
AddDropDown(Options);
}
function AddDropDown(Options) {
var selectHTML = "<label>Day:</label> ";
selectHTML += "<select>";
for (i = 0; i < Options.length; i = i + 1) {
selectHTML += "<option value='" + Options[i] + "'>" + Options[i] + "</option>";
}
selectHTML += "</select>";
document.getElementById("DomContainer").innerHTML = selectHTML;
}
For example <div id="new_drop">//Display the drop down here </div>
Simply add a second parameter to AddDropDown for passing the ID of the container to which you want to insert your dropdown list:
function AddDropDown(Options, containerId) {
...
document.getElementById(containerId).innerHTML = selectHTML;
Then call it like this:
AddDropDown(Options, "new_drop");
(if I understand you correctly)
No need to remove and append elements from the DOM, just replace the existing element contents ... here's a simplified version.
// if "SelectedIndex" is one of the values in the array provided
if ($.inArray(SelectedIndex, [2,5,7])) {
$("#DomContainer").html("<label>Day:</label> "+inject_dropdown(28));
}
// Creates and returns a new drop-down based on the "length" provided
function inject_dropdown(length){
var selectHTML = "<select>";
for( i=1; i<=length; i++ ){
selectHTML += "<option value='" + i + "'>" + i + "</option>"
}
selectHTML += "</select>"
return selectHTML;
}
Replace the $('#DomContainer') selector with whatever selector identifies the place you want the new drop-down to appear.