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);
});
Related
I need my selection box to display the last selected item from db after user submits form in JS. Below is my code. The JS correctly shows the options from db. After submission the selection box reverts back to the first item and not selected.
$(document).ready(function () {
$.getJSON("getCompany.php", success = function(data)
{
var options = "Select Company";
for(var i = 0; i < data.length; i++)
{
options += "<option value='" + data[i].Value + "'>" + data[i].Company + "</option>";
}
$("#slctCom").append(options);
$("#slctCom").change();
});
});
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());
});
});
I have two select boxes. I'd like to populate the number of options of second select box based on the value inside the option the user chooses within the first select box. So for example the first select box has options (with values) ranging from 1-3. If the user selects the second option there should be 2 options in the second select box. If the third option is selected then there are three options. And if the first is selected there should be only one option.
I've managed to populate the second select box using a change event but what I'm trying to figure out how to remove excess options. So far its just appending options (as it should). So for example if I selected the third option and change back to the first, 2 & 3 should be removed.
HTML
<select>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select></select>
JS
$(function() {
$('select:eq(0)').on('change', function() {
for (var i = 1; i <= $('select:eq(0) option:selected').val(); i++) {
$('select(1)').append('<option val="' + i + '">' + i + '</option>');
}
});
});
You could do it using empty():
$(function () {
$('select:eq(0)').on('change', function () {
$('select:eq(1)').empty();
for (var i = 1; i <= $(this).val(); i++) {
$('select:eq(1)').append('<option val="' + i + '">' + i + '</option>');
}
});
});
But you could do it like this too:
$(function () {
$('select:eq(0)').on('change', function () {
$('select:eq(1)').html($(this).find('option:selected').prevAll().addBack().clone());
});
});
-DEMO-
Regarding performance, i'd use that instead: {even thought using document fragment could be faster than string concatenation, really not sure about that...}
$(function () {
var select1 = $('select')[1];
$('select').eq(0).on('change', function () {
for (var i = 1, z = this.value, str = ""; i <= z; i++) {
str += '<option val="' + i + '">' + i + '</option>';
}
select1.innerHTML = str;
});
});
-DEMO-
You could clear the inner html of the second select
$(function() {
$('select:eq(0)').on('change', function() {
$('select:eq(1)').html("");
for (var i = 1; i <= $('select:eq(0) option:selected').val(); i++) {
$('select:eq(1)').append('<option val="' + i + '">' + i + '</option>');
}
});
});
I am working on a script to add a row to a form using js.
this is the js script I have.
<script>
jQuery(function($) {
var $button = $('#add-row'),
$row = $('.timesheet-row').clone();
$button.click(function() {
$row.clone().insertAfter('#clone-row');
});
});
</script>
Then my form's elements are set up like this.
<div class="form-group col-lg-2">
<label>In Time</label>
<input class="form-control" type="datetime" id="intime" name="intime[]">
</div>
My problem is I cant seem to figure out how to retrieve the values of the form fields
here is the jfiddle
jfiddle
Updated jfiddle to revised code to post to php file
<?php
$pos= $_POST['position'];
$position = json_decode($pos);
echo $position;
echo "This should work";
If anymore than one line is found no response is returned.
Basically you'll need to iterate through the elements to get their values.
.each() will help you in that.
select an element input or select with their name and call .each() on it.
In .each() fetch the value of current element and store it.
Here's the updated jsFiddle.
I took the liberty of adding a button(id = "get-row-values") on whose click you'll see an alert with all the values of your inputs and selects in .timesheet-row.
Also I removed [] from the names of your inputs and selects.
$("#get-row-values").click(function () {
var position = "";
var unit = "";
var employee = "";
var intime = "";
var outtime = "";
$(".timesheet-row select[name=position]").each(function () {
position += " " + $(this).val();
});
$(".timesheet-row select[name=unit]").each(function () {
unit += " " + $(this).val();
});
$(".timesheet-row select[name=employee]").each(function () {
employee += " " + $(this).val();
});
$(".timesheet-row input[name=intime]").each(function () {
intime += " " + $(this).val();
});
$(".timesheet-row input[name=outtime]").each(function () {
outtime += " " + $(this).val();
});
alert("Positions : " + position + "\nUnits : " + unit + "\nEmployees : " + employee + "\nIntimes : " + intime + "\nOuttimes : " + outtime);
});
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.